[
  {
    "path": ".gitignore",
    "content": "# Prerequisites\n*.d\n\n# Compiled Object files\n*.slo\n*.lo\n*.o\n*.obj\n\n# Precompiled Headers\n*.gch\n*.pch\n\n# Compiled Dynamic libraries\n*.so\n*.dylib\n*.dll\n\n# Fortran module files\n*.mod\n*.smod\n\n# Compiled Static libraries\n*.lai\n*.la\n*.a\n*.lib\n\n# Executables\n*.exe\n*.out\n*.app\n*.perfetto\n*.spec\n\n*.vs\nx64/\n*.log\nBin/\n*.user\n/vc2019/*.aps\n\nsrc/MixDevice.h\n\nperf-doctor-*"
  },
  {
    "path": "3rdparty/Cinder-VNM/README.md",
    "content": "# Cinder-VNM\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/cinderblock.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<cinder>\n<block\n\tname=\"vnm\"\n\tid=\"org.jing.vnm\"\n\tauthor=\"Vinjn Zhang\"\n\tlicense=\"MIT\"\n\tsummary=\"Keep it simple and happy\"\n\tcore=\"false\"\n\t>\n\t<sourcePattern>src/*.*</sourcePattern>\n\t<headerPattern>include/*.*</headerPattern>\n\t<includePath>include</includePath>\n\t<includePath>ui</includePath>\n\t<includePath>ui/implot</includePath>\n\t<includePath>../</includePath>\n</block>\n<template>templates/Melo Scene/template.xml</template>\n<template>templates/Minimalist VNM/template.xml</template>\n<template>templates/DepthSensor VNM/template.xml</template>\n<template>templates/NonGame/template.xml</template>\n</cinder>"
  },
  {
    "path": "3rdparty/Cinder-VNM/imgui_remote_client/imgui/detector.js",
    "content": "/**\n * @author alteredq / http://alteredqualia.com/\n * @author mr.doob / http://mrdoob.com/\n */\n\nvar Detector = {\n\n\tcanvas: !! window.CanvasRenderingContext2D,\n\twebgl: ( function () { try { var canvas = document.createElement( 'canvas' ); return !! window.WebGLRenderingContext && ( canvas.getContext( 'webgl' ) || canvas.getContext( 'experimental-webgl' ) ); } catch( e ) { return false; } } )(),\n\tworkers: !! window.Worker,\n\tfileapi: window.File && window.FileReader && window.FileList && window.Blob,\n\n\tgetWebGLErrorMessage: function () {\n\n\t\tvar element = document.createElement( 'div' );\n\t\telement.id = 'webgl-error-message';\n\t\telement.style.fontFamily = 'monospace';\n\t\telement.style.fontSize = '13px';\n\t\telement.style.fontWeight = 'normal';\n\t\telement.style.textAlign = 'center';\n\t\telement.style.background = '#fff';\n\t\telement.style.color = '#000';\n\t\telement.style.padding = '1.5em';\n\t\telement.style.width = '400px';\n\t\telement.style.margin = '5em auto 0';\n\n\t\tif ( ! this.webgl ) {\n\n\t\t\telement.innerHTML = window.WebGLRenderingContext ? [\n\t\t\t\t'Your graphics card does not seem to support <a href=\"http://khronos.org/webgl/wiki/Getting_a_WebGL_Implementation\" style=\"color:#000\">WebGL</a>.<br />',\n\t\t\t\t'Find out how to get it <a href=\"http://get.webgl.org/\" style=\"color:#000\">here</a>.'\n\t\t\t].join( '\\n' ) : [\n\t\t\t\t'Your browser does not seem to support <a href=\"http://khronos.org/webgl/wiki/Getting_a_WebGL_Implementation\" style=\"color:#000\">WebGL</a>.<br/>',\n\t\t\t\t'Find out how to get it <a href=\"http://get.webgl.org/\" style=\"color:#000\">here</a>.'\n\t\t\t].join( '\\n' );\n\n\t\t}\n\n\t\treturn element;\n\n\t},\n\n\taddGetWebGLMessage: function ( parameters ) {\n\n\t\tvar parent, id, element;\n\n\t\tparameters = parameters || {};\n\n\t\tparent = parameters.parent !== undefined ? parameters.parent : document.body;\n\t\tid = parameters.id !== undefined ? parameters.id : 'oldie';\n\n\t\telement = Detector.getWebGLErrorMessage();\n\t\telement.id = id;\n\n\t\tparent.appendChild( element );\n\n\t}\n\n};"
  },
  {
    "path": "3rdparty/Cinder-VNM/imgui_remote_client/imgui/lz4.js",
    "content": "/*! lz4.js v0.1.0 Released under the MIT license. https://github.com/ukyo/lz4.js/LICENSE */\nvar lz4 = {};\n(function() {\n    function e(a) {\n        throw a;\n    }\n    var i = void 0,\n        l = !0,\n        m = null,\n        p = !1;\n\n    function q() {\n        return function() {}\n    }\n    var r = {\n            TOTAL_MEMORY: 13656760\n        },\n        aa = {},\n        s;\n    for (s in r) r.hasOwnProperty(s) && (aa[s] = r[s]);\n    var ba = \"object\" === typeof process && \"function\" === typeof require,\n        ca = \"object\" === typeof window,\n        ea = \"function\" === typeof importScripts,\n        fa = !ca && !ba && !ea;\n    if (ba) {\n        r.print = function(a) {\n            process.stdout.write(a + \"\\n\")\n        };\n        r.printErr = function(a) {\n            process.stderr.write(a + \"\\n\")\n        };\n        var ga = require(\"fs\"),\n            ha = require(\"path\");\n        r.read = function(a, b) {\n            var a = ha.normalize(a),\n                c = ga.readFileSync(a);\n            !c && a != ha.resolve(a) && (a = path.join(__dirname, \"..\", \"src\", a), c = ga.readFileSync(a));\n            c && !b && (c = c.toString());\n            return c\n        };\n        r.readBinary = function(a) {\n            return r.read(a, l)\n        };\n        r.load = function(a) {\n            ia(read(a))\n        };\n        r.arguments = process.argv.slice(2);\n        module.exports = r\n    } else fa ? (r.print = print, \"undefined\" != typeof printErr &&\n        (r.printErr = printErr), r.read = \"undefined\" != typeof read ? read : function() {\n            e(\"no read() available (jsc?)\")\n        }, r.readBinary = function(a) {\n            return read(a, \"binary\")\n        }, \"undefined\" != typeof scriptArgs ? r.arguments = scriptArgs : \"undefined\" != typeof arguments && (r.arguments = arguments), this.Module = r, eval(\"if (typeof gc === 'function' && gc.toString().indexOf('[native code]') > 0) var gc = undefined\")) : ca || ea ? (r.read = function(a) {\n            var b = new XMLHttpRequest;\n            b.open(\"GET\", a, p);\n            b.send(m);\n            return b.responseText\n        }, \"undefined\" != typeof arguments &&\n        (r.arguments = arguments), \"undefined\" !== typeof console ? (r.print = function(a) {\n            console.log(a)\n        }, r.printErr = function(a) {\n            console.log(a)\n        }) : r.print = q(), ca ? this.Module = r : r.load = importScripts) : e(\"Unknown runtime environment. Where are we?\");\n\n    function ia(a) {\n        eval.call(m, a)\n    }\n    \"undefined\" == !r.load && r.read && (r.load = function(a) {\n        ia(r.read(a))\n    });\n    r.print || (r.print = q());\n    r.printErr || (r.printErr = r.print);\n    r.arguments || (r.arguments = []);\n    r.print = r.print;\n    r.P = r.printErr;\n    r.preRun = [];\n    r.postRun = [];\n    for (s in aa) aa.hasOwnProperty(s) && (r[s] = aa[s]);\n\n    function ja() {\n        return u\n    }\n\n    function ka(a) {\n        u = a\n    }\n\n    function la(a) {\n        switch (a) {\n            case \"i1\":\n            case \"i8\":\n                return 1;\n            case \"i16\":\n                return 2;\n            case \"i32\":\n                return 4;\n            case \"i64\":\n                return 8;\n            case \"float\":\n                return 4;\n            case \"double\":\n                return 8;\n            default:\n                return \"*\" === a[a.length - 1] ? ma : \"i\" === a[0] ? (a = parseInt(a.substr(1)), w(0 === a % 8), a / 8) : 0\n        }\n    }\n\n    function na(a, b, c) {\n        c && c.length ? (c.splice || (c = Array.prototype.slice.call(c)), c.splice(0, 0, b), r[\"dynCall_\" + a].apply(m, c)) : r[\"dynCall_\" + a].call(m, b)\n    }\n    var oa;\n\n    function pa() {\n        var a = [],\n            b = 0;\n        this.ea = function(c) {\n            c &= 255;\n            if (0 == a.length) {\n                if (0 == (c & 128)) return String.fromCharCode(c);\n                a.push(c);\n                b = 192 == (c & 224) ? 1 : 224 == (c & 240) ? 2 : 3;\n                return \"\"\n            }\n            if (b && (a.push(c), b--, 0 < b)) return \"\";\n            var c = a[0],\n                d = a[1],\n                f = a[2],\n                g = a[3];\n            2 == a.length ? c = String.fromCharCode((c & 31) << 6 | d & 63) : 3 == a.length ? c = String.fromCharCode((c & 15) << 12 | (d & 63) << 6 | f & 63) : (c = (c & 7) << 18 | (d & 63) << 12 | (f & 63) << 6 | g & 63, c = String.fromCharCode(Math.floor((c - 65536) / 1024) + 55296, (c - 65536) % 1024 + 56320));\n            a.length = 0;\n            return c\n        };\n        this.Sa = function(a) {\n            for (var a =\n                    unescape(encodeURIComponent(a)), b = [], f = 0; f < a.length; f++) b.push(a.charCodeAt(f));\n            return b\n        }\n    }\n\n    function qa(a) {\n        var b = u;\n        u = u + a | 0;\n        u = u + 7 & -8;\n        return b\n    }\n\n    function ra(a) {\n        var b = x;\n        x = x + a | 0;\n        x = x + 7 & -8;\n        return b\n    }\n\n    function ta(a) {\n        var b = y;\n        y = y + a | 0;\n        y = y + 7 & -8;\n        y >= ua && B(\"Cannot enlarge memory arrays in asm.js. Either (1) compile with -s TOTAL_MEMORY=X with X higher than the current value \" + ua + \", or (2) set Module.TOTAL_MEMORY before the program runs.\");\n        return b\n    }\n\n    function va(a, b) {\n        return Math.ceil(a / (b ? b : 8)) * (b ? b : 8)\n    }\n    var ma = 4,\n        wa = {},\n        xa = p,\n        C, ya;\n\n    function w(a, b) {\n        a || B(\"Assertion failed: \" + b)\n    }\n    r.ccall = function(a, b, c, d) {\n        return za(Aa(a), b, c, d)\n    };\n\n    function Aa(a) {\n        try {\n            var b = r[\"_\" + a];\n            b || (b = eval(\"_\" + a))\n        } catch (c) {}\n        w(b, \"Cannot call unknown function \" + a + \" (perhaps LLVM optimizations or closure removed it?)\");\n        return b\n    }\n\n    function za(a, b, c, d) {\n        function f(a, b) {\n            if (\"string\" == b) {\n                if (a === m || a === i || 0 === a) return 0;\n                a = D(a);\n                b = \"array\"\n            }\n            if (\"array\" == b) {\n                g || (g = ja());\n                var c = qa(a.length);\n                Ba(a, c);\n                return c\n            }\n            return a\n        }\n        var g = 0,\n            h = 0,\n            d = d ? d.map(function(a) {\n                return f(a, c[h++])\n            }) : [];\n        a = a.apply(m, d);\n        \"string\" == b ? b = Ca(a) : (w(\"array\" != b), b = a);\n        g && ka(g);\n        return b\n    }\n    r.cwrap = function(a, b, c) {\n        var d = Aa(a);\n        return function() {\n            return za(d, b, c, Array.prototype.slice.call(arguments))\n        }\n    };\n\n    function Da(a, b, c) {\n        c = c || \"i8\";\n        \"*\" === c.charAt(c.length - 1) && (c = \"i32\");\n        switch (c) {\n            case \"i1\":\n                F[a] = b;\n                break;\n            case \"i8\":\n                F[a] = b;\n                break;\n            case \"i16\":\n                G[a >> 1] = b;\n                break;\n            case \"i32\":\n                H[a >> 2] = b;\n                break;\n            case \"i64\":\n                ya = [b >>> 0, (C = b, 1 <= +Ea(C) ? 0 < C ? (Fa(+Ga(C / 4294967296), 4294967295) | 0) >>> 0 : ~~+Ha((C - +(~~C >>> 0)) / 4294967296) >>> 0 : 0)];\n                H[a >> 2] = ya[0];\n                H[a + 4 >> 2] = ya[1];\n                break;\n            case \"float\":\n                Ia[a >> 2] = b;\n                break;\n            case \"double\":\n                Ja[a >> 3] = b;\n                break;\n            default:\n                B(\"invalid type for setValue: \" + c)\n        }\n    }\n    r.setValue = Da;\n    r.getValue = function(a, b) {\n        b = b || \"i8\";\n        \"*\" === b.charAt(b.length - 1) && (b = \"i32\");\n        switch (b) {\n            case \"i1\":\n                return F[a];\n            case \"i8\":\n                return F[a];\n            case \"i16\":\n                return G[a >> 1];\n            case \"i32\":\n                return H[a >> 2];\n            case \"i64\":\n                return H[a >> 2];\n            case \"float\":\n                return Ia[a >> 2];\n            case \"double\":\n                return Ja[a >> 3];\n            default:\n                B(\"invalid type for setValue: \" + b)\n        }\n        return m\n    };\n    var I = 2,\n        Ka = 4;\n    r.ALLOC_NORMAL = 0;\n    r.ALLOC_STACK = 1;\n    r.ALLOC_STATIC = I;\n    r.ALLOC_DYNAMIC = 3;\n    r.ALLOC_NONE = Ka;\n\n    function K(a, b, c, d) {\n        var f, g;\n        \"number\" === typeof a ? (f = l, g = a) : (f = p, g = a.length);\n        var h = \"string\" === typeof b ? b : m,\n            c = c == Ka ? d : [L, qa, ra, ta][c === i ? I : c](Math.max(g, h ? 1 : b.length));\n        if (f) {\n            d = c;\n            w(0 == (c & 3));\n            for (a = c + (g & -4); d < a; d += 4) H[d >> 2] = 0;\n            for (a = c + g; d < a;) F[d++ | 0] = 0;\n            return c\n        }\n        if (\"i8\" === h) return a.subarray || a.slice ? M.set(a, c) : M.set(new Uint8Array(a), c), c;\n        for (var d = 0, k, t; d < g;) {\n            var j = a[d];\n            \"function\" === typeof j && (j = wa.ld(j));\n            f = h || b[d];\n            0 === f ? d++ : (\"i64\" == f && (f = \"i32\"), Da(c + d, j, f), t !== f && (k = la(f), t = f), d += k)\n        }\n        return c\n    }\n    r.allocate = K;\n\n    function Ca(a, b) {\n        for (var c = p, d, f = 0;;) {\n            d = M[a + f | 0];\n            if (128 <= d) c = l;\n            else if (0 == d && !b) break;\n            f++;\n            if (b && f == b) break\n        }\n        b || (b = f);\n        var g = \"\";\n        if (!c) {\n            for (; 0 < b;) d = String.fromCharCode.apply(String, M.subarray(a, a + Math.min(b, 1024))), g = g ? g + d : d, a += 1024, b -= 1024;\n            return g\n        }\n        c = new pa;\n        for (f = 0; f < b; f++) d = M[a + f | 0], g += c.ea(d);\n        return g\n    }\n    r.Pointer_stringify = Ca;\n    r.UTF16ToString = function(a) {\n        for (var b = 0, c = \"\";;) {\n            var d = G[a + 2 * b >> 1];\n            if (0 == d) return c;\n            ++b;\n            c += String.fromCharCode(d)\n        }\n    };\n    r.stringToUTF16 = function(a, b) {\n        for (var c = 0; c < a.length; ++c) G[b + 2 * c >> 1] = a.charCodeAt(c);\n        G[b + 2 * a.length >> 1] = 0\n    };\n    r.UTF32ToString = function(a) {\n        for (var b = 0, c = \"\";;) {\n            var d = H[a + 4 * b >> 2];\n            if (0 == d) return c;\n            ++b;\n            65536 <= d ? (d -= 65536, c += String.fromCharCode(55296 | d >> 10, 56320 | d & 1023)) : c += String.fromCharCode(d)\n        }\n    };\n    r.stringToUTF32 = function(a, b) {\n        for (var c = 0, d = 0; d < a.length; ++d) {\n            var f = a.charCodeAt(d);\n            if (55296 <= f && 57343 >= f) var g = a.charCodeAt(++d),\n                f = 65536 + ((f & 1023) << 10) | g & 1023;\n            H[b + 4 * c >> 2] = f;\n            ++c\n        }\n        H[b + 4 * c >> 2] = 0\n    };\n\n    function La(a) {\n        try {\n            \"number\" === typeof a && (a = Ca(a));\n            if (\"_\" !== a[0] || \"_\" !== a[1] || \"Z\" !== a[2]) return a;\n            switch (a[3]) {\n                case \"n\":\n                    return \"operator new()\";\n                case \"d\":\n                    return \"operator delete()\"\n            }\n            var b = 3,\n                c = {\n                    v: \"void\",\n                    b: \"bool\",\n                    c: \"char\",\n                    s: \"short\",\n                    i: \"int\",\n                    l: \"long\",\n                    f: \"float\",\n                    d: \"double\",\n                    w: \"wchar_t\",\n                    a: \"signed char\",\n                    h: \"unsigned char\",\n                    t: \"unsigned short\",\n                    j: \"unsigned int\",\n                    m: \"unsigned long\",\n                    x: \"long long\",\n                    y: \"unsigned long long\",\n                    z: \"...\"\n                },\n                d = [],\n                f = l,\n                g = function(h, t, j) {\n                    var t = t || Infinity,\n                        z = \"\",\n                        A = [],\n                        n;\n                    if (\"N\" === a[b]) {\n                        b++;\n                        \"K\" === a[b] && b++;\n                        for (n = [];\n                            \"E\" !== a[b];)\n                            if (\"S\" === a[b]) {\n                                b++;\n                                var v = a.indexOf(\"_\", b);\n                                n.push(d[a.substring(b, v) || 0] || \"?\");\n                                b = v + 1\n                            } else if (\"C\" === a[b]) n.push(n[n.length - 1]), b += 2;\n                        else {\n                            var v = parseInt(a.substr(b)),\n                                E = v.toString().length;\n                            if (!v || !E) {\n                                b--;\n                                break\n                            }\n                            var da = a.substr(b + E, v);\n                            n.push(da);\n                            d.push(da);\n                            b += E + v\n                        }\n                        b++;\n                        n = n.join(\"::\");\n                        t--;\n                        if (0 === t) return h ? [n] : n\n                    } else if ((\"K\" === a[b] || f && \"L\" === a[b]) && b++, v = parseInt(a.substr(b))) E = v.toString().length, n = a.substr(b + E, v), b += E + v;\n                    f = p;\n                    \"I\" === a[b] ? (b++, v = g(l), E = g(l, 1, l), z += E[0] + \" \" + n + \"<\" + v.join(\", \") +\n                        \">\") : z = n;\n                    a: for (; b < a.length && 0 < t--;)\n                        if (n = a[b++], n in c) A.push(c[n]);\n                        else switch (n) {\n                            case \"P\":\n                                A.push(g(l, 1, l)[0] + \"*\");\n                                break;\n                            case \"R\":\n                                A.push(g(l, 1, l)[0] + \"&\");\n                                break;\n                            case \"L\":\n                                b++;\n                                v = a.indexOf(\"E\", b) - b;\n                                A.push(a.substr(b, v));\n                                b += v + 2;\n                                break;\n                            case \"A\":\n                                v = parseInt(a.substr(b));\n                                b += v.toString().length;\n                                \"_\" !== a[b] && e(\"?\");\n                                b++;\n                                A.push(g(l, 1, l)[0] + \" [\" + v + \"]\");\n                                break;\n                            case \"E\":\n                                break a;\n                            default:\n                                z += \"?\" + n;\n                                break a\n                        }!j && (1 === A.length && \"void\" === A[0]) && (A = []);\n                    return h ? A : z + (\"(\" + A.join(\", \") + \")\")\n                };\n            return g()\n        } catch (h) {\n            return a\n        }\n    }\n\n    function Ma() {\n        var a = Error().stack;\n        return a ? a.replace(/__Z[\\w\\d_]+/g, function(a) {\n            var c = La(a);\n            return a === c ? a : a + \" [\" + c + \"]\"\n        }) : \"(no stack trace available)\"\n    }\n    var F, M, G, Na, H, Oa, Ia, Ja, Pa = 0,\n        x = 0,\n        Qa = 0,\n        u = 0,\n        Ra = 0,\n        Sa = 0,\n        y = 0,\n        ua = r.TOTAL_MEMORY || 16777216;\n    w(\"undefined\" !== typeof Int32Array && \"undefined\" !== typeof Float64Array && !!(new Int32Array(1)).subarray && !!(new Int32Array(1)).set, \"Cannot fallback to non-typed array case: Code is too specialized\");\n    var N = new ArrayBuffer(ua);\n    F = new Int8Array(N);\n    G = new Int16Array(N);\n    H = new Int32Array(N);\n    M = new Uint8Array(N);\n    Na = new Uint16Array(N);\n    Oa = new Uint32Array(N);\n    Ia = new Float32Array(N);\n    Ja = new Float64Array(N);\n    H[0] = 255;\n    w(255 === M[0] && 0 === M[3], \"Typed arrays 2 must be run on a little-endian system\");\n    r.HEAP = i;\n    r.HEAP8 = F;\n    r.HEAP16 = G;\n    r.HEAP32 = H;\n    r.HEAPU8 = M;\n    r.HEAPU16 = Na;\n    r.HEAPU32 = Oa;\n    r.HEAPF32 = Ia;\n    r.HEAPF64 = Ja;\n\n    function O(a) {\n        for (; 0 < a.length;) {\n            var b = a.shift();\n            if (\"function\" == typeof b) b();\n            else {\n                var c = b.J;\n                \"number\" === typeof c ? b.aa === i ? na(\"v\", c) : na(\"vi\", c, [b.aa]) : c(b.aa === i ? m : b.aa)\n            }\n        }\n    }\n    var Ta = [],\n        P = [],\n        Ua = [],\n        Va = [],\n        Wa = [],\n        Xa = p;\n\n    function Ya(a) {\n        Ta.unshift(a)\n    }\n    r.addOnPreRun = r.bd = Ya;\n    r.addOnInit = r.Zc = function(a) {\n        P.unshift(a)\n    };\n    r.addOnPreMain = r.ad = function(a) {\n        Ua.unshift(a)\n    };\n    r.addOnExit = r.Yc = function(a) {\n        Va.unshift(a)\n    };\n\n    function Za(a) {\n        Wa.unshift(a)\n    }\n    r.addOnPostRun = r.$c = Za;\n\n    function D(a, b, c) {\n        a = (new pa).Sa(a);\n        c && (a.length = c);\n        b || a.push(0);\n        return a\n    }\n    r.intArrayFromString = D;\n    r.intArrayToString = function(a) {\n        for (var b = [], c = 0; c < a.length; c++) {\n            var d = a[c];\n            255 < d && (d &= 255);\n            b.push(String.fromCharCode(d))\n        }\n        return b.join(\"\")\n    };\n    r.writeStringToMemory = function(a, b, c) {\n        a = D(a, c);\n        for (c = 0; c < a.length;) F[b + c | 0] = a[c], c += 1\n    };\n\n    function Ba(a, b) {\n        for (var c = 0; c < a.length; c++) F[b + c | 0] = a[c]\n    }\n    r.writeArrayToMemory = Ba;\n    r.writeAsciiToMemory = function(a, b, c) {\n        for (var d = 0; d < a.length; d++) F[b + d | 0] = a.charCodeAt(d);\n        c || (F[b + a.length | 0] = 0)\n    };\n    Math.imul || (Math.imul = function(a, b) {\n        var c = a & 65535,\n            d = b & 65535;\n        return c * d + ((a >>> 16) * d + c * (b >>> 16) << 16) | 0\n    });\n    Math.nd = Math.imul;\n    var Ea = Math.abs,\n        Ha = Math.ceil,\n        Ga = Math.floor,\n        Fa = Math.min,\n        Q = 0,\n        $a = m,\n        ab = m;\n\n    function bb() {\n        Q++;\n        r.monitorRunDependencies && r.monitorRunDependencies(Q)\n    }\n    r.addRunDependency = bb;\n\n    function cb() {\n        Q--;\n        r.monitorRunDependencies && r.monitorRunDependencies(Q);\n        if (0 == Q && ($a !== m && (clearInterval($a), $a = m), ab)) {\n            var a = ab;\n            ab = m;\n            a()\n        }\n    }\n    r.removeRunDependency = cb;\n    r.preloadedImages = {};\n    r.preloadedAudios = {};\n    Pa = 8;\n    x = Pa + 528;\n    P.push({\n        J: function() {\n            db()\n        }\n    });\n    K([0, 0, 0, 0, 3, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], \"i8\", Ka, 8);\n    var eb = va(K(12, \"i8\", I), 8);\n    w(0 == eb % 8);\n    r._memset = fb;\n    r._memcpy = gb;\n    var hb = K([8, 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, 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, 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, 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, 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, 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, 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, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0,\n        1, 0, 3, 0, 1, 0, 2, 0, 1, 0\n    ], \"i8\", I);\n    r._llvm_cttz_i32 = ib;\n    var jb = 0;\n\n    function kb(a) {\n        return H[jb >> 2] = a\n    }\n\n    function lb(a) {\n        lb.Ka || (y = y + 4095 & -4096, lb.Ka = l, w(ta), lb.Ia = ta, ta = function() {\n            B(\"cannot dynamically allocate, sbrk now has control\")\n        });\n        var b = y;\n        0 != a && lb.Ia(a);\n        return b\n    }\n    var R = {\n        L: 1,\n        Q: 2,\n        Lc: 3,\n        Gb: 4,\n        D: 5,\n        ma: 6,\n        Ya: 7,\n        dc: 8,\n        Da: 9,\n        nb: 10,\n        ia: 11,\n        Vc: 11,\n        Fa: 12,\n        Ca: 13,\n        zb: 14,\n        pc: 15,\n        lb: 16,\n        ja: 17,\n        Wc: 18,\n        ka: 19,\n        rc: 20,\n        Y: 21,\n        C: 22,\n        Zb: 23,\n        Ea: 24,\n        vc: 25,\n        Sc: 26,\n        Ab: 27,\n        lc: 28,\n        $: 29,\n        Ic: 30,\n        Sb: 31,\n        Bc: 32,\n        wb: 33,\n        Fc: 34,\n        hc: 42,\n        Db: 43,\n        ob: 44,\n        Jb: 45,\n        Kb: 46,\n        Lb: 47,\n        Rb: 48,\n        Tc: 49,\n        bc: 50,\n        Ib: 51,\n        tb: 35,\n        ec: 37,\n        eb: 52,\n        hb: 53,\n        Xc: 54,\n        $b: 55,\n        ib: 56,\n        jb: 57,\n        ub: 35,\n        kb: 59,\n        nc: 60,\n        cc: 61,\n        Pc: 62,\n        mc: 63,\n        ic: 64,\n        jc: 65,\n        Hc: 66,\n        fc: 67,\n        ab: 68,\n        Mc: 69,\n        pb: 70,\n        Cc: 71,\n        Ub: 72,\n        xb: 73,\n        gb: 74,\n        wc: 76,\n        fb: 77,\n        Gc: 78,\n        Mb: 79,\n        Nb: 80,\n        Qb: 81,\n        Pb: 82,\n        Ob: 83,\n        oc: 38,\n        la: 39,\n        Vb: 36,\n        Z: 40,\n        xc: 95,\n        Ac: 96,\n        sb: 104,\n        ac: 105,\n        bb: 97,\n        Ec: 91,\n        tc: 88,\n        kc: 92,\n        Jc: 108,\n        rb: 111,\n        Za: 98,\n        qb: 103,\n        Yb: 101,\n        Wb: 100,\n        Qc: 110,\n        Bb: 112,\n        Cb: 113,\n        Fb: 115,\n        cb: 114,\n        vb: 89,\n        Tb: 90,\n        Dc: 93,\n        Kc: 94,\n        $a: 99,\n        Xb: 102,\n        Hb: 106,\n        qc: 107,\n        Rc: 109,\n        Uc: 87,\n        yb: 122,\n        Nc: 116,\n        uc: 95,\n        gc: 123,\n        Eb: 84,\n        yc: 75,\n        mb: 125,\n        sc: 131,\n        zc: 130,\n        Oc: 86\n    };\n    r._strlen = mb;\n    var nb = {\n            \"0\": \"Success\",\n            1: \"Not super-user\",\n            2: \"No such file or directory\",\n            3: \"No such process\",\n            4: \"Interrupted system call\",\n            5: \"I/O error\",\n            6: \"No such device or address\",\n            7: \"Arg list too long\",\n            8: \"Exec format error\",\n            9: \"Bad file number\",\n            10: \"No children\",\n            11: \"No more processes\",\n            12: \"Not enough core\",\n            13: \"Permission denied\",\n            14: \"Bad address\",\n            15: \"Block device required\",\n            16: \"Mount device busy\",\n            17: \"File exists\",\n            18: \"Cross-device link\",\n            19: \"No such device\",\n            20: \"Not a directory\",\n            21: \"Is a directory\",\n            22: \"Invalid argument\",\n            23: \"Too many open files in system\",\n            24: \"Too many open files\",\n            25: \"Not a typewriter\",\n            26: \"Text file busy\",\n            27: \"File too large\",\n            28: \"No space left on device\",\n            29: \"Illegal seek\",\n            30: \"Read only file system\",\n            31: \"Too many links\",\n            32: \"Broken pipe\",\n            33: \"Math arg out of domain of func\",\n            34: \"Math result not representable\",\n            35: \"File locking deadlock error\",\n            36: \"File or path name too long\",\n            37: \"No record locks available\",\n            38: \"Function not implemented\",\n            39: \"Directory not empty\",\n            40: \"Too many symbolic links\",\n            42: \"No message of desired type\",\n            43: \"Identifier removed\",\n            44: \"Channel number out of range\",\n            45: \"Level 2 not synchronized\",\n            46: \"Level 3 halted\",\n            47: \"Level 3 reset\",\n            48: \"Link number out of range\",\n            49: \"Protocol driver not attached\",\n            50: \"No CSI structure available\",\n            51: \"Level 2 halted\",\n            52: \"Invalid exchange\",\n            53: \"Invalid request descriptor\",\n            54: \"Exchange full\",\n            55: \"No anode\",\n            56: \"Invalid request code\",\n            57: \"Invalid slot\",\n            59: \"Bad font file fmt\",\n            60: \"Device not a stream\",\n            61: \"No data (for no delay io)\",\n            62: \"Timer expired\",\n            63: \"Out of streams resources\",\n            64: \"Machine is not on the network\",\n            65: \"Package not installed\",\n            66: \"The object is remote\",\n            67: \"The link has been severed\",\n            68: \"Advertise error\",\n            69: \"Srmount error\",\n            70: \"Communication error on send\",\n            71: \"Protocol error\",\n            72: \"Multihop attempted\",\n            73: \"Cross mount point (not really error)\",\n            74: \"Trying to read unreadable message\",\n            75: \"Value too large for defined data type\",\n            76: \"Given log. name not unique\",\n            77: \"f.d. invalid for this operation\",\n            78: \"Remote address changed\",\n            79: \"Can   access a needed shared lib\",\n            80: \"Accessing a corrupted shared lib\",\n            81: \".lib section in a.out corrupted\",\n            82: \"Attempting to link in too many libs\",\n            83: \"Attempting to exec a shared library\",\n            84: \"Illegal byte sequence\",\n            86: \"Streams pipe error\",\n            87: \"Too many users\",\n            88: \"Socket operation on non-socket\",\n            89: \"Destination address required\",\n            90: \"Message too long\",\n            91: \"Protocol wrong type for socket\",\n            92: \"Protocol not available\",\n            93: \"Unknown protocol\",\n            94: \"Socket type not supported\",\n            95: \"Not supported\",\n            96: \"Protocol family not supported\",\n            97: \"Address family not supported by protocol family\",\n            98: \"Address already in use\",\n            99: \"Address not available\",\n            100: \"Network interface is not configured\",\n            101: \"Network is unreachable\",\n            102: \"Connection reset by network\",\n            103: \"Connection aborted\",\n            104: \"Connection reset by peer\",\n            105: \"No buffer space available\",\n            106: \"Socket is already connected\",\n            107: \"Socket is not connected\",\n            108: \"Can't send after socket shutdown\",\n            109: \"Too many references\",\n            110: \"Connection timed out\",\n            111: \"Connection refused\",\n            112: \"Host is down\",\n            113: \"Host is unreachable\",\n            114: \"Socket already connected\",\n            115: \"Connection already in progress\",\n            116: \"Stale file handle\",\n            122: \"Quota exceeded\",\n            123: \"No medium (in tape drive)\",\n            125: \"Operation canceled\",\n            130: \"Previous owner died\",\n            131: \"State not recoverable\"\n        },\n        ob = [];\n\n    function pb(a, b) {\n        ob[a] = {\n            input: [],\n            G: [],\n            O: b\n        };\n        qb[a] = {\n            k: rb\n        }\n    }\n    var rb = {\n            open: function(a) {\n                var b = ob[a.e.U];\n                b || e(new S(R.ka));\n                a.p = b;\n                a.seekable = p\n            },\n            close: function(a) {\n                a.p.G.length && a.p.O.T(a.p, 10)\n            },\n            H: function(a, b, c, d) {\n                (!a.p || !a.p.O.ta) && e(new S(R.ma));\n                for (var f = 0, g = 0; g < d; g++) {\n                    var h;\n                    try {\n                        h = a.p.O.ta(a.p)\n                    } catch (k) {\n                        e(new S(R.D))\n                    }\n                    h === i && 0 === f && e(new S(R.ia));\n                    if (h === m || h === i) break;\n                    f++;\n                    b[c + g] = h\n                }\n                f && (a.e.timestamp = Date.now());\n                return f\n            },\n            write: function(a, b, c, d) {\n                (!a.p || !a.p.O.T) && e(new S(R.ma));\n                for (var f = 0; f < d; f++) try {\n                    a.p.O.T(a.p, b[c + f])\n                } catch (g) {\n                    e(new S(R.D))\n                }\n                d && (a.e.timestamp =\n                    Date.now());\n                return f\n            }\n        },\n        T = {\n            u: m,\n            Ba: 1,\n            X: 2,\n            ha: 3,\n            B: function() {\n                return T.createNode(m, \"/\", 16895, 0)\n            },\n            createNode: function(a, b, c, d) {\n                (24576 === (c & 61440) || 4096 === (c & 61440)) && e(new S(R.L));\n                T.u || (T.u = {\n                    dir: {\n                        e: {\n                            A: T.g.A,\n                            o: T.g.o,\n                            da: T.g.da,\n                            K: T.g.K,\n                            K: T.g.K,\n                            rename: T.g.rename,\n                            Aa: T.g.Aa,\n                            za: T.g.za,\n                            ya: T.g.ya,\n                            W: T.g.W\n                        },\n                        I: {\n                            F: T.k.F\n                        }\n                    },\n                    file: {\n                        e: {\n                            A: T.g.A,\n                            o: T.g.o\n                        },\n                        I: {\n                            F: T.k.F,\n                            H: T.k.H,\n                            write: T.k.write,\n                            na: T.k.na,\n                            va: T.k.va\n                        }\n                    },\n                    link: {\n                        e: {\n                            A: T.g.A,\n                            o: T.g.o,\n                            V: T.g.V\n                        },\n                        I: {}\n                    },\n                    qa: {\n                        e: {\n                            A: T.g.A,\n                            o: T.g.o\n                        },\n                        I: sb\n                    }\n                });\n                c = tb(a, b, c, d);\n                16384 === (c.mode & 61440) ? (c.g =\n                    T.u.dir.e, c.k = T.u.dir.I, c.n = {}) : 32768 === (c.mode & 61440) ? (c.g = T.u.file.e, c.k = T.u.file.I, c.n = [], c.S = T.X) : 40960 === (c.mode & 61440) ? (c.g = T.u.link.e, c.k = T.u.link.I) : 8192 === (c.mode & 61440) && (c.g = T.u.qa.e, c.k = T.u.qa.I);\n                c.timestamp = Date.now();\n                a && (a.n[b] = c);\n                return c\n            },\n            ba: function(a) {\n                a.S !== T.X && (a.n = Array.prototype.slice.call(a.n), a.S = T.X)\n            },\n            g: {\n                A: function(a) {\n                    var b = {};\n                    b.hd = 8192 === (a.mode & 61440) ? a.id : 1;\n                    b.od = a.id;\n                    b.mode = a.mode;\n                    b.td = 1;\n                    b.uid = 0;\n                    b.md = 0;\n                    b.U = a.U;\n                    b.size = 16384 === (a.mode & 61440) ? 4096 : 32768 === (a.mode & 61440) ? a.n.length :\n                        40960 === (a.mode & 61440) ? a.link.length : 0;\n                    b.dd = new Date(a.timestamp);\n                    b.sd = new Date(a.timestamp);\n                    b.gd = new Date(a.timestamp);\n                    b.Ja = 4096;\n                    b.ed = Math.ceil(b.size / b.Ja);\n                    return b\n                },\n                o: function(a, b) {\n                    b.mode !== i && (a.mode = b.mode);\n                    b.timestamp !== i && (a.timestamp = b.timestamp);\n                    if (b.size !== i) {\n                        T.ba(a);\n                        var c = a.n;\n                        if (b.size < c.length) c.length = b.size;\n                        else\n                            for (; b.size > c.length;) c.push(0)\n                    }\n                },\n                da: function() {\n                    e(ub[R.Q])\n                },\n                K: function(a, b, c, d) {\n                    return T.createNode(a, b, c, d)\n                },\n                rename: function(a, b, c) {\n                    if (16384 === (a.mode & 61440)) {\n                        var d;\n                        try {\n                            d = vb(b,\n                                c)\n                        } catch (f) {}\n                        if (d)\n                            for (var g in d.n) e(new S(R.la))\n                    }\n                    delete a.parent.n[a.name];\n                    a.name = c;\n                    b.n[c] = a;\n                    a.parent = b\n                },\n                Aa: function(a, b) {\n                    delete a.n[b]\n                },\n                za: function(a, b) {\n                    var c = vb(a, b),\n                        d;\n                    for (d in c.n) e(new S(R.la));\n                    delete a.n[b]\n                },\n                ya: function(a) {\n                    var b = [\".\", \"..\"],\n                        c;\n                    for (c in a.n) a.n.hasOwnProperty(c) && b.push(c);\n                    return b\n                },\n                W: function(a, b, c) {\n                    a = T.createNode(a, b, 41471, 0);\n                    a.link = c;\n                    return a\n                },\n                V: function(a) {\n                    40960 !== (a.mode & 61440) && e(new S(R.C));\n                    return a.link\n                }\n            },\n            k: {\n                H: function(a, b, c, d, f) {\n                    a = a.e.n;\n                    if (f >= a.length) return 0;\n                    d = Math.min(a.length -\n                        f, d);\n                    w(0 <= d);\n                    if (8 < d && a.subarray) b.set(a.subarray(f, f + d), c);\n                    else\n                        for (var g = 0; g < d; g++) b[c + g] = a[f + g];\n                    return d\n                },\n                write: function(a, b, c, d, f, g) {\n                    var h = a.e;\n                    h.timestamp = Date.now();\n                    a = h.n;\n                    if (d && 0 === a.length && 0 === f && b.subarray) return g && 0 === c ? (h.n = b, h.S = b.buffer === F.buffer ? T.Ba : T.ha) : (h.n = new Uint8Array(b.subarray(c, c + d)), h.S = T.ha), d;\n                    T.ba(h);\n                    for (a = h.n; a.length < f;) a.push(0);\n                    for (g = 0; g < d; g++) a[f + g] = b[c + g];\n                    return d\n                },\n                F: function(a, b, c) {\n                    1 === c ? b += a.position : 2 === c && 32768 === (a.e.mode & 61440) && (b += a.e.n.length);\n                    0 > b && e(new S(R.C));\n                    a.Va = [];\n                    return a.position = b\n                },\n                na: function(a, b, c) {\n                    T.ba(a.e);\n                    a = a.e.n;\n                    for (b += c; b > a.length;) a.push(0)\n                },\n                va: function(a, b, c, d, f, g, h) {\n                    32768 !== (a.e.mode & 61440) && e(new S(R.ka));\n                    a = a.e.n;\n                    if (!(h & 2) && (a.buffer === b || a.buffer === b.buffer)) f = p, d = a.byteOffset;\n                    else {\n                        if (0 < f || f + d < a.length) a = a.subarray ? a.subarray(f, f + d) : Array.prototype.slice.call(a, f, f + d);\n                        f = l;\n                        (d = L(d)) || e(new S(R.Fa));\n                        b.set(a, d)\n                    }\n                    return {\n                        wd: d,\n                        cd: f\n                    }\n                }\n            }\n        },\n        wb = K(1, \"i32*\", I),\n        xb = K(1, \"i32*\", I),\n        yb = K(1, \"i32*\", I),\n        zb = m,\n        qb = [m],\n        Ab = [m],\n        Bb = 1,\n        Cb = m,\n        Db = l,\n        S = m,\n        ub = {};\n\n    function U(a, b) {\n        a = Eb(\"/\", a);\n        b = b || {\n            fa: 0\n        };\n        8 < b.fa && e(new S(R.Z));\n        for (var c = Fb(a.split(\"/\").filter(function(a) {\n                return !!a\n            }), p), d = zb, f = \"/\", g = 0; g < c.length; g++) {\n            var h = g === c.length - 1;\n            if (h && b.parent) break;\n            d = vb(d, c[g]);\n            f = V(f + \"/\" + c[g]);\n            d.Pa && (d = d.B.root);\n            if (!h || b.N)\n                for (h = 0; 40960 === (d.mode & 61440);) {\n                    d = U(f, {\n                        N: p\n                    }).e;\n                    d.g.V || e(new S(R.C));\n                    var d = d.g.V(d),\n                        k = Eb;\n                    var t = /^(\\/?|)([\\s\\S]*?)((?:\\.{1,2}|[^\\/]+?|)(\\.[^.\\/]*|))(?:[\\/]*)$/.exec(f).slice(1),\n                        f = t[0],\n                        t = t[1];\n                    !f && !t ? f = \".\" : (t && (t = t.substr(0, t.length - 1)), f += t);\n                    f = k(f, d);\n                    d = U(f, {\n                        fa: b.fa\n                    }).e;\n                    40 < h++ && e(new S(R.Z))\n                }\n        }\n        return {\n            path: f,\n            e: d\n        }\n    }\n\n    function W(a) {\n        for (var b;;) {\n            if (a === a.parent) return a = a.B.Qa, !b ? a : \"/\" !== a[a.length - 1] ? a + \"/\" + b : a + b;\n            b = b ? a.name + \"/\" + b : a.name;\n            a = a.parent\n        }\n    }\n\n    function Gb(a, b) {\n        for (var c = 0, d = 0; d < b.length; d++) c = (c << 5) - c + b.charCodeAt(d) | 0;\n        return (a + c >>> 0) % Cb.length\n    }\n\n    function vb(a, b) {\n        var c = Hb(a, \"x\");\n        c && e(new S(c));\n        for (c = Cb[Gb(a.id, b)]; c; c = c.Ra) {\n            var d = c.name;\n            if (c.parent.id === a.id && d === b) return c\n        }\n        return a.g.da(a, b)\n    }\n\n    function tb(a, b, c, d) {\n        Ib || (Ib = function(a, b, c, d) {\n            this.id = Bb++;\n            this.name = b;\n            this.mode = c;\n            this.g = {};\n            this.k = {};\n            this.U = d;\n            this.B = this.parent = m;\n            a || (a = this);\n            this.parent = a;\n            this.B = a.B;\n            a = Gb(this.parent.id, this.name);\n            this.Ra = Cb[a];\n            Cb[a] = this\n        }, Ib.prototype = {}, Object.defineProperties(Ib.prototype, {\n            H: {\n                get: function() {\n                    return 365 === (this.mode & 365)\n                },\n                set: function(a) {\n                    a ? this.mode |= 365 : this.mode &= -366\n                }\n            },\n            write: {\n                get: function() {\n                    return 146 === (this.mode & 146)\n                },\n                set: function(a) {\n                    a ? this.mode |= 146 : this.mode &= -147\n                }\n            },\n            Oa: {\n                get: function() {\n                    return 16384 ===\n                        (this.mode & 61440)\n                }\n            },\n            Na: {\n                get: function() {\n                    return 8192 === (this.mode & 61440)\n                }\n            }\n        }));\n        return new Ib(a, b, c, d)\n    }\n    var Jb = {\n        r: 0,\n        rs: 1052672,\n        \"r+\": 2,\n        w: 577,\n        wx: 705,\n        xw: 705,\n        \"w+\": 578,\n        \"wx+\": 706,\n        \"xw+\": 706,\n        a: 1089,\n        ax: 1217,\n        xa: 1217,\n        \"a+\": 1090,\n        \"ax+\": 1218,\n        \"xa+\": 1218\n    };\n\n    function Hb(a, b) {\n        return Db ? 0 : -1 !== b.indexOf(\"r\") && !(a.mode & 292) || -1 !== b.indexOf(\"w\") && !(a.mode & 146) || -1 !== b.indexOf(\"x\") && !(a.mode & 73) ? R.Ca : 0\n    }\n\n    function Kb(a, b) {\n        try {\n            return vb(a, b), R.ja\n        } catch (c) {}\n        return Hb(a, \"wx\")\n    }\n    var sb = {\n        open: function(a) {\n            a.k = qb[a.e.U].k;\n            a.k.open && a.k.open(a)\n        },\n        F: function() {\n            e(new S(R.$))\n        }\n    };\n\n    function Lb(a, b, c) {\n        var d = U(a, {\n                parent: l\n            }).e,\n            a = Mb(a),\n            f = Kb(d, a);\n        f && e(new S(f));\n        d.g.K || e(new S(R.L));\n        return d.g.K(d, a, b, c)\n    }\n\n    function Nb(a, b) {\n        b = (b !== i ? b : 438) & 4095;\n        b |= 32768;\n        return Lb(a, b, 0)\n    }\n\n    function X(a, b) {\n        b = (b !== i ? b : 511) & 1023;\n        b |= 16384;\n        return Lb(a, b, 0)\n    }\n\n    function Ob(a, b, c) {\n        \"undefined\" === typeof c && (c = b, b = 438);\n        return Lb(a, b | 8192, c)\n    }\n\n    function Pb(a, b) {\n        var c = U(b, {\n                parent: l\n            }).e,\n            d = Mb(b),\n            f = Kb(c, d);\n        f && e(new S(f));\n        c.g.W || e(new S(R.L));\n        return c.g.W(c, d, a)\n    }\n\n    function Qb(a, b) {\n        var c;\n        c = \"string\" === typeof a ? U(a, {\n            N: l\n        }).e : a;\n        c.g.o || e(new S(R.L));\n        c.g.o(c, {\n            mode: b & 4095 | c.mode & -4096,\n            timestamp: Date.now()\n        })\n    }\n\n    function Rb(a, b) {\n        var c, d;\n        \"string\" === typeof b ? (d = Jb[b], \"undefined\" === typeof d && e(Error(\"Unknown file open mode: \" + b))) : d = b;\n        b = d;\n        c = b & 64 ? (\"undefined\" === typeof c ? 438 : c) & 4095 | 32768 : 0;\n        var f;\n        if (\"object\" === typeof a) f = a;\n        else {\n            a = V(a);\n            try {\n                f = U(a, {\n                    N: !(b & 131072)\n                }).e\n            } catch (g) {}\n        }\n        b & 64 && (f ? b & 128 && e(new S(R.ja)) : f = Lb(a, c, 0));\n        f || e(new S(R.Q));\n        8192 === (f.mode & 61440) && (b &= -513);\n        f ? 40960 === (f.mode & 61440) ? c = R.Z : 16384 === (f.mode & 61440) && (0 !== (b & 2097155) || b & 512) ? c = R.Y : (c = [\"r\", \"w\", \"rw\"][b & 2097155], b & 512 && (c += \"w\"), c = Hb(f, c)) : c = R.Q;\n        c && e(new S(c));\n        b & 512 && (c = f, c = \"string\" === typeof c ? U(c, {\n            N: l\n        }).e : c, c.g.o || e(new S(R.L)), 16384 === (c.mode & 61440) && e(new S(R.Y)), 32768 !== (c.mode & 61440) && e(new S(R.C)), (d = Hb(c, \"w\")) && e(new S(d)), c.g.o(c, {\n            size: 0,\n            timestamp: Date.now()\n        }));\n        var b = b & -641,\n            h;\n        f = {\n            e: f,\n            path: W(f),\n            M: b,\n            seekable: l,\n            position: 0,\n            k: f.k,\n            Va: [],\n            error: p\n        };\n        Y || (Y = q(), Y.prototype = {}, Object.defineProperties(Y.prototype, {\n            object: {\n                get: function() {\n                    return this.e\n                },\n                set: function(a) {\n                    this.e = a\n                }\n            },\n            qd: {\n                get: function() {\n                    return 1 !== (this.M & 2097155)\n                }\n            },\n            rd: {\n                get: function() {\n                    return 0 !==\n                        (this.M & 2097155)\n                }\n            },\n            pd: {\n                get: function() {\n                    return this.M & 1024\n                }\n            }\n        }));\n        if (f.__proto__) f.__proto__ = Y.prototype;\n        else {\n            c = new Y;\n            for (var k in f) c[k] = f[k];\n            f = c\n        }\n        a: {\n            k = i || 4096;\n            for (c = i || 1; c <= k; c++)\n                if (!Ab[c]) {\n                    h = c;\n                    break a\n                }\n            e(new S(R.Ea))\n        }\n        f.q = h;\n        h = Ab[h] = f;\n        h.k.open && h.k.open(h);\n        r.logReadFiles && !(b & 1) && (Sb || (Sb = {}), a in Sb || (Sb[a] = 1, r.printErr(\"read file: \" + a)));\n        return h\n    }\n\n    function Tb(a) {\n        try {\n            a.k.close && a.k.close(a)\n        } catch (b) {\n            e(b)\n        } finally {\n            Ab[a.q] = m\n        }\n    }\n\n    function Ub() {\n        S || (S = function(a) {\n            this.jd = a;\n            for (var b in R)\n                if (R[b] === a) {\n                    this.code = b;\n                    break\n                }\n            this.message = nb[a];\n            this.stack = Ma()\n        }, S.prototype = Error(), [R.Q].forEach(function(a) {\n            ub[a] = new S(a);\n            ub[a].stack = \"<generic error, no stack>\"\n        }))\n    }\n    var Vb;\n\n    function Wb(a, b) {\n        var c = 0;\n        a && (c |= 365);\n        b && (c |= 146);\n        return c\n    }\n\n    function Xb(a, b, c, d, f, g) {\n        a = b ? V((\"string\" === typeof a ? a : W(a)) + \"/\" + b) : a;\n        d = Wb(d, f);\n        f = Nb(a, d);\n        if (c) {\n            if (\"string\" === typeof c) {\n                for (var a = Array(c.length), b = 0, h = c.length; b < h; ++b) a[b] = c.charCodeAt(b);\n                c = a\n            }\n            Qb(f, d | 146);\n            var a = Rb(f, \"w\"),\n                b = c,\n                h = c.length,\n                k = 0;\n            (0 > h || 0 > k) && e(new S(R.C));\n            0 === (a.M & 2097155) && e(new S(R.Da));\n            16384 === (a.e.mode & 61440) && e(new S(R.Y));\n            a.k.write || e(new S(R.C));\n            c = l;\n            \"undefined\" === typeof k ? (k = a.position, c = p) : a.seekable || e(new S(R.$));\n            a.M & 1024 && ((!a.seekable || !a.k.F) && e(new S(R.$)), a.k.F(a, 0, 2));\n            g =\n                a.k.write(a, b, 0, h, k, g);\n            c || (a.position += g);\n            Tb(a);\n            Qb(f, d)\n        }\n        return f\n    }\n\n    function Z(a, b, c, d) {\n        a = V((\"string\" === typeof a ? a : W(a)) + \"/\" + b);\n        b = Wb(!!c, !!d);\n        Z.ua || (Z.ua = 64);\n        var f;\n        f = Z.ua++ << 8 | 0;\n        qb[f] = {\n            k: {\n                open: function(a) {\n                    a.seekable = p\n                },\n                close: function() {\n                    d && (d.buffer && d.buffer.length) && d(10)\n                },\n                H: function(a, b, d, f) {\n                    for (var j = 0, z = 0; z < f; z++) {\n                        var A;\n                        try {\n                            A = c()\n                        } catch (n) {\n                            e(new S(R.D))\n                        }\n                        A === i && 0 === j && e(new S(R.ia));\n                        if (A === m || A === i) break;\n                        j++;\n                        b[d + z] = A\n                    }\n                    j && (a.e.timestamp = Date.now());\n                    return j\n                },\n                write: function(a, b, c, f) {\n                    for (var j = 0; j < f; j++) try {\n                        d(b[c + j])\n                    } catch (z) {\n                        e(new S(R.D))\n                    }\n                    f && (a.e.timestamp = Date.now());\n                    return j\n                }\n            }\n        };\n        return Ob(a, b, f)\n    }\n\n    function Yb(a) {\n        if (a.Na || a.Oa || a.link || a.n) return l;\n        var b = l;\n        \"undefined\" !== typeof XMLHttpRequest && e(Error(\"Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.\"));\n        if (r.read) try {\n            a.n = D(r.read(a.url), l)\n        } catch (c) {\n            b = p\n        } else e(Error(\"Cannot load without read() or XMLHttpRequest.\"));\n        b || kb(R.D);\n        return b\n    }\n    var Ib, Y, Sb;\n\n    function Fb(a, b) {\n        for (var c = 0, d = a.length - 1; 0 <= d; d--) {\n            var f = a[d];\n            \".\" === f ? a.splice(d, 1) : \"..\" === f ? (a.splice(d, 1), c++) : c && (a.splice(d, 1), c--)\n        }\n        if (b)\n            for (; c--; c) a.unshift(\"..\");\n        return a\n    }\n\n    function V(a) {\n        var b = \"/\" === a.charAt(0),\n            c = \"/\" === a.substr(-1),\n            a = Fb(a.split(\"/\").filter(function(a) {\n                return !!a\n            }), !b).join(\"/\");\n        !a && !b && (a = \".\");\n        a && c && (a += \"/\");\n        return (b ? \"/\" : \"\") + a\n    }\n\n    function Mb(a) {\n        if (\"/\" === a) return \"/\";\n        var b = a.lastIndexOf(\"/\");\n        return -1 === b ? a : a.substr(b + 1)\n    }\n\n    function Eb() {\n        for (var a = \"\", b = p, c = arguments.length - 1; - 1 <= c && !b; c--) {\n            var d = 0 <= c ? arguments[c] : \"/\";\n            \"string\" !== typeof d && e(new TypeError(\"Arguments to path.resolve must be strings\"));\n            d && (a = d + \"/\" + a, b = \"/\" === d.charAt(0))\n        }\n        a = Fb(a.split(\"/\").filter(function(a) {\n            return !!a\n        }), !b).join(\"/\");\n        return (b ? \"/\" : \"\") + a || \".\"\n    }\n    var Zb = p,\n        $b = p,\n        ac = p,\n        bc = p,\n        cc = i,\n        dc = i;\n\n    function ec(a) {\n        return {\n            jpg: \"image/jpeg\",\n            jpeg: \"image/jpeg\",\n            png: \"image/png\",\n            bmp: \"image/bmp\",\n            ogg: \"audio/ogg\",\n            wav: \"audio/wav\",\n            mp3: \"audio/mpeg\"\n        }[a.substr(a.lastIndexOf(\".\") + 1)]\n    }\n    var fc = [];\n\n    function gc() {\n        var a = r.canvas;\n        fc.forEach(function(b) {\n            b(a.width, a.height)\n        })\n    }\n\n    function hc() {\n        var a = r.canvas;\n        this.Xa = a.width;\n        this.Wa = a.height;\n        a.width = screen.width;\n        a.height = screen.height;\n        \"undefined\" != typeof SDL && (a = Oa[SDL.screen + 0 * ma >> 2], H[SDL.screen + 0 * ma >> 2] = a | 8388608);\n        gc()\n    }\n\n    function ic() {\n        var a = r.canvas;\n        a.width = this.Xa;\n        a.height = this.Wa;\n        \"undefined\" != typeof SDL && (a = Oa[SDL.screen + 0 * ma >> 2], H[SDL.screen + 0 * ma >> 2] = a & -8388609);\n        gc()\n    }\n    var jc, kc, lc, mc, jb = ra(4);\n    H[jb >> 2] = 0;\n    r.requestFullScreen = function(a, b) {\n        function c() {\n            $b = p;\n            (document.webkitFullScreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.mozFullscreenElement || document.fullScreenElement || document.fullscreenElement) === d ? (d.pa = document.cancelFullScreen || document.mozCancelFullScreen || document.webkitCancelFullScreen, d.pa = d.pa.bind(document), cc && d.ga(), $b = l, dc && hc()) : dc && ic();\n            if (r.onFullScreen) r.onFullScreen($b)\n        }\n        cc = a;\n        dc = b;\n        \"undefined\" === typeof cc && (cc = l);\n        \"undefined\" === typeof dc &&\n            (dc = p);\n        var d = r.canvas;\n        bc || (bc = l, document.addEventListener(\"fullscreenchange\", c, p), document.addEventListener(\"mozfullscreenchange\", c, p), document.addEventListener(\"webkitfullscreenchange\", c, p));\n        d.Ta = d.requestFullScreen || d.mozRequestFullScreen || (d.webkitRequestFullScreen ? function() {\n            d.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT)\n        } : m);\n        d.Ta()\n    };\n    r.requestAnimationFrame = function(a) {\n        \"undefined\" === typeof window ? setTimeout(a, 1E3 / 60) : (window.requestAnimationFrame || (window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame || window.setTimeout), window.requestAnimationFrame(a))\n    };\n    r.setCanvasSize = function(a, b, c) {\n        var d = r.canvas;\n        d.width = a;\n        d.height = b;\n        c || gc()\n    };\n    r.pauseMainLoop = q();\n    r.resumeMainLoop = function() {\n        Zb && (Zb = p, m())\n    };\n    r.getUserMedia = function() {\n        window.sa || (window.sa = navigator.getUserMedia || navigator.mozGetUserMedia);\n        window.sa(i)\n    };\n    Ub();\n    var Cb = Array(4096),\n        zb = tb(m, \"/\", 16895, 0),\n        nc = T,\n        oc = \"/\",\n        pc;\n    oc && (pc = U(oc, {\n        N: p\n    }), oc = pc.path);\n    var qc = {\n            type: nc,\n            vd: {},\n            Qa: oc,\n            root: m\n        },\n        rc = nc.B(qc);\n    rc.B = qc;\n    qc.root = rc;\n    pc && (pc.e.B = qc, pc.e.Pa = l, \"/\" === oc && (zb = qc.root));\n    X(\"/tmp\");\n    X(\"/dev\");\n    qb[259] = {\n        k: {\n            H: function() {\n                return 0\n            },\n            write: function() {\n                return 0\n            }\n        }\n    };\n    Ob(\"/dev/null\", 259);\n    pb(1280, {\n        ta: function(a) {\n            if (!a.input.length) {\n                var b = m;\n                if (ba) {\n                    if (b = process.stdin.read(), !b) {\n                        if (process.stdin._readableState && process.stdin._readableState.ended) return m;\n                        return\n                    }\n                } else \"undefined\" != typeof window && \"function\" == typeof window.prompt ? (b = window.prompt(\"Input: \"), b !== m && (b += \"\\n\")) : \"function\" == typeof readline && (b = readline(), b !== m && (b += \"\\n\"));\n                if (!b) return m;\n                a.input = D(b, l)\n            }\n            return a.input.shift()\n        },\n        T: function(a, b) {\n            b === m || 10 === b ? (r.print(a.G.join(\"\")), a.G = []) : a.G.push(sc.ea(b))\n        }\n    });\n    pb(1536, {\n        T: function(a, b) {\n            b === m || 10 === b ? (r.printErr(a.G.join(\"\")), a.G = []) : a.G.push(sc.ea(b))\n        }\n    });\n    Ob(\"/dev/tty\", 1280);\n    Ob(\"/dev/tty1\", 1536);\n    X(\"/dev/shm\");\n    X(\"/dev/shm/tmp\");\n    P.unshift({\n        J: function() {\n            if (!r.noFSInit && !Vb) {\n                w(!Vb, \"FS.init was previously called. If you want to initialize later with custom parameters, remove any earlier calls (note that one is automatically added to the generated code)\");\n                Vb = l;\n                Ub();\n                r.stdin = r.stdin;\n                r.stdout = r.stdout;\n                r.stderr = r.stderr;\n                r.stdin ? Z(\"/dev\", \"stdin\", r.stdin) : Pb(\"/dev/tty\", \"/dev/stdin\");\n                r.stdout ? Z(\"/dev\", \"stdout\", m, r.stdout) : Pb(\"/dev/tty\", \"/dev/stdout\");\n                r.stderr ? Z(\"/dev\", \"stderr\", m, r.stderr) : Pb(\"/dev/tty1\", \"/dev/stderr\");\n                var a = Rb(\"/dev/stdin\",\n                    \"r\");\n                H[wb >> 2] = a.q;\n                w(1 === a.q, \"invalid handle for stdin (\" + a.q + \")\");\n                a = Rb(\"/dev/stdout\", \"w\");\n                H[xb >> 2] = a.q;\n                w(2 === a.q, \"invalid handle for stdout (\" + a.q + \")\");\n                a = Rb(\"/dev/stderr\", \"w\");\n                H[yb >> 2] = a.q;\n                w(3 === a.q, \"invalid handle for stderr (\" + a.q + \")\")\n            }\n        }\n    });\n    Ua.push({\n        J: function() {\n            Db = p\n        }\n    });\n    Va.push({\n        J: function() {\n            Vb = p;\n            for (var a = 0; a < Ab.length; a++) {\n                var b = Ab[a];\n                b && Tb(b)\n            }\n        }\n    });\n    r.FS_createFolder = function(a, b, c, d) {\n        a = V((\"string\" === typeof a ? a : W(a)) + \"/\" + b);\n        return X(a, Wb(c, d))\n    };\n    r.FS_createPath = function(a, b) {\n        for (var a = \"string\" === typeof a ? a : W(a), c = b.split(\"/\").reverse(); c.length;) {\n            var d = c.pop();\n            if (d) {\n                var f = V(a + \"/\" + d);\n                try {\n                    X(f)\n                } catch (g) {}\n                a = f\n            }\n        }\n        return f\n    };\n    r.FS_createDataFile = Xb;\n    r.FS_createPreloadedFile = function(a, b, c, d, f, g, h, k, t) {\n        function j() {\n            ac = document.pointerLockElement === n || document.mozPointerLockElement === n || document.webkitPointerLockElement === n\n        }\n\n        function z(c) {\n            function j(c) {\n                k || Xb(a, b, c, d, f, t);\n                g && g();\n                cb()\n            }\n            var n = p;\n            r.preloadPlugins.forEach(function(a) {\n                !n && a.canHandle(v) && (a.handle(c, v, j, function() {\n                    h && h();\n                    cb()\n                }), n = l)\n            });\n            n || j(c)\n        }\n        r.preloadPlugins || (r.preloadPlugins = []);\n        if (!jc && !ea) {\n            jc = l;\n            try {\n                new Blob, kc = l\n            } catch (A) {\n                kc = p, console.log(\"warning: no blob constructor, cannot create blobs with mimetypes\")\n            }\n            lc =\n                \"undefined\" != typeof MozBlobBuilder ? MozBlobBuilder : \"undefined\" != typeof WebKitBlobBuilder ? WebKitBlobBuilder : !kc ? console.log(\"warning: no BlobBuilder\") : m;\n            mc = \"undefined\" != typeof window ? window.URL ? window.URL : window.webkitURL : i;\n            !r.wa && \"undefined\" === typeof mc && (console.log(\"warning: Browser does not support creating object URLs. Built-in browser image decoding will not be available.\"), r.wa = l);\n            r.preloadPlugins.push({\n                canHandle: function(a) {\n                    return !r.wa && /\\.(jpg|jpeg|png|bmp)$/i.test(a)\n                },\n                handle: function(a, b,\n                    c, d) {\n                    var f = m;\n                    if (kc) try {\n                        f = new Blob([a], {\n                            type: ec(b)\n                        }), f.size !== a.length && (f = new Blob([(new Uint8Array(a)).buffer], {\n                            type: ec(b)\n                        }))\n                    } catch (g) {\n                        var h = \"Blob constructor present but fails: \" + g + \"; falling back to blob builder\";\n                        oa || (oa = {});\n                        oa[h] || (oa[h] = 1, r.P(h))\n                    }\n                    f || (f = new lc, f.append((new Uint8Array(a)).buffer), f = f.getBlob());\n                    var j = mc.createObjectURL(f),\n                        n = new Image;\n                    n.onload = function() {\n                        w(n.complete, \"Image \" + b + \" could not be decoded\");\n                        var d = document.createElement(\"canvas\");\n                        d.width = n.width;\n                        d.height = n.height;\n                        d.getContext(\"2d\").drawImage(n,\n                            0, 0);\n                        r.preloadedImages[b] = d;\n                        mc.revokeObjectURL(j);\n                        c && c(a)\n                    };\n                    n.onerror = function() {\n                        console.log(\"Image \" + j + \" could not be decoded\");\n                        d && d()\n                    };\n                    n.src = j\n                }\n            });\n            r.preloadPlugins.push({\n                canHandle: function(a) {\n                    return !r.ud && a.substr(-4) in {\n                        \".ogg\": 1,\n                        \".wav\": 1,\n                        \".mp3\": 1\n                    }\n                },\n                handle: function(a, b, c, d) {\n                    function f(d) {\n                        h || (h = l, r.preloadedAudios[b] = d, c && c(a))\n                    }\n\n                    function g() {\n                        h || (h = l, r.preloadedAudios[b] = new Audio, d && d())\n                    }\n                    var h = p;\n                    if (kc) {\n                        try {\n                            var j = new Blob([a], {\n                                type: ec(b)\n                            })\n                        } catch (n) {\n                            return g()\n                        }\n                        var j = mc.createObjectURL(j),\n                            k = new Audio;\n                        k.addEventListener(\"canplaythrough\",\n                            function() {\n                                f(k)\n                            }, p);\n                        k.onerror = function() {\n                            if (!h) {\n                                console.log(\"warning: browser could not fully decode audio \" + b + \", trying slower base64 approach\");\n                                for (var c = \"\", d = 0, g = 0, j = 0; j < a.length; j++) {\n                                    d = d << 8 | a[j];\n                                    for (g += 8; 6 <= g;) var n = d >> g - 6 & 63,\n                                        g = g - 6,\n                                        c = c + \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\" [n]\n                                }\n                                2 == g ? (c += \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\" [(d & 3) << 4], c += \"==\") : 4 == g && (c += \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\" [(d & 15) << 2], c += \"=\");\n                                k.src = \"data:audio/x-\" + b.substr(-3) + \";base64,\" + c;\n                                f(k)\n                            }\n                        };\n                        k.src = j;\n                        setTimeout(function() {\n                            xa || f(k)\n                        }, 1E4)\n                    } else return g()\n                }\n            });\n            var n = r.canvas;\n            n.ga = n.requestPointerLock || n.mozRequestPointerLock || n.webkitRequestPointerLock;\n            n.ra = document.exitPointerLock || document.mozExitPointerLock || document.webkitExitPointerLock || q();\n            n.ra = n.ra.bind(document);\n            document.addEventListener(\"pointerlockchange\", j, p);\n            document.addEventListener(\"mozpointerlockchange\", j, p);\n            document.addEventListener(\"webkitpointerlockchange\", j, p);\n            r.elementPointerLock &&\n                n.addEventListener(\"click\", function(a) {\n                    !ac && n.ga && (n.ga(), a.preventDefault())\n                }, p)\n        }\n        var v = b ? Eb(V(a + \"/\" + b)) : a;\n        bb();\n        if (\"string\" == typeof c) {\n            var E = h,\n                da = function() {\n                    E ? E() : e('Loading data file \"' + c + '\" failed.')\n                },\n                J = new XMLHttpRequest;\n            J.open(\"GET\", c, l);\n            J.responseType = \"arraybuffer\";\n            J.onload = function() {\n                if (200 == J.status || 0 == J.status && J.response) {\n                    var a = J.response;\n                    w(a, 'Loading data file \"' + c + '\" failed (no arrayBuffer).');\n                    a = new Uint8Array(a);\n                    z(a);\n                    cb()\n                } else da()\n            };\n            J.onerror = da;\n            J.send(m);\n            bb()\n        } else z(c)\n    };\n    r.FS_createLazyFile = function(a, b, c, d, f) {\n        var g, h;\n        \"undefined\" !== typeof XMLHttpRequest ? (ea || e(\"Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc\"), g = function() {\n            this.ca = p;\n            this.R = []\n        }, g.prototype.get = function(a) {\n            if (!(a > this.length - 1 || 0 > a)) {\n                var b = a % this.La;\n                return this.Ma(Math.floor(a / this.La))[b]\n            }\n        }, g.prototype.Ua = function(a) {\n            this.Ma = a\n        }, g.prototype.oa = function() {\n            var a = new XMLHttpRequest;\n            a.open(\"HEAD\", c, p);\n            a.send(m);\n            200 <= a.status && 300 > a.status ||\n                304 === a.status || e(Error(\"Couldn't load \" + c + \". Status: \" + a.status));\n            var b = Number(a.getResponseHeader(\"Content-length\")),\n                d, f = 1048576;\n            if (!((d = a.getResponseHeader(\"Accept-Ranges\")) && \"bytes\" === d)) f = b;\n            var g = this;\n            g.Ua(function(a) {\n                var d = a * f,\n                    h = (a + 1) * f - 1,\n                    h = Math.min(h, b - 1);\n                if (\"undefined\" === typeof g.R[a]) {\n                    var k = g.R;\n                    d > h && e(Error(\"invalid range (\" + d + \", \" + h + \") or no bytes requested!\"));\n                    h > b - 1 && e(Error(\"only \" + b + \" bytes available! programmer error!\"));\n                    var j = new XMLHttpRequest;\n                    j.open(\"GET\", c, p);\n                    b !== f && j.setRequestHeader(\"Range\",\n                        \"bytes=\" + d + \"-\" + h);\n                    \"undefined\" != typeof Uint8Array && (j.responseType = \"arraybuffer\");\n                    j.overrideMimeType && j.overrideMimeType(\"text/plain; charset=x-user-defined\");\n                    j.send(m);\n                    200 <= j.status && 300 > j.status || 304 === j.status || e(Error(\"Couldn't load \" + c + \". Status: \" + j.status));\n                    d = j.response !== i ? new Uint8Array(j.response || []) : D(j.responseText || \"\", l);\n                    k[a] = d\n                }\n                \"undefined\" === typeof g.R[a] && e(Error(\"doXHR failed!\"));\n                return g.R[a]\n            });\n            this.Ha = b;\n            this.Ga = f;\n            this.ca = l\n        }, g = new g, Object.defineProperty(g, \"length\", {\n            get: function() {\n                this.ca ||\n                    this.oa();\n                return this.Ha\n            }\n        }), Object.defineProperty(g, \"chunkSize\", {\n            get: function() {\n                this.ca || this.oa();\n                return this.Ga\n            }\n        }), h = i) : (h = c, g = i);\n        var k, a = V((\"string\" === typeof a ? a : W(a)) + \"/\" + b);\n        k = Nb(a, Wb(d, f));\n        g ? k.n = g : h && (k.n = m, k.url = h);\n        var t = {};\n        Object.keys(k.k).forEach(function(a) {\n            var b = k.k[a];\n            t[a] = function() {\n                Yb(k) || e(new S(R.D));\n                return b.apply(m, arguments)\n            }\n        });\n        t.H = function(a, b, c, d, f) {\n            Yb(k) || e(new S(R.D));\n            a = a.e.n;\n            if (f >= a.length) return 0;\n            d = Math.min(a.length - f, d);\n            w(0 <= d);\n            if (a.slice)\n                for (var g = 0; g < d; g++) b[c + g] = a[f + g];\n            else\n                for (g = 0; g < d; g++) b[c + g] = a.get(f + g);\n            return d\n        };\n        k.k = t;\n        return k\n    };\n    r.FS_createLink = function(a, b, c) {\n        a = V((\"string\" === typeof a ? a : W(a)) + \"/\" + b);\n        return Pb(c, a)\n    };\n    r.FS_createDevice = Z;\n    P.unshift({\n        J: q()\n    });\n    Va.push({\n        J: q()\n    });\n    var sc = new pa;\n    ba && (require(\"fs\"), process.platform.match(/^win/));\n    Qa = u = va(x);\n    Ra = Qa + 5242880;\n    Sa = y = va(Ra);\n    w(Sa < ua);\n    Fa = Math.min;\n    var $ = (function(global, env, buffer) {\n            // EMSCRIPTEN_START_ASM\n            \"use asm\";\n            var a = new global.Int8Array(buffer);\n            var b = new global.Int16Array(buffer);\n            var c = new global.Int32Array(buffer);\n            var d = new global.Uint8Array(buffer);\n            var e = new global.Uint16Array(buffer);\n            var f = new global.Uint32Array(buffer);\n            var g = new global.Float32Array(buffer);\n            var h = new global.Float64Array(buffer);\n            var i = env.STACKTOP | 0;\n            var j = env.STACK_MAX | 0;\n            var k = env.tempDoublePtr | 0;\n            var l = env.ABORT | 0;\n            var m = env.cttz_i8 | 0;\n            var n = env.ctlz_i8 | 0;\n            var o = +env.NaN;\n            var p = +env.Infinity;\n            var q = 0;\n            var r = 0;\n            var s = 0;\n            var t = 0;\n            var u = 0,\n                v = 0,\n                w = 0,\n                x = 0,\n                y = 0.0,\n                z = 0,\n                A = 0,\n                B = 0,\n                C = 0.0;\n            var D = 0;\n            var E = 0;\n            var F = 0;\n            var G = 0;\n            var H = 0;\n            var I = 0;\n            var J = 0;\n            var K = 0;\n            var L = 0;\n            var M = 0;\n            var N = global.Math.floor;\n            var O = global.Math.abs;\n            var P = global.Math.sqrt;\n            var Q = global.Math.pow;\n            var R = global.Math.cos;\n            var S = global.Math.sin;\n            var T = global.Math.tan;\n            var U = global.Math.acos;\n            var V = global.Math.asin;\n            var W = global.Math.atan;\n            var X = global.Math.atan2;\n            var Y = global.Math.exp;\n            var Z = global.Math.log;\n            var _ = global.Math.ceil;\n            var $ = global.Math.imul;\n            var aa = env.abort;\n            var ab = env.assert;\n            var ac = env.asmPrintInt;\n            var ad = env.asmPrintFloat;\n            var ae = env.min;\n            var af = env.invoke_ii;\n            var ag = env.invoke_v;\n            var ah = env.invoke_iii;\n            var ai = env.invoke_vi;\n            var aj = env._sysconf;\n            var ak = env._sbrk;\n            var al = env.___setErrNo;\n            var am = env.___errno_location;\n            var an = env._abort;\n            var ao = env._time;\n            var ap = env._fflush;\n            var aq = 0.0;\n            // EMSCRIPTEN_START_FUNCS\n            function av(a) {\n                a = a | 0;\n                var b = 0;\n                b = i;\n                i = i + a | 0;\n                i = i + 7 & -8;\n                return b | 0\n            }\n\n            function aw() {\n                return i | 0\n            }\n\n            function ax(a) {\n                a = a | 0;\n                i = a\n            }\n\n            function ay(a, b) {\n                a = a | 0;\n                b = b | 0;\n                if ((q | 0) == 0) {\n                    q = a;\n                    r = b\n                }\n            }\n\n            function az(b) {\n                b = b | 0;\n                a[k] = a[b];\n                a[k + 1 | 0] = a[b + 1 | 0];\n                a[k + 2 | 0] = a[b + 2 | 0];\n                a[k + 3 | 0] = a[b + 3 | 0]\n            }\n\n            function aA(b) {\n                b = b | 0;\n                a[k] = a[b];\n                a[k + 1 | 0] = a[b + 1 | 0];\n                a[k + 2 | 0] = a[b + 2 | 0];\n                a[k + 3 | 0] = a[b + 3 | 0];\n                a[k + 4 | 0] = a[b + 4 | 0];\n                a[k + 5 | 0] = a[b + 5 | 0];\n                a[k + 6 | 0] = a[b + 6 | 0];\n                a[k + 7 | 0] = a[b + 7 | 0]\n            }\n\n            function aB(a) {\n                a = a | 0;\n                D = a\n            }\n\n            function aC(a) {\n                a = a | 0;\n                E = a\n            }\n\n            function aD(a) {\n                a = a | 0;\n                F = a\n            }\n\n            function aE(a) {\n                a = a | 0;\n                G = a\n            }\n\n            function aF(a) {\n                a = a | 0;\n                H = a\n            }\n\n            function aG(a) {\n                a = a | 0;\n                I = a\n            }\n\n            function aH(a) {\n                a = a | 0;\n                J = a\n            }\n\n            function aI(a) {\n                a = a | 0;\n                K = a\n            }\n\n            function aJ(a) {\n                a = a | 0;\n                L = a\n            }\n\n            function aK(a) {\n                a = a | 0;\n                M = a\n            }\n\n            function aL() {}\n\n            function aM(f, g, h) {\n                f = f | 0;\n                g = g | 0;\n                h = h | 0;\n                var j = 0,\n                    k = 0,\n                    l = 0,\n                    m = 0,\n                    n = 0,\n                    o = 0,\n                    p = 0,\n                    q = 0,\n                    r = 0,\n                    s = 0,\n                    t = 0,\n                    u = 0,\n                    w = 0,\n                    x = 0,\n                    y = 0,\n                    z = 0,\n                    A = 0,\n                    B = 0,\n                    C = 0,\n                    D = 0,\n                    E = 0,\n                    F = 0,\n                    G = 0,\n                    H = 0,\n                    I = 0,\n                    J = 0,\n                    K = 0,\n                    L = 0,\n                    M = 0,\n                    N = 0,\n                    O = 0,\n                    P = 0,\n                    Q = 0,\n                    R = 0,\n                    S = 0,\n                    T = 0,\n                    U = 0,\n                    V = 0,\n                    W = 0,\n                    X = 0,\n                    Y = 0,\n                    Z = 0,\n                    _ = 0,\n                    aa = 0,\n                    ab = 0,\n                    ac = 0,\n                    ad = 0,\n                    ae = 0,\n                    af = 0,\n                    ag = 0,\n                    ah = 0,\n                    ai = 0,\n                    aj = 0,\n                    ak = 0,\n                    al = 0,\n                    am = 0,\n                    an = 0,\n                    ao = 0,\n                    ap = 0,\n                    aq = 0,\n                    ar = 0,\n                    as = 0,\n                    at = 0,\n                    au = 0,\n                    av = 0,\n                    aw = 0,\n                    ax = 0,\n                    ay = 0,\n                    az = 0,\n                    aA = 0,\n                    aB = 0,\n                    aC = 0,\n                    aD = 0,\n                    aE = 0,\n                    aF = 0,\n                    aG = 0;\n                j = i;\n                i = i + 16384 | 0;\n                k = j | 0;\n                l = k;\n                aR(l | 0, 0, 16384) | 0;\n                l = f + h | 0;\n                m = h - 12 | 0;\n                n = f + m | 0;\n                o = f + (h - 5) | 0;\n                p = h >>> 0 > 2113929216 >>> 0;\n                if ((h | 0) >= 65547) {\n                    if (p) {\n                        q = 0;\n                        i = j;\n                        return q | 0\n                    }\n                    r = f;\n                    c[k + (($(d[r] | d[r + 1 | 0] << 8 | d[r + 2 | 0] << 16 | d[r + 3 | 0] << 24 | 0, -1640531535) | 0) >>> 20 << 2) >> 2] = f;\n                    L6: do {\n                        if ((m | 0) < 2) {\n                            s = f;\n                            t = g\n                        } else {\n                            r = f + (h - 8) | 0;\n                            u = f + (h - 6) | 0;\n                            w = g;\n                            x = f;\n                            y = f;\n                            z = f + 2 | 0;\n                            while (1) {\n                                A = y + 1 | 0;\n                                B = A;\n                                C = A;\n                                A = d[B] | d[B + 1 | 0] << 8 | d[B + 2 | 0] << 16 | d[B + 3 | 0] << 24 | 0;\n                                B = 68;\n                                D = z;\n                                while (1) {\n                                    E = ($(A, -1640531535) | 0) >>> 20;\n                                    F = D;\n                                    G = d[F] | d[F + 1 | 0] << 8 | d[F + 2 | 0] << 16 | d[F + 3 | 0] << 24 | 0;\n                                    F = k + (E << 2) | 0;\n                                    E = c[F >> 2] | 0;\n                                    c[F >> 2] = C;\n                                    if ((E + 65535 | 0) >>> 0 >= C >>> 0) {\n                                        F = E;\n                                        H = C;\n                                        if ((d[F] | d[F + 1 | 0] << 8 | d[F + 2 | 0] << 16 | d[F + 3 | 0] << 24 | 0) == (d[H] | d[H + 1 | 0] << 8 | d[H + 2 | 0] << 16 | d[H + 3 | 0] << 24 | 0)) {\n                                            I = C;\n                                            J = E;\n                                            break\n                                        }\n                                    }\n                                    E = D + (B >> 6) | 0;\n                                    if (E >>> 0 > n >>> 0) {\n                                        s = x;\n                                        t = w;\n                                        break L6\n                                    } else {\n                                        C = D;\n                                        A = G;\n                                        B = B + 1 | 0;\n                                        D = E\n                                    }\n                                }\n                                while (1) {\n                                    if (!(I >>> 0 > x >>> 0 & J >>> 0 > f >>> 0)) {\n                                        break\n                                    }\n                                    D = I - 1 | 0;\n                                    B = J - 1 | 0;\n                                    if ((a[D] | 0) == (a[B] | 0)) {\n                                        I = D;\n                                        J = B\n                                    } else {\n                                        break\n                                    }\n                                }\n                                B = I;\n                                D = x;\n                                A = B - D | 0;\n                                C = w + 1 | 0;\n                                if ((A | 0) > 14) {\n                                    E = A - 15 | 0;\n                                    a[w] = -16;\n                                    if ((E | 0) > 254) {\n                                        G = B - 270 - D | 0;\n                                        D = (G >>> 0) / 255 | 0;\n                                        B = D + 1 | 0;\n                                        aR(C | 0, -1 | 0, B | 0) | 0;\n                                        K = G + (D * -255 | 0) & 255;\n                                        L = w + (D + 2) | 0\n                                    } else {\n                                        K = E & 255;\n                                        L = C\n                                    }\n                                    a[L] = K;\n                                    M = L + 1 | 0\n                                } else {\n                                    a[w] = A << 4 & 255;\n                                    M = C\n                                }\n                                C = M + A | 0;\n                                A = x;\n                                E = M;\n                                while (1) {\n                                    D = A;\n                                    G = E;\n                                    v = d[D] | d[D + 1 | 0] << 8 | d[D + 2 | 0] << 16 | d[D + 3 | 0] << 24 | 0;\n                                    a[G] = v & 255;\n                                    v = v >> 8;\n                                    a[G + 1 | 0] = v & 255;\n                                    v = v >> 8;\n                                    a[G + 2 | 0] = v & 255;\n                                    v = v >> 8;\n                                    a[G + 3 | 0] = v & 255;\n                                    G = A + 4 | 0;\n                                    D = E + 4 | 0;\n                                    v = d[G] | d[G + 1 | 0] << 8 | d[G + 2 | 0] << 16 | d[G + 3 | 0] << 24 | 0;\n                                    a[D] = v & 255;\n                                    v = v >> 8;\n                                    a[D + 1 | 0] = v & 255;\n                                    v = v >> 8;\n                                    a[D + 2 | 0] = v & 255;\n                                    v = v >> 8;\n                                    a[D + 3 | 0] = v & 255;\n                                    D = E + 8 | 0;\n                                    if (D >>> 0 < C >>> 0) {\n                                        A = A + 8 | 0;\n                                        E = D\n                                    } else {\n                                        N = I;\n                                        O = C;\n                                        P = J;\n                                        Q = w;\n                                        break\n                                    }\n                                }\n                                while (1) {\n                                    C = O;\n                                    v = N - P & 65535;\n                                    a[C] = v & 255;\n                                    v = v >> 8;\n                                    a[C + 1 | 0] = v & 255;\n                                    C = O + 2 | 0;\n                                    E = N + 4 | 0;\n                                    A = E;\n                                    D = P;\n                                    while (1) {\n                                        R = D + 4 | 0;\n                                        if (A >>> 0 >= r >>> 0) {\n                                            S = 68;\n                                            break\n                                        }\n                                        G = R;\n                                        T = d[G] | d[G + 1 | 0] << 8 | d[G + 2 | 0] << 16 | d[G + 3 | 0] << 24 | 0;\n                                        G = A;\n                                        U = d[G] | d[G + 1 | 0] << 8 | d[G + 2 | 0] << 16 | d[G + 3 | 0] << 24 | 0;\n                                        if ((T | 0) == (U | 0)) {\n                                            A = A + 4 | 0;\n                                            D = R\n                                        } else {\n                                            S = 67;\n                                            break\n                                        }\n                                    }\n                                    do {\n                                        if ((S | 0) == 67) {\n                                            S = 0;\n                                            V = A + ((aT(U ^ T | 0) | 0) >>> 3) | 0\n                                        } else if ((S | 0) == 68) {\n                                            S = 0;\n                                            do {\n                                                if (A >>> 0 < u >>> 0) {\n                                                    G = R;\n                                                    B = A;\n                                                    if ((d[G] | d[G + 1 | 0] << 8) << 16 >> 16 << 16 >> 16 != (d[B] | d[B + 1 | 0] << 8) << 16 >> 16 << 16 >> 16) {\n                                                        W = A;\n                                                        X = R;\n                                                        break\n                                                    }\n                                                    W = A + 2 | 0;\n                                                    X = D + 6 | 0\n                                                } else {\n                                                    W = A;\n                                                    X = R\n                                                }\n                                            } while (0);\n                                            if (W >>> 0 >= o >>> 0) {\n                                                V = W;\n                                                break\n                                            }\n                                            V = (a[X] | 0) == (a[W] | 0) ? W + 1 | 0 : W\n                                        }\n                                    } while (0);\n                                    A = V;\n                                    D = E;\n                                    B = A - D | 0;\n                                    G = a[Q] | 0;\n                                    if ((B | 0) > 14) {\n                                        a[Q] = G + 15 & 255;\n                                        H = B - 15 | 0;\n                                        if ((H | 0) > 509) {\n                                            F = A - 525 - D | 0;\n                                            D = (F >>> 0) / 510 | 0;\n                                            Y = F + (D * -510 | 0) | 0;\n                                            F = D << 1;\n                                            D = H;\n                                            Z = C;\n                                            while (1) {\n                                                a[Z] = -1;\n                                                a[Z + 1 | 0] = -1;\n                                                _ = D - 510 | 0;\n                                                if ((_ | 0) > 509) {\n                                                    D = _;\n                                                    Z = Z + 2 | 0\n                                                } else {\n                                                    break\n                                                }\n                                            }\n                                            aa = Y;\n                                            ab = O + (F + 4) | 0\n                                        } else {\n                                            aa = H;\n                                            ab = C\n                                        }\n                                        if ((aa | 0) > 254) {\n                                            a[ab] = -1;\n                                            ac = ab + 1 | 0;\n                                            ad = aa + 1 & 255\n                                        } else {\n                                            ac = ab;\n                                            ad = aa & 255\n                                        }\n                                        a[ac] = ad;\n                                        ae = ac + 1 | 0\n                                    } else {\n                                        a[Q] = (G & 255) + B & 255;\n                                        ae = C\n                                    }\n                                    if (V >>> 0 > n >>> 0) {\n                                        s = V;\n                                        t = ae;\n                                        break L6\n                                    }\n                                    Z = V - 2 | 0;\n                                    D = Z;\n                                    c[k + (($(d[D] | d[D + 1 | 0] << 8 | d[D + 2 | 0] << 16 | d[D + 3 | 0] << 24 | 0, -1640531535) | 0) >>> 20 << 2) >> 2] = Z;\n                                    Z = V;\n                                    D = k + (($(d[Z] | d[Z + 1 | 0] << 8 | d[Z + 2 | 0] << 16 | d[Z + 3 | 0] << 24 | 0, -1640531535) | 0) >>> 20 << 2) | 0;\n                                    E = c[D >> 2] | 0;\n                                    c[D >> 2] = A;\n                                    if ((E + 65535 | 0) >>> 0 < V >>> 0) {\n                                        break\n                                    }\n                                    D = E;\n                                    if ((d[D] | d[D + 1 | 0] << 8 | d[D + 2 | 0] << 16 | d[D + 3 | 0] << 24 | 0) != (d[Z] | d[Z + 1 | 0] << 8 | d[Z + 2 | 0] << 16 | d[Z + 3 | 0] << 24 | 0)) {\n                                        break\n                                    }\n                                    a[ae] = 0;\n                                    N = V;\n                                    O = ae + 1 | 0;\n                                    P = E;\n                                    Q = ae\n                                }\n                                E = V + 2 | 0;\n                                if (E >>> 0 > n >>> 0) {\n                                    s = V;\n                                    t = ae;\n                                    break\n                                } else {\n                                    w = ae;\n                                    x = V;\n                                    y = V;\n                                    z = E\n                                }\n                            }\n                        }\n                    } while (0);\n                    V = l;\n                    ae = s;\n                    Q = V - ae | 0;\n                    if ((Q | 0) > 14) {\n                        a[t] = -16;\n                        P = Q - 15 | 0;\n                        O = t + 1 | 0;\n                        if ((P | 0) > 254) {\n                            N = V - 270 - ae | 0;\n                            ae = (N >>> 0) / 255 | 0;\n                            V = ae + 2 | 0;\n                            ac = ae + 1 | 0;\n                            aR(O | 0, -1 | 0, ac | 0) | 0;\n                            af = N + (ae * -255 | 0) & 255;\n                            ag = t + V | 0\n                        } else {\n                            af = P & 255;\n                            ag = O\n                        }\n                        a[ag] = af;\n                        ah = ag\n                    } else {\n                        a[t] = Q << 4 & 255;\n                        ah = t\n                    }\n                    t = ah + 1 | 0;\n                    aS(t | 0, s | 0, Q) | 0;\n                    q = ah + (Q + 1) - g | 0;\n                    i = j;\n                    return q | 0\n                }\n                if (p) {\n                    q = 0;\n                    i = j;\n                    return q | 0\n                }\n                L72: do {\n                    if ((h | 0) < 13) {\n                        ai = g;\n                        aj = f\n                    } else {\n                        p = f;\n                        Q = k;\n                        b[Q + (($(d[p] | d[p + 1 | 0] << 8 | d[p + 2 | 0] << 16 | d[p + 3 | 0] << 24 | 0, -1640531535) | 0) >>> 19 << 1) >> 1] = 0;\n                        if ((m | 0) < 2) {\n                            ai = g;\n                            aj = f;\n                            break\n                        }\n                        p = f;\n                        ah = f + (h - 8) | 0;\n                        s = f + (h - 6) | 0;\n                        t = f;\n                        ag = g;\n                        af = f;\n                        O = f + 2 | 0;\n                        while (1) {\n                            P = af + 1 | 0;\n                            V = P;\n                            ae = d[V] | d[V + 1 | 0] << 8 | d[V + 2 | 0] << 16 | d[V + 3 | 0] << 24 | 0;\n                            V = P;\n                            P = 68;\n                            N = O;\n                            while (1) {\n                                ac = ($(ae, -1640531535) | 0) >>> 19;\n                                ad = N;\n                                aa = d[ad] | d[ad + 1 | 0] << 8 | d[ad + 2 | 0] << 16 | d[ad + 3 | 0] << 24 | 0;\n                                ad = Q + (ac << 1) | 0;\n                                ac = e[ad >> 1] | 0;\n                                ab = f + ac | 0;\n                                b[ad >> 1] = V - p & 65535;\n                                if ((f + (ac + 65535) | 0) >>> 0 >= V >>> 0) {\n                                    ac = ab;\n                                    ad = V;\n                                    if ((d[ac] | d[ac + 1 | 0] << 8 | d[ac + 2 | 0] << 16 | d[ac + 3 | 0] << 24 | 0) == (d[ad] | d[ad + 1 | 0] << 8 | d[ad + 2 | 0] << 16 | d[ad + 3 | 0] << 24 | 0)) {\n                                        ak = ab;\n                                        al = V;\n                                        break\n                                    }\n                                }\n                                ab = N + (P >> 6) | 0;\n                                if (ab >>> 0 > n >>> 0) {\n                                    ai = ag;\n                                    aj = t;\n                                    break L72\n                                } else {\n                                    ae = aa;\n                                    V = N;\n                                    P = P + 1 | 0;\n                                    N = ab\n                                }\n                            }\n                            while (1) {\n                                if (!(al >>> 0 > t >>> 0 & ak >>> 0 > f >>> 0)) {\n                                    break\n                                }\n                                N = al - 1 | 0;\n                                P = ak - 1 | 0;\n                                if ((a[N] | 0) == (a[P] | 0)) {\n                                    ak = P;\n                                    al = N\n                                } else {\n                                    break\n                                }\n                            }\n                            N = al;\n                            P = t;\n                            V = N - P | 0;\n                            ae = ag + 1 | 0;\n                            if ((V | 0) > 14) {\n                                ab = V - 15 | 0;\n                                a[ag] = -16;\n                                if ((ab | 0) > 254) {\n                                    aa = N - 270 - P | 0;\n                                    P = (aa >>> 0) / 255 | 0;\n                                    N = P + 1 | 0;\n                                    aR(ae | 0, -1 | 0, N | 0) | 0;\n                                    am = ag + (P + 2) | 0;\n                                    an = aa + (P * -255 | 0) & 255\n                                } else {\n                                    am = ae;\n                                    an = ab & 255\n                                }\n                                a[am] = an;\n                                ao = am + 1 | 0\n                            } else {\n                                a[ag] = V << 4 & 255;\n                                ao = ae\n                            }\n                            ae = ao + V | 0;\n                            V = ao;\n                            ab = t;\n                            while (1) {\n                                P = ab;\n                                aa = V;\n                                v = d[P] | d[P + 1 | 0] << 8 | d[P + 2 | 0] << 16 | d[P + 3 | 0] << 24 | 0;\n                                a[aa] = v & 255;\n                                v = v >> 8;\n                                a[aa + 1 | 0] = v & 255;\n                                v = v >> 8;\n                                a[aa + 2 | 0] = v & 255;\n                                v = v >> 8;\n                                a[aa + 3 | 0] = v & 255;\n                                aa = ab + 4 | 0;\n                                P = V + 4 | 0;\n                                v = d[aa] | d[aa + 1 | 0] << 8 | d[aa + 2 | 0] << 16 | d[aa + 3 | 0] << 24 | 0;\n                                a[P] = v & 255;\n                                v = v >> 8;\n                                a[P + 1 | 0] = v & 255;\n                                v = v >> 8;\n                                a[P + 2 | 0] = v & 255;\n                                v = v >> 8;\n                                a[P + 3 | 0] = v & 255;\n                                P = V + 8 | 0;\n                                if (P >>> 0 < ae >>> 0) {\n                                    V = P;\n                                    ab = ab + 8 | 0\n                                } else {\n                                    ap = ag;\n                                    aq = ak;\n                                    ar = ae;\n                                    as = al;\n                                    break\n                                }\n                            }\n                            while (1) {\n                                ae = ar;\n                                v = as - aq & 65535;\n                                a[ae] = v & 255;\n                                v = v >> 8;\n                                a[ae + 1 | 0] = v & 255;\n                                ae = ar + 2 | 0;\n                                ab = as + 4 | 0;\n                                V = aq;\n                                P = ab;\n                                while (1) {\n                                    at = V + 4 | 0;\n                                    if (P >>> 0 >= ah >>> 0) {\n                                        S = 23;\n                                        break\n                                    }\n                                    aa = at;\n                                    au = d[aa] | d[aa + 1 | 0] << 8 | d[aa + 2 | 0] << 16 | d[aa + 3 | 0] << 24 | 0;\n                                    aa = P;\n                                    av = d[aa] | d[aa + 1 | 0] << 8 | d[aa + 2 | 0] << 16 | d[aa + 3 | 0] << 24 | 0;\n                                    if ((au | 0) == (av | 0)) {\n                                        V = at;\n                                        P = P + 4 | 0\n                                    } else {\n                                        S = 22;\n                                        break\n                                    }\n                                }\n                                do {\n                                    if ((S | 0) == 22) {\n                                        S = 0;\n                                        aw = P + ((aT(av ^ au | 0) | 0) >>> 3) | 0\n                                    } else if ((S | 0) == 23) {\n                                        S = 0;\n                                        do {\n                                            if (P >>> 0 < s >>> 0) {\n                                                A = at;\n                                                C = P;\n                                                if ((d[A] | d[A + 1 | 0] << 8) << 16 >> 16 << 16 >> 16 != (d[C] | d[C + 1 | 0] << 8) << 16 >> 16 << 16 >> 16) {\n                                                    ax = at;\n                                                    ay = P;\n                                                    break\n                                                }\n                                                ax = V + 6 | 0;\n                                                ay = P + 2 | 0\n                                            } else {\n                                                ax = at;\n                                                ay = P\n                                            }\n                                        } while (0);\n                                        if (ay >>> 0 >= o >>> 0) {\n                                            aw = ay;\n                                            break\n                                        }\n                                        aw = (a[ax] | 0) == (a[ay] | 0) ? ay + 1 | 0 : ay\n                                    }\n                                } while (0);\n                                P = aw;\n                                V = ab;\n                                C = P - V | 0;\n                                A = a[ap] | 0;\n                                if ((C | 0) > 14) {\n                                    a[ap] = A + 15 & 255;\n                                    B = C - 15 | 0;\n                                    if ((B | 0) > 509) {\n                                        G = P - 525 - V | 0;\n                                        V = (G >>> 0) / 510 | 0;\n                                        H = G + (V * -510 | 0) | 0;\n                                        G = V << 1;\n                                        V = ae;\n                                        F = B;\n                                        while (1) {\n                                            a[V] = -1;\n                                            a[V + 1 | 0] = -1;\n                                            Y = F - 510 | 0;\n                                            if ((Y | 0) > 509) {\n                                                V = V + 2 | 0;\n                                                F = Y\n                                            } else {\n                                                break\n                                            }\n                                        }\n                                        az = ar + (G + 4) | 0;\n                                        aA = H\n                                    } else {\n                                        az = ae;\n                                        aA = B\n                                    }\n                                    if ((aA | 0) > 254) {\n                                        a[az] = -1;\n                                        aB = aA + 1 & 255;\n                                        aC = az + 1 | 0\n                                    } else {\n                                        aB = aA & 255;\n                                        aC = az\n                                    }\n                                    a[aC] = aB;\n                                    aD = aC + 1 | 0\n                                } else {\n                                    a[ap] = (A & 255) + C & 255;\n                                    aD = ae\n                                }\n                                if (aw >>> 0 > n >>> 0) {\n                                    ai = aD;\n                                    aj = aw;\n                                    break L72\n                                }\n                                F = aw - 2 | 0;\n                                V = F;\n                                b[Q + (($(d[V] | d[V + 1 | 0] << 8 | d[V + 2 | 0] << 16 | d[V + 3 | 0] << 24 | 0, -1640531535) | 0) >>> 19 << 1) >> 1] = F - p & 65535;\n                                F = aw;\n                                V = Q + (($(d[F] | d[F + 1 | 0] << 8 | d[F + 2 | 0] << 16 | d[F + 3 | 0] << 24 | 0, -1640531535) | 0) >>> 19 << 1) | 0;\n                                ab = e[V >> 1] | 0;\n                                Y = f + ab | 0;\n                                b[V >> 1] = P - p & 65535;\n                                if ((f + (ab + 65535) | 0) >>> 0 < aw >>> 0) {\n                                    break\n                                }\n                                ab = Y;\n                                if ((d[ab] | d[ab + 1 | 0] << 8 | d[ab + 2 | 0] << 16 | d[ab + 3 | 0] << 24 | 0) != (d[F] | d[F + 1 | 0] << 8 | d[F + 2 | 0] << 16 | d[F + 3 | 0] << 24 | 0)) {\n                                    break\n                                }\n                                a[aD] = 0;\n                                ap = aD;\n                                aq = Y;\n                                ar = aD + 1 | 0;\n                                as = aw\n                            }\n                            Y = aw + 2 | 0;\n                            if (Y >>> 0 > n >>> 0) {\n                                ai = aD;\n                                aj = aw;\n                                break\n                            } else {\n                                t = aw;\n                                ag = aD;\n                                af = aw;\n                                O = Y\n                            }\n                        }\n                    }\n                } while (0);\n                aw = l;\n                l = aj;\n                aD = aw - l | 0;\n                if ((aD | 0) > 14) {\n                    a[ai] = -16;\n                    n = aD - 15 | 0;\n                    as = ai + 1 | 0;\n                    if ((n | 0) > 254) {\n                        ar = aw - 270 - l | 0;\n                        l = (ar >>> 0) / 255 | 0;\n                        aw = l + 2 | 0;\n                        aq = l + 1 | 0;\n                        aR(as | 0, -1 | 0, aq | 0) | 0;\n                        aE = ar + (l * -255 | 0) & 255;\n                        aF = ai + aw | 0\n                    } else {\n                        aE = n & 255;\n                        aF = as\n                    }\n                    a[aF] = aE;\n                    aG = aF\n                } else {\n                    a[ai] = aD << 4 & 255;\n                    aG = ai\n                }\n                ai = aG + 1 | 0;\n                aS(ai | 0, aj | 0, aD) | 0;\n                q = aG + (aD + 1) - g | 0;\n                i = j;\n                return q | 0\n            }\n\n            function aN(b, e, f, g) {\n                b = b | 0;\n                e = e | 0;\n                f = f | 0;\n                g = g | 0;\n                var h = 0,\n                    i = 0,\n                    j = 0,\n                    k = 0,\n                    l = 0,\n                    m = 0,\n                    n = 0,\n                    o = 0,\n                    p = 0,\n                    q = 0,\n                    r = 0,\n                    s = 0,\n                    t = 0,\n                    u = 0,\n                    w = 0,\n                    x = 0,\n                    y = 0,\n                    z = 0,\n                    A = 0,\n                    B = 0,\n                    C = 0,\n                    D = 0,\n                    E = 0,\n                    F = 0,\n                    G = 0,\n                    H = 0,\n                    I = 0,\n                    J = 0,\n                    K = 0,\n                    L = 0,\n                    M = 0,\n                    N = 0,\n                    O = 0,\n                    P = 0,\n                    Q = 0,\n                    R = 0,\n                    S = 0,\n                    T = 0;\n                h = b + f | 0;\n                i = e + g | 0;\n                if ((g | 0) == 0) {\n                    if ((f | 0) != 1) {\n                        j = -1;\n                        return j | 0\n                    }\n                    j = ((a[b] | 0) != 0) << 31 >> 31;\n                    return j | 0\n                }\n                k = e + (g - 12) | 0;\n                l = b + (f - 8) | 0;\n                m = e + (g - 8) | 0;\n                n = e + (g - 5) | 0;\n                g = b + (f - 6) | 0;\n                f = b;\n                o = e;\n                L143: while (1) {\n                    p = f + 1 | 0;\n                    q = d[f] | 0;\n                    r = q >>> 4;\n                    do {\n                        if ((r | 0) == 15) {\n                            if (p >>> 0 < h >>> 0) {\n                                s = 15;\n                                t = p\n                            } else {\n                                u = p;\n                                w = 15;\n                                break\n                            }\n                            while (1) {\n                                x = t + 1 | 0;\n                                y = a[t] | 0;\n                                z = (y & 255) + s | 0;\n                                if (x >>> 0 < h >>> 0 & y << 24 >> 24 == -1) {\n                                    s = z;\n                                    t = x\n                                } else {\n                                    u = x;\n                                    w = z;\n                                    break\n                                }\n                            }\n                        } else {\n                            u = p;\n                            w = r\n                        }\n                    } while (0);\n                    A = o + w | 0;\n                    B = u + w | 0;\n                    if (A >>> 0 > k >>> 0 | B >>> 0 > l >>> 0) {\n                        C = 106;\n                        break\n                    } else {\n                        D = u;\n                        E = o\n                    }\n                    while (1) {\n                        r = D;\n                        p = E;\n                        v = d[r] | d[r + 1 | 0] << 8 | d[r + 2 | 0] << 16 | d[r + 3 | 0] << 24 | 0;\n                        a[p] = v & 255;\n                        v = v >> 8;\n                        a[p + 1 | 0] = v & 255;\n                        v = v >> 8;\n                        a[p + 2 | 0] = v & 255;\n                        v = v >> 8;\n                        a[p + 3 | 0] = v & 255;\n                        p = D + 4 | 0;\n                        r = E + 4 | 0;\n                        v = d[p] | d[p + 1 | 0] << 8 | d[p + 2 | 0] << 16 | d[p + 3 | 0] << 24 | 0;\n                        a[r] = v & 255;\n                        v = v >> 8;\n                        a[r + 1 | 0] = v & 255;\n                        v = v >> 8;\n                        a[r + 2 | 0] = v & 255;\n                        v = v >> 8;\n                        a[r + 3 | 0] = v & 255;\n                        F = E + 8 | 0;\n                        if (F >>> 0 < A >>> 0) {\n                            D = D + 8 | 0;\n                            E = F\n                        } else {\n                            break\n                        }\n                    }\n                    r = A;\n                    p = r - F | 0;\n                    z = D + (p + 8) | 0;\n                    x = w - ((d[z] | d[z + 1 | 0] << 8) << 16 >> 16 & 65535) | 0;\n                    z = o + x | 0;\n                    y = D + (p + 10) | 0;\n                    if (z >>> 0 < e >>> 0) {\n                        G = y;\n                        break\n                    }\n                    p = q & 15;\n                    L154: do {\n                        if ((p | 0) == 15) {\n                            H = y;\n                            I = 15;\n                            while (1) {\n                                if (H >>> 0 >= g >>> 0) {\n                                    J = H;\n                                    K = I;\n                                    break L154\n                                }\n                                L = H + 1 | 0;\n                                M = a[H] | 0;\n                                N = (M & 255) + I | 0;\n                                if (M << 24 >> 24 == -1) {\n                                    H = L;\n                                    I = N\n                                } else {\n                                    J = L;\n                                    K = N;\n                                    break\n                                }\n                            }\n                        } else {\n                            J = y;\n                            K = p\n                        }\n                    } while (0);\n                    if ((r - z | 0) < 4) {\n                        a[A] = a[z] | 0;\n                        a[o + (w + 1) | 0] = a[o + (x + 1) | 0] | 0;\n                        a[o + (w + 2) | 0] = a[o + (x + 2) | 0] | 0;\n                        a[o + (w + 3) | 0] = a[o + (x + 3) | 0] | 0;\n                        p = o + (w + 4) | 0;\n                        y = x + 4 | 0;\n                        q = o + (y - (c[8 + (p - (o + y) << 2) >> 2] | 0)) | 0;\n                        y = q;\n                        I = p;\n                        v = d[y] | d[y + 1 | 0] << 8 | d[y + 2 | 0] << 16 | d[y + 3 | 0] << 24 | 0;\n                        a[I] = v & 255;\n                        v = v >> 8;\n                        a[I + 1 | 0] = v & 255;\n                        v = v >> 8;\n                        a[I + 2 | 0] = v & 255;\n                        v = v >> 8;\n                        a[I + 3 | 0] = v & 255;\n                        O = q;\n                        P = p\n                    } else {\n                        p = z;\n                        q = A;\n                        v = d[p] | d[p + 1 | 0] << 8 | d[p + 2 | 0] << 16 | d[p + 3 | 0] << 24 | 0;\n                        a[q] = v & 255;\n                        v = v >> 8;\n                        a[q + 1 | 0] = v & 255;\n                        v = v >> 8;\n                        a[q + 2 | 0] = v & 255;\n                        v = v >> 8;\n                        a[q + 3 | 0] = v & 255;\n                        O = o + (x + 4) | 0;\n                        P = o + (w + 4) | 0\n                    }\n                    q = P + K | 0;\n                    if (q >>> 0 <= m >>> 0) {\n                        p = O;\n                        I = P;\n                        while (1) {\n                            y = p;\n                            H = I;\n                            v = d[y] | d[y + 1 | 0] << 8 | d[y + 2 | 0] << 16 | d[y + 3 | 0] << 24 | 0;\n                            a[H] = v & 255;\n                            v = v >> 8;\n                            a[H + 1 | 0] = v & 255;\n                            v = v >> 8;\n                            a[H + 2 | 0] = v & 255;\n                            v = v >> 8;\n                            a[H + 3 | 0] = v & 255;\n                            H = p + 4 | 0;\n                            y = I + 4 | 0;\n                            v = d[H] | d[H + 1 | 0] << 8 | d[H + 2 | 0] << 16 | d[H + 3 | 0] << 24 | 0;\n                            a[y] = v & 255;\n                            v = v >> 8;\n                            a[y + 1 | 0] = v & 255;\n                            v = v >> 8;\n                            a[y + 2 | 0] = v & 255;\n                            v = v >> 8;\n                            a[y + 3 | 0] = v & 255;\n                            y = I + 8 | 0;\n                            if (y >>> 0 < q >>> 0) {\n                                p = p + 8 | 0;\n                                I = y\n                            } else {\n                                f = J;\n                                o = q;\n                                continue L143\n                            }\n                        }\n                    }\n                    if (q >>> 0 > n >>> 0) {\n                        G = J;\n                        break\n                    } else {\n                        Q = O;\n                        R = P\n                    }\n                    do {\n                        I = Q;\n                        p = R;\n                        v = d[I] | d[I + 1 | 0] << 8 | d[I + 2 | 0] << 16 | d[I + 3 | 0] << 24 | 0;\n                        a[p] = v & 255;\n                        v = v >> 8;\n                        a[p + 1 | 0] = v & 255;\n                        v = v >> 8;\n                        a[p + 2 | 0] = v & 255;\n                        v = v >> 8;\n                        a[p + 3 | 0] = v & 255;\n                        p = Q + 4 | 0;\n                        I = R + 4 | 0;\n                        v = d[p] | d[p + 1 | 0] << 8 | d[p + 2 | 0] << 16 | d[p + 3 | 0] << 24 | 0;\n                        a[I] = v & 255;\n                        v = v >> 8;\n                        a[I + 1 | 0] = v & 255;\n                        v = v >> 8;\n                        a[I + 2 | 0] = v & 255;\n                        v = v >> 8;\n                        a[I + 3 | 0] = v & 255;\n                        R = R + 8 | 0;\n                        Q = Q + 8 | 0;\n                    } while (R >>> 0 < m >>> 0);\n                    if (R >>> 0 < q >>> 0) {\n                        S = R;\n                        T = Q\n                    } else {\n                        f = J;\n                        o = q;\n                        continue\n                    }\n                    while (1) {\n                        I = S + 1 | 0;\n                        a[S] = a[T] | 0;\n                        if (I >>> 0 < q >>> 0) {\n                            S = I;\n                            T = T + 1 | 0\n                        } else {\n                            f = J;\n                            o = q;\n                            continue L143\n                        }\n                    }\n                }\n                do {\n                    if ((C | 0) == 106) {\n                        if ((B | 0) != (h | 0) | A >>> 0 > i >>> 0) {\n                            G = u;\n                            break\n                        }\n                        aS(o | 0, u | 0, w) | 0;\n                        j = A - e | 0;\n                        return j | 0\n                    }\n                } while (0);\n                j = b - 1 - G | 0;\n                return j | 0\n            }\n\n            function aO(a, b, e) {\n                a = a | 0;\n                b = b | 0;\n                e = e | 0;\n                var f = 0,\n                    g = 0,\n                    h = 0,\n                    i = 0,\n                    j = 0,\n                    k = 0,\n                    l = 0,\n                    m = 0,\n                    n = 0,\n                    o = 0,\n                    p = 0,\n                    q = 0,\n                    r = 0,\n                    s = 0,\n                    t = 0,\n                    u = 0,\n                    v = 0,\n                    w = 0,\n                    x = 0,\n                    y = 0,\n                    z = 0,\n                    A = 0,\n                    B = 0,\n                    C = 0,\n                    D = 0,\n                    E = 0,\n                    F = 0,\n                    G = 0,\n                    H = 0;\n                f = a + b | 0;\n                g = (b | 0) > 15;\n                if ((a & 3 | 0) == 0) {\n                    if (g) {\n                        h = a + (b - 16) | 0;\n                        i = a;\n                        j = e + 606290984 | 0;\n                        k = e - 2048144777 | 0;\n                        l = e;\n                        m = e + 1640531535 | 0;\n                        do {\n                            n = i;\n                            o = ($(d[n] | d[n + 1 | 0] << 8 | d[n + 2 | 0] << 16 | d[n + 3 | 0] << 24 | 0, -2048144777) | 0) + j | 0;\n                            p = o << 13 | o >>> 19;\n                            j = $(p, -1640531535) | 0;\n                            o = i + 4 | 0;\n                            n = ($(d[o] | d[o + 1 | 0] << 8 | d[o + 2 | 0] << 16 | d[o + 3 | 0] << 24 | 0, -2048144777) | 0) + k | 0;\n                            q = n << 13 | n >>> 19;\n                            k = $(q, -1640531535) | 0;\n                            n = i + 8 | 0;\n                            o = ($(d[n] | d[n + 1 | 0] << 8 | d[n + 2 | 0] << 16 | d[n + 3 | 0] << 24 | 0, -2048144777) | 0) + l | 0;\n                            r = o << 13 | o >>> 19;\n                            l = $(r, -1640531535) | 0;\n                            o = i + 12 | 0;\n                            n = ($(d[o] | d[o + 1 | 0] << 8 | d[o + 2 | 0] << 16 | d[o + 3 | 0] << 24 | 0, -2048144777) | 0) + m | 0;\n                            s = n << 13 | n >>> 19;\n                            m = $(s, -1640531535) | 0;\n                            i = i + 16 | 0;\n                        } while (i >>> 0 <= h >>> 0);\n                        t = i;\n                        u = (k >>> 25 | ($(q, 465361024) | 0)) + (j >>> 31 | ($(p, 1013904226) | 0)) + (l >>> 20 | ($(r, 2006650880) | 0)) + (m >>> 14 | ($(s, -423362560) | 0)) | 0\n                    } else {\n                        t = a;\n                        u = e + 374761393 | 0\n                    }\n                    s = u + b | 0;\n                    u = a + (b - 4) | 0;\n                    if (t >>> 0 > u >>> 0) {\n                        v = s;\n                        w = t\n                    } else {\n                        m = s;\n                        s = t;\n                        while (1) {\n                            t = s;\n                            r = ($(d[t] | d[t + 1 | 0] << 8 | d[t + 2 | 0] << 16 | d[t + 3 | 0] << 24 | 0, -1028477379) | 0) + m | 0;\n                            t = $(r << 17 | r >>> 15, 668265263) | 0;\n                            r = s + 4 | 0;\n                            if (r >>> 0 > u >>> 0) {\n                                v = t;\n                                w = r;\n                                break\n                            } else {\n                                m = t;\n                                s = r\n                            }\n                        }\n                    }\n                    if (w >>> 0 < f >>> 0) {\n                        s = v;\n                        m = w;\n                        while (1) {\n                            w = ($(d[m] | 0, 374761393) | 0) + s | 0;\n                            u = $(w << 11 | w >>> 21, -1640531535) | 0;\n                            w = m + 1 | 0;\n                            if (w >>> 0 < f >>> 0) {\n                                s = u;\n                                m = w\n                            } else {\n                                x = u;\n                                break\n                            }\n                        }\n                    } else {\n                        x = v\n                    }\n                    v = $(x >>> 15 ^ x, -2048144777) | 0;\n                    x = $(v >>> 13 ^ v, -1028477379) | 0;\n                    y = x >>> 16 ^ x;\n                    return y | 0\n                } else {\n                    if (g) {\n                        g = a + (b - 16) | 0;\n                        x = e + 1640531535 | 0;\n                        v = e;\n                        m = e - 2048144777 | 0;\n                        s = e + 606290984 | 0;\n                        u = a;\n                        do {\n                            w = ($(c[u >> 2] | 0, -2048144777) | 0) + s | 0;\n                            z = w << 13 | w >>> 19;\n                            s = $(z, -1640531535) | 0;\n                            w = ($(c[u + 4 >> 2] | 0, -2048144777) | 0) + m | 0;\n                            A = w << 13 | w >>> 19;\n                            m = $(A, -1640531535) | 0;\n                            w = ($(c[u + 8 >> 2] | 0, -2048144777) | 0) + v | 0;\n                            B = w << 13 | w >>> 19;\n                            v = $(B, -1640531535) | 0;\n                            w = ($(c[u + 12 >> 2] | 0, -2048144777) | 0) + x | 0;\n                            C = w << 13 | w >>> 19;\n                            x = $(C, -1640531535) | 0;\n                            u = u + 16 | 0;\n                        } while (u >>> 0 <= g >>> 0);\n                        D = (m >>> 25 | ($(A, 465361024) | 0)) + (s >>> 31 | ($(z, 1013904226) | 0)) + (v >>> 20 | ($(B, 2006650880) | 0)) + (x >>> 14 | ($(C, -423362560) | 0)) | 0;\n                        E = u\n                    } else {\n                        D = e + 374761393 | 0;\n                        E = a\n                    }\n                    e = D + b | 0;\n                    D = a + (b - 4) | 0;\n                    if (E >>> 0 > D >>> 0) {\n                        F = E;\n                        G = e\n                    } else {\n                        b = E;\n                        E = e;\n                        while (1) {\n                            e = ($(c[b >> 2] | 0, -1028477379) | 0) + E | 0;\n                            a = $(e << 17 | e >>> 15, 668265263) | 0;\n                            e = b + 4 | 0;\n                            if (e >>> 0 > D >>> 0) {\n                                F = e;\n                                G = a;\n                                break\n                            } else {\n                                b = e;\n                                E = a\n                            }\n                        }\n                    }\n                    if (F >>> 0 < f >>> 0) {\n                        E = F;\n                        F = G;\n                        while (1) {\n                            b = ($(d[E] | 0, 374761393) | 0) + F | 0;\n                            D = $(b << 11 | b >>> 21, -1640531535) | 0;\n                            b = E + 1 | 0;\n                            if (b >>> 0 < f >>> 0) {\n                                E = b;\n                                F = D\n                            } else {\n                                H = D;\n                                break\n                            }\n                        }\n                    } else {\n                        H = G\n                    }\n                    G = $(H >>> 15 ^ H, -2048144777) | 0;\n                    H = $(G >>> 13 ^ G, -1028477379) | 0;\n                    y = H >>> 16 ^ H;\n                    return y | 0\n                }\n                return 0\n            }\n\n            function aP(a) {\n                a = a | 0;\n                var b = 0,\n                    d = 0,\n                    e = 0,\n                    f = 0,\n                    g = 0,\n                    h = 0,\n                    i = 0,\n                    j = 0,\n                    k = 0,\n                    l = 0,\n                    m = 0,\n                    n = 0,\n                    o = 0,\n                    p = 0,\n                    q = 0,\n                    r = 0,\n                    s = 0,\n                    t = 0,\n                    u = 0,\n                    v = 0,\n                    w = 0,\n                    x = 0,\n                    y = 0,\n                    z = 0,\n                    A = 0,\n                    B = 0,\n                    C = 0,\n                    D = 0,\n                    E = 0,\n                    F = 0,\n                    G = 0,\n                    H = 0,\n                    I = 0,\n                    J = 0,\n                    K = 0,\n                    L = 0,\n                    M = 0,\n                    N = 0,\n                    O = 0,\n                    P = 0,\n                    Q = 0,\n                    R = 0,\n                    S = 0,\n                    T = 0,\n                    U = 0,\n                    V = 0,\n                    W = 0,\n                    X = 0,\n                    Y = 0,\n                    Z = 0,\n                    _ = 0,\n                    $ = 0,\n                    aa = 0,\n                    ab = 0,\n                    ac = 0,\n                    ad = 0,\n                    ae = 0,\n                    af = 0,\n                    ag = 0,\n                    ah = 0,\n                    ai = 0,\n                    al = 0,\n                    ap = 0,\n                    aq = 0,\n                    ar = 0,\n                    as = 0,\n                    at = 0,\n                    au = 0,\n                    av = 0,\n                    aw = 0,\n                    ax = 0,\n                    ay = 0,\n                    az = 0,\n                    aA = 0,\n                    aB = 0,\n                    aC = 0,\n                    aD = 0,\n                    aE = 0,\n                    aF = 0,\n                    aG = 0,\n                    aH = 0,\n                    aI = 0,\n                    aJ = 0,\n                    aK = 0,\n                    aL = 0;\n                do {\n                    if (a >>> 0 < 245 >>> 0) {\n                        if (a >>> 0 < 11 >>> 0) {\n                            b = 16\n                        } else {\n                            b = a + 11 & -8\n                        }\n                        d = b >>> 3;\n                        e = c[16] | 0;\n                        f = e >>> (d >>> 0);\n                        if ((f & 3 | 0) != 0) {\n                            g = (f & 1 ^ 1) + d | 0;\n                            h = g << 1;\n                            i = 104 + (h << 2) | 0;\n                            j = 104 + (h + 2 << 2) | 0;\n                            h = c[j >> 2] | 0;\n                            k = h + 8 | 0;\n                            l = c[k >> 2] | 0;\n                            do {\n                                if ((i | 0) == (l | 0)) {\n                                    c[16] = e & ~(1 << g)\n                                } else {\n                                    if (l >>> 0 < (c[20] | 0) >>> 0) {\n                                        an();\n                                        return 0\n                                    }\n                                    m = l + 12 | 0;\n                                    if ((c[m >> 2] | 0) == (h | 0)) {\n                                        c[m >> 2] = i;\n                                        c[j >> 2] = l;\n                                        break\n                                    } else {\n                                        an();\n                                        return 0\n                                    }\n                                }\n                            } while (0);\n                            l = g << 3;\n                            c[h + 4 >> 2] = l | 3;\n                            j = h + (l | 4) | 0;\n                            c[j >> 2] = c[j >> 2] | 1;\n                            n = k;\n                            return n | 0\n                        }\n                        if (b >>> 0 <= (c[18] | 0) >>> 0) {\n                            o = b;\n                            break\n                        }\n                        if ((f | 0) != 0) {\n                            j = 2 << d;\n                            l = f << d & (j | -j);\n                            j = (l & -l) - 1 | 0;\n                            l = j >>> 12 & 16;\n                            i = j >>> (l >>> 0);\n                            j = i >>> 5 & 8;\n                            m = i >>> (j >>> 0);\n                            i = m >>> 2 & 4;\n                            p = m >>> (i >>> 0);\n                            m = p >>> 1 & 2;\n                            q = p >>> (m >>> 0);\n                            p = q >>> 1 & 1;\n                            r = (j | l | i | m | p) + (q >>> (p >>> 0)) | 0;\n                            p = r << 1;\n                            q = 104 + (p << 2) | 0;\n                            m = 104 + (p + 2 << 2) | 0;\n                            p = c[m >> 2] | 0;\n                            i = p + 8 | 0;\n                            l = c[i >> 2] | 0;\n                            do {\n                                if ((q | 0) == (l | 0)) {\n                                    c[16] = e & ~(1 << r)\n                                } else {\n                                    if (l >>> 0 < (c[20] | 0) >>> 0) {\n                                        an();\n                                        return 0\n                                    }\n                                    j = l + 12 | 0;\n                                    if ((c[j >> 2] | 0) == (p | 0)) {\n                                        c[j >> 2] = q;\n                                        c[m >> 2] = l;\n                                        break\n                                    } else {\n                                        an();\n                                        return 0\n                                    }\n                                }\n                            } while (0);\n                            l = r << 3;\n                            m = l - b | 0;\n                            c[p + 4 >> 2] = b | 3;\n                            q = p;\n                            e = q + b | 0;\n                            c[q + (b | 4) >> 2] = m | 1;\n                            c[q + l >> 2] = m;\n                            l = c[18] | 0;\n                            if ((l | 0) != 0) {\n                                q = c[21] | 0;\n                                d = l >>> 3;\n                                l = d << 1;\n                                f = 104 + (l << 2) | 0;\n                                k = c[16] | 0;\n                                h = 1 << d;\n                                do {\n                                    if ((k & h | 0) == 0) {\n                                        c[16] = k | h;\n                                        s = f;\n                                        t = 104 + (l + 2 << 2) | 0\n                                    } else {\n                                        d = 104 + (l + 2 << 2) | 0;\n                                        g = c[d >> 2] | 0;\n                                        if (g >>> 0 >= (c[20] | 0) >>> 0) {\n                                            s = g;\n                                            t = d;\n                                            break\n                                        }\n                                        an();\n                                        return 0\n                                    }\n                                } while (0);\n                                c[t >> 2] = q;\n                                c[s + 12 >> 2] = q;\n                                c[q + 8 >> 2] = s;\n                                c[q + 12 >> 2] = f\n                            }\n                            c[18] = m;\n                            c[21] = e;\n                            n = i;\n                            return n | 0\n                        }\n                        l = c[17] | 0;\n                        if ((l | 0) == 0) {\n                            o = b;\n                            break\n                        }\n                        h = (l & -l) - 1 | 0;\n                        l = h >>> 12 & 16;\n                        k = h >>> (l >>> 0);\n                        h = k >>> 5 & 8;\n                        p = k >>> (h >>> 0);\n                        k = p >>> 2 & 4;\n                        r = p >>> (k >>> 0);\n                        p = r >>> 1 & 2;\n                        d = r >>> (p >>> 0);\n                        r = d >>> 1 & 1;\n                        g = c[368 + ((h | l | k | p | r) + (d >>> (r >>> 0)) << 2) >> 2] | 0;\n                        r = g;\n                        d = g;\n                        p = (c[g + 4 >> 2] & -8) - b | 0;\n                        while (1) {\n                            g = c[r + 16 >> 2] | 0;\n                            if ((g | 0) == 0) {\n                                k = c[r + 20 >> 2] | 0;\n                                if ((k | 0) == 0) {\n                                    break\n                                } else {\n                                    u = k\n                                }\n                            } else {\n                                u = g\n                            }\n                            g = (c[u + 4 >> 2] & -8) - b | 0;\n                            k = g >>> 0 < p >>> 0;\n                            r = u;\n                            d = k ? u : d;\n                            p = k ? g : p\n                        }\n                        r = d;\n                        i = c[20] | 0;\n                        if (r >>> 0 < i >>> 0) {\n                            an();\n                            return 0\n                        }\n                        e = r + b | 0;\n                        m = e;\n                        if (r >>> 0 >= e >>> 0) {\n                            an();\n                            return 0\n                        }\n                        e = c[d + 24 >> 2] | 0;\n                        f = c[d + 12 >> 2] | 0;\n                        do {\n                            if ((f | 0) == (d | 0)) {\n                                q = d + 20 | 0;\n                                g = c[q >> 2] | 0;\n                                if ((g | 0) == 0) {\n                                    k = d + 16 | 0;\n                                    l = c[k >> 2] | 0;\n                                    if ((l | 0) == 0) {\n                                        v = 0;\n                                        break\n                                    } else {\n                                        w = l;\n                                        x = k\n                                    }\n                                } else {\n                                    w = g;\n                                    x = q\n                                }\n                                while (1) {\n                                    q = w + 20 | 0;\n                                    g = c[q >> 2] | 0;\n                                    if ((g | 0) != 0) {\n                                        w = g;\n                                        x = q;\n                                        continue\n                                    }\n                                    q = w + 16 | 0;\n                                    g = c[q >> 2] | 0;\n                                    if ((g | 0) == 0) {\n                                        break\n                                    } else {\n                                        w = g;\n                                        x = q\n                                    }\n                                }\n                                if (x >>> 0 < i >>> 0) {\n                                    an();\n                                    return 0\n                                } else {\n                                    c[x >> 2] = 0;\n                                    v = w;\n                                    break\n                                }\n                            } else {\n                                q = c[d + 8 >> 2] | 0;\n                                if (q >>> 0 < i >>> 0) {\n                                    an();\n                                    return 0\n                                }\n                                g = q + 12 | 0;\n                                if ((c[g >> 2] | 0) != (d | 0)) {\n                                    an();\n                                    return 0\n                                }\n                                k = f + 8 | 0;\n                                if ((c[k >> 2] | 0) == (d | 0)) {\n                                    c[g >> 2] = f;\n                                    c[k >> 2] = q;\n                                    v = f;\n                                    break\n                                } else {\n                                    an();\n                                    return 0\n                                }\n                            }\n                        } while (0);\n                        L292: do {\n                            if ((e | 0) != 0) {\n                                f = d + 28 | 0;\n                                i = 368 + (c[f >> 2] << 2) | 0;\n                                do {\n                                    if ((d | 0) == (c[i >> 2] | 0)) {\n                                        c[i >> 2] = v;\n                                        if ((v | 0) != 0) {\n                                            break\n                                        }\n                                        c[17] = c[17] & ~(1 << c[f >> 2]);\n                                        break L292\n                                    } else {\n                                        if (e >>> 0 < (c[20] | 0) >>> 0) {\n                                            an();\n                                            return 0\n                                        }\n                                        q = e + 16 | 0;\n                                        if ((c[q >> 2] | 0) == (d | 0)) {\n                                            c[q >> 2] = v\n                                        } else {\n                                            c[e + 20 >> 2] = v\n                                        }\n                                        if ((v | 0) == 0) {\n                                            break L292\n                                        }\n                                    }\n                                } while (0);\n                                if (v >>> 0 < (c[20] | 0) >>> 0) {\n                                    an();\n                                    return 0\n                                }\n                                c[v + 24 >> 2] = e;\n                                f = c[d + 16 >> 2] | 0;\n                                do {\n                                    if ((f | 0) != 0) {\n                                        if (f >>> 0 < (c[20] | 0) >>> 0) {\n                                            an();\n                                            return 0\n                                        } else {\n                                            c[v + 16 >> 2] = f;\n                                            c[f + 24 >> 2] = v;\n                                            break\n                                        }\n                                    }\n                                } while (0);\n                                f = c[d + 20 >> 2] | 0;\n                                if ((f | 0) == 0) {\n                                    break\n                                }\n                                if (f >>> 0 < (c[20] | 0) >>> 0) {\n                                    an();\n                                    return 0\n                                } else {\n                                    c[v + 20 >> 2] = f;\n                                    c[f + 24 >> 2] = v;\n                                    break\n                                }\n                            }\n                        } while (0);\n                        if (p >>> 0 < 16 >>> 0) {\n                            e = p + b | 0;\n                            c[d + 4 >> 2] = e | 3;\n                            f = r + (e + 4) | 0;\n                            c[f >> 2] = c[f >> 2] | 1\n                        } else {\n                            c[d + 4 >> 2] = b | 3;\n                            c[r + (b | 4) >> 2] = p | 1;\n                            c[r + (p + b) >> 2] = p;\n                            f = c[18] | 0;\n                            if ((f | 0) != 0) {\n                                e = c[21] | 0;\n                                i = f >>> 3;\n                                f = i << 1;\n                                q = 104 + (f << 2) | 0;\n                                k = c[16] | 0;\n                                g = 1 << i;\n                                do {\n                                    if ((k & g | 0) == 0) {\n                                        c[16] = k | g;\n                                        y = q;\n                                        z = 104 + (f + 2 << 2) | 0\n                                    } else {\n                                        i = 104 + (f + 2 << 2) | 0;\n                                        l = c[i >> 2] | 0;\n                                        if (l >>> 0 >= (c[20] | 0) >>> 0) {\n                                            y = l;\n                                            z = i;\n                                            break\n                                        }\n                                        an();\n                                        return 0\n                                    }\n                                } while (0);\n                                c[z >> 2] = e;\n                                c[y + 12 >> 2] = e;\n                                c[e + 8 >> 2] = y;\n                                c[e + 12 >> 2] = q\n                            }\n                            c[18] = p;\n                            c[21] = m\n                        }\n                        f = d + 8 | 0;\n                        if ((f | 0) == 0) {\n                            o = b;\n                            break\n                        } else {\n                            n = f\n                        }\n                        return n | 0\n                    } else {\n                        if (a >>> 0 > 4294967231 >>> 0) {\n                            o = -1;\n                            break\n                        }\n                        f = a + 11 | 0;\n                        g = f & -8;\n                        k = c[17] | 0;\n                        if ((k | 0) == 0) {\n                            o = g;\n                            break\n                        }\n                        r = -g | 0;\n                        i = f >>> 8;\n                        do {\n                            if ((i | 0) == 0) {\n                                A = 0\n                            } else {\n                                if (g >>> 0 > 16777215 >>> 0) {\n                                    A = 31;\n                                    break\n                                }\n                                f = (i + 1048320 | 0) >>> 16 & 8;\n                                l = i << f;\n                                h = (l + 520192 | 0) >>> 16 & 4;\n                                j = l << h;\n                                l = (j + 245760 | 0) >>> 16 & 2;\n                                B = 14 - (h | f | l) + (j << l >>> 15) | 0;\n                                A = g >>> ((B + 7 | 0) >>> 0) & 1 | B << 1\n                            }\n                        } while (0);\n                        i = c[368 + (A << 2) >> 2] | 0;\n                        L340: do {\n                            if ((i | 0) == 0) {\n                                C = 0;\n                                D = r;\n                                E = 0\n                            } else {\n                                if ((A | 0) == 31) {\n                                    F = 0\n                                } else {\n                                    F = 25 - (A >>> 1) | 0\n                                }\n                                d = 0;\n                                m = r;\n                                p = i;\n                                q = g << F;\n                                e = 0;\n                                while (1) {\n                                    B = c[p + 4 >> 2] & -8;\n                                    l = B - g | 0;\n                                    if (l >>> 0 < m >>> 0) {\n                                        if ((B | 0) == (g | 0)) {\n                                            C = p;\n                                            D = l;\n                                            E = p;\n                                            break L340\n                                        } else {\n                                            G = p;\n                                            H = l\n                                        }\n                                    } else {\n                                        G = d;\n                                        H = m\n                                    }\n                                    l = c[p + 20 >> 2] | 0;\n                                    B = c[p + 16 + (q >>> 31 << 2) >> 2] | 0;\n                                    j = (l | 0) == 0 | (l | 0) == (B | 0) ? e : l;\n                                    if ((B | 0) == 0) {\n                                        C = G;\n                                        D = H;\n                                        E = j;\n                                        break\n                                    } else {\n                                        d = G;\n                                        m = H;\n                                        p = B;\n                                        q = q << 1;\n                                        e = j\n                                    }\n                                }\n                            }\n                        } while (0);\n                        if ((E | 0) == 0 & (C | 0) == 0) {\n                            i = 2 << A;\n                            r = k & (i | -i);\n                            if ((r | 0) == 0) {\n                                o = g;\n                                break\n                            }\n                            i = (r & -r) - 1 | 0;\n                            r = i >>> 12 & 16;\n                            e = i >>> (r >>> 0);\n                            i = e >>> 5 & 8;\n                            q = e >>> (i >>> 0);\n                            e = q >>> 2 & 4;\n                            p = q >>> (e >>> 0);\n                            q = p >>> 1 & 2;\n                            m = p >>> (q >>> 0);\n                            p = m >>> 1 & 1;\n                            I = c[368 + ((i | r | e | q | p) + (m >>> (p >>> 0)) << 2) >> 2] | 0\n                        } else {\n                            I = E\n                        }\n                        if ((I | 0) == 0) {\n                            J = D;\n                            K = C\n                        } else {\n                            p = I;\n                            m = D;\n                            q = C;\n                            while (1) {\n                                e = (c[p + 4 >> 2] & -8) - g | 0;\n                                r = e >>> 0 < m >>> 0;\n                                i = r ? e : m;\n                                e = r ? p : q;\n                                r = c[p + 16 >> 2] | 0;\n                                if ((r | 0) != 0) {\n                                    p = r;\n                                    m = i;\n                                    q = e;\n                                    continue\n                                }\n                                r = c[p + 20 >> 2] | 0;\n                                if ((r | 0) == 0) {\n                                    J = i;\n                                    K = e;\n                                    break\n                                } else {\n                                    p = r;\n                                    m = i;\n                                    q = e\n                                }\n                            }\n                        }\n                        if ((K | 0) == 0) {\n                            o = g;\n                            break\n                        }\n                        if (J >>> 0 >= ((c[18] | 0) - g | 0) >>> 0) {\n                            o = g;\n                            break\n                        }\n                        q = K;\n                        m = c[20] | 0;\n                        if (q >>> 0 < m >>> 0) {\n                            an();\n                            return 0\n                        }\n                        p = q + g | 0;\n                        k = p;\n                        if (q >>> 0 >= p >>> 0) {\n                            an();\n                            return 0\n                        }\n                        e = c[K + 24 >> 2] | 0;\n                        i = c[K + 12 >> 2] | 0;\n                        do {\n                            if ((i | 0) == (K | 0)) {\n                                r = K + 20 | 0;\n                                d = c[r >> 2] | 0;\n                                if ((d | 0) == 0) {\n                                    j = K + 16 | 0;\n                                    B = c[j >> 2] | 0;\n                                    if ((B | 0) == 0) {\n                                        L = 0;\n                                        break\n                                    } else {\n                                        M = B;\n                                        N = j\n                                    }\n                                } else {\n                                    M = d;\n                                    N = r\n                                }\n                                while (1) {\n                                    r = M + 20 | 0;\n                                    d = c[r >> 2] | 0;\n                                    if ((d | 0) != 0) {\n                                        M = d;\n                                        N = r;\n                                        continue\n                                    }\n                                    r = M + 16 | 0;\n                                    d = c[r >> 2] | 0;\n                                    if ((d | 0) == 0) {\n                                        break\n                                    } else {\n                                        M = d;\n                                        N = r\n                                    }\n                                }\n                                if (N >>> 0 < m >>> 0) {\n                                    an();\n                                    return 0\n                                } else {\n                                    c[N >> 2] = 0;\n                                    L = M;\n                                    break\n                                }\n                            } else {\n                                r = c[K + 8 >> 2] | 0;\n                                if (r >>> 0 < m >>> 0) {\n                                    an();\n                                    return 0\n                                }\n                                d = r + 12 | 0;\n                                if ((c[d >> 2] | 0) != (K | 0)) {\n                                    an();\n                                    return 0\n                                }\n                                j = i + 8 | 0;\n                                if ((c[j >> 2] | 0) == (K | 0)) {\n                                    c[d >> 2] = i;\n                                    c[j >> 2] = r;\n                                    L = i;\n                                    break\n                                } else {\n                                    an();\n                                    return 0\n                                }\n                            }\n                        } while (0);\n                        L390: do {\n                            if ((e | 0) != 0) {\n                                i = K + 28 | 0;\n                                m = 368 + (c[i >> 2] << 2) | 0;\n                                do {\n                                    if ((K | 0) == (c[m >> 2] | 0)) {\n                                        c[m >> 2] = L;\n                                        if ((L | 0) != 0) {\n                                            break\n                                        }\n                                        c[17] = c[17] & ~(1 << c[i >> 2]);\n                                        break L390\n                                    } else {\n                                        if (e >>> 0 < (c[20] | 0) >>> 0) {\n                                            an();\n                                            return 0\n                                        }\n                                        r = e + 16 | 0;\n                                        if ((c[r >> 2] | 0) == (K | 0)) {\n                                            c[r >> 2] = L\n                                        } else {\n                                            c[e + 20 >> 2] = L\n                                        }\n                                        if ((L | 0) == 0) {\n                                            break L390\n                                        }\n                                    }\n                                } while (0);\n                                if (L >>> 0 < (c[20] | 0) >>> 0) {\n                                    an();\n                                    return 0\n                                }\n                                c[L + 24 >> 2] = e;\n                                i = c[K + 16 >> 2] | 0;\n                                do {\n                                    if ((i | 0) != 0) {\n                                        if (i >>> 0 < (c[20] | 0) >>> 0) {\n                                            an();\n                                            return 0\n                                        } else {\n                                            c[L + 16 >> 2] = i;\n                                            c[i + 24 >> 2] = L;\n                                            break\n                                        }\n                                    }\n                                } while (0);\n                                i = c[K + 20 >> 2] | 0;\n                                if ((i | 0) == 0) {\n                                    break\n                                }\n                                if (i >>> 0 < (c[20] | 0) >>> 0) {\n                                    an();\n                                    return 0\n                                } else {\n                                    c[L + 20 >> 2] = i;\n                                    c[i + 24 >> 2] = L;\n                                    break\n                                }\n                            }\n                        } while (0);\n                        do {\n                            if (J >>> 0 < 16 >>> 0) {\n                                e = J + g | 0;\n                                c[K + 4 >> 2] = e | 3;\n                                i = q + (e + 4) | 0;\n                                c[i >> 2] = c[i >> 2] | 1\n                            } else {\n                                c[K + 4 >> 2] = g | 3;\n                                c[q + (g | 4) >> 2] = J | 1;\n                                c[q + (J + g) >> 2] = J;\n                                i = J >>> 3;\n                                if (J >>> 0 < 256 >>> 0) {\n                                    e = i << 1;\n                                    m = 104 + (e << 2) | 0;\n                                    r = c[16] | 0;\n                                    j = 1 << i;\n                                    do {\n                                        if ((r & j | 0) == 0) {\n                                            c[16] = r | j;\n                                            O = m;\n                                            P = 104 + (e + 2 << 2) | 0\n                                        } else {\n                                            i = 104 + (e + 2 << 2) | 0;\n                                            d = c[i >> 2] | 0;\n                                            if (d >>> 0 >= (c[20] | 0) >>> 0) {\n                                                O = d;\n                                                P = i;\n                                                break\n                                            }\n                                            an();\n                                            return 0\n                                        }\n                                    } while (0);\n                                    c[P >> 2] = k;\n                                    c[O + 12 >> 2] = k;\n                                    c[q + (g + 8) >> 2] = O;\n                                    c[q + (g + 12) >> 2] = m;\n                                    break\n                                }\n                                e = p;\n                                j = J >>> 8;\n                                do {\n                                    if ((j | 0) == 0) {\n                                        Q = 0\n                                    } else {\n                                        if (J >>> 0 > 16777215 >>> 0) {\n                                            Q = 31;\n                                            break\n                                        }\n                                        r = (j + 1048320 | 0) >>> 16 & 8;\n                                        i = j << r;\n                                        d = (i + 520192 | 0) >>> 16 & 4;\n                                        B = i << d;\n                                        i = (B + 245760 | 0) >>> 16 & 2;\n                                        l = 14 - (d | r | i) + (B << i >>> 15) | 0;\n                                        Q = J >>> ((l + 7 | 0) >>> 0) & 1 | l << 1\n                                    }\n                                } while (0);\n                                j = 368 + (Q << 2) | 0;\n                                c[q + (g + 28) >> 2] = Q;\n                                c[q + (g + 20) >> 2] = 0;\n                                c[q + (g + 16) >> 2] = 0;\n                                m = c[17] | 0;\n                                l = 1 << Q;\n                                if ((m & l | 0) == 0) {\n                                    c[17] = m | l;\n                                    c[j >> 2] = e;\n                                    c[q + (g + 24) >> 2] = j;\n                                    c[q + (g + 12) >> 2] = e;\n                                    c[q + (g + 8) >> 2] = e;\n                                    break\n                                }\n                                if ((Q | 0) == 31) {\n                                    R = 0\n                                } else {\n                                    R = 25 - (Q >>> 1) | 0\n                                }\n                                l = J << R;\n                                m = c[j >> 2] | 0;\n                                while (1) {\n                                    if ((c[m + 4 >> 2] & -8 | 0) == (J | 0)) {\n                                        break\n                                    }\n                                    S = m + 16 + (l >>> 31 << 2) | 0;\n                                    j = c[S >> 2] | 0;\n                                    if ((j | 0) == 0) {\n                                        T = 302;\n                                        break\n                                    } else {\n                                        l = l << 1;\n                                        m = j\n                                    }\n                                }\n                                if ((T | 0) == 302) {\n                                    if (S >>> 0 < (c[20] | 0) >>> 0) {\n                                        an();\n                                        return 0\n                                    } else {\n                                        c[S >> 2] = e;\n                                        c[q + (g + 24) >> 2] = m;\n                                        c[q + (g + 12) >> 2] = e;\n                                        c[q + (g + 8) >> 2] = e;\n                                        break\n                                    }\n                                }\n                                l = m + 8 | 0;\n                                j = c[l >> 2] | 0;\n                                i = c[20] | 0;\n                                if (m >>> 0 < i >>> 0) {\n                                    an();\n                                    return 0\n                                }\n                                if (j >>> 0 < i >>> 0) {\n                                    an();\n                                    return 0\n                                } else {\n                                    c[j + 12 >> 2] = e;\n                                    c[l >> 2] = e;\n                                    c[q + (g + 8) >> 2] = j;\n                                    c[q + (g + 12) >> 2] = m;\n                                    c[q + (g + 24) >> 2] = 0;\n                                    break\n                                }\n                            }\n                        } while (0);\n                        q = K + 8 | 0;\n                        if ((q | 0) == 0) {\n                            o = g;\n                            break\n                        } else {\n                            n = q\n                        }\n                        return n | 0\n                    }\n                } while (0);\n                K = c[18] | 0;\n                if (o >>> 0 <= K >>> 0) {\n                    S = K - o | 0;\n                    J = c[21] | 0;\n                    if (S >>> 0 > 15 >>> 0) {\n                        R = J;\n                        c[21] = R + o;\n                        c[18] = S;\n                        c[R + (o + 4) >> 2] = S | 1;\n                        c[R + K >> 2] = S;\n                        c[J + 4 >> 2] = o | 3\n                    } else {\n                        c[18] = 0;\n                        c[21] = 0;\n                        c[J + 4 >> 2] = K | 3;\n                        S = J + (K + 4) | 0;\n                        c[S >> 2] = c[S >> 2] | 1\n                    }\n                    n = J + 8 | 0;\n                    return n | 0\n                }\n                J = c[19] | 0;\n                if (o >>> 0 < J >>> 0) {\n                    S = J - o | 0;\n                    c[19] = S;\n                    J = c[22] | 0;\n                    K = J;\n                    c[22] = K + o;\n                    c[K + (o + 4) >> 2] = S | 1;\n                    c[J + 4 >> 2] = o | 3;\n                    n = J + 8 | 0;\n                    return n | 0\n                }\n                do {\n                    if ((c[10] | 0) == 0) {\n                        J = aj(30) | 0;\n                        if ((J - 1 & J | 0) == 0) {\n                            c[12] = J;\n                            c[11] = J;\n                            c[13] = -1;\n                            c[14] = -1;\n                            c[15] = 0;\n                            c[127] = 0;\n                            c[10] = (ao(0) | 0) & -16 ^ 1431655768;\n                            break\n                        } else {\n                            an();\n                            return 0\n                        }\n                    }\n                } while (0);\n                J = o + 48 | 0;\n                S = c[12] | 0;\n                K = o + 47 | 0;\n                R = S + K | 0;\n                Q = -S | 0;\n                S = R & Q;\n                if (S >>> 0 <= o >>> 0) {\n                    n = 0;\n                    return n | 0\n                }\n                O = c[126] | 0;\n                do {\n                    if ((O | 0) != 0) {\n                        P = c[124] | 0;\n                        L = P + S | 0;\n                        if (L >>> 0 <= P >>> 0 | L >>> 0 > O >>> 0) {\n                            n = 0\n                        } else {\n                            break\n                        }\n                        return n | 0\n                    }\n                } while (0);\n                L482: do {\n                    if ((c[127] & 4 | 0) == 0) {\n                        O = c[22] | 0;\n                        L484: do {\n                            if ((O | 0) == 0) {\n                                T = 332\n                            } else {\n                                L = O;\n                                P = 512;\n                                while (1) {\n                                    U = P | 0;\n                                    M = c[U >> 2] | 0;\n                                    if (M >>> 0 <= L >>> 0) {\n                                        V = P + 4 | 0;\n                                        if ((M + (c[V >> 2] | 0) | 0) >>> 0 > L >>> 0) {\n                                            break\n                                        }\n                                    }\n                                    M = c[P + 8 >> 2] | 0;\n                                    if ((M | 0) == 0) {\n                                        T = 332;\n                                        break L484\n                                    } else {\n                                        P = M\n                                    }\n                                }\n                                if ((P | 0) == 0) {\n                                    T = 332;\n                                    break\n                                }\n                                L = R - (c[19] | 0) & Q;\n                                if (L >>> 0 >= 2147483647 >>> 0) {\n                                    W = 0;\n                                    break\n                                }\n                                m = ak(L | 0) | 0;\n                                e = (m | 0) == ((c[U >> 2] | 0) + (c[V >> 2] | 0) | 0);\n                                X = e ? m : -1;\n                                Y = e ? L : 0;\n                                Z = m;\n                                _ = L;\n                                T = 341\n                            }\n                        } while (0);\n                        do {\n                            if ((T | 0) == 332) {\n                                O = ak(0) | 0;\n                                if ((O | 0) == -1) {\n                                    W = 0;\n                                    break\n                                }\n                                g = O;\n                                L = c[11] | 0;\n                                m = L - 1 | 0;\n                                if ((m & g | 0) == 0) {\n                                    $ = S\n                                } else {\n                                    $ = S - g + (m + g & -L) | 0\n                                }\n                                L = c[124] | 0;\n                                g = L + $ | 0;\n                                if (!($ >>> 0 > o >>> 0 & $ >>> 0 < 2147483647 >>> 0)) {\n                                    W = 0;\n                                    break\n                                }\n                                m = c[126] | 0;\n                                if ((m | 0) != 0) {\n                                    if (g >>> 0 <= L >>> 0 | g >>> 0 > m >>> 0) {\n                                        W = 0;\n                                        break\n                                    }\n                                }\n                                m = ak($ | 0) | 0;\n                                g = (m | 0) == (O | 0);\n                                X = g ? O : -1;\n                                Y = g ? $ : 0;\n                                Z = m;\n                                _ = $;\n                                T = 341\n                            }\n                        } while (0);\n                        L504: do {\n                            if ((T | 0) == 341) {\n                                m = -_ | 0;\n                                if ((X | 0) != -1) {\n                                    aa = Y;\n                                    ab = X;\n                                    T = 352;\n                                    break L482\n                                }\n                                do {\n                                    if ((Z | 0) != -1 & _ >>> 0 < 2147483647 >>> 0 & _ >>> 0 < J >>> 0) {\n                                        g = c[12] | 0;\n                                        O = K - _ + g & -g;\n                                        if (O >>> 0 >= 2147483647 >>> 0) {\n                                            ac = _;\n                                            break\n                                        }\n                                        if ((ak(O | 0) | 0) == -1) {\n                                            ak(m | 0) | 0;\n                                            W = Y;\n                                            break L504\n                                        } else {\n                                            ac = O + _ | 0;\n                                            break\n                                        }\n                                    } else {\n                                        ac = _\n                                    }\n                                } while (0);\n                                if ((Z | 0) == -1) {\n                                    W = Y\n                                } else {\n                                    aa = ac;\n                                    ab = Z;\n                                    T = 352;\n                                    break L482\n                                }\n                            }\n                        } while (0);\n                        c[127] = c[127] | 4;\n                        ad = W;\n                        T = 349\n                    } else {\n                        ad = 0;\n                        T = 349\n                    }\n                } while (0);\n                do {\n                    if ((T | 0) == 349) {\n                        if (S >>> 0 >= 2147483647 >>> 0) {\n                            break\n                        }\n                        W = ak(S | 0) | 0;\n                        Z = ak(0) | 0;\n                        if (!((Z | 0) != -1 & (W | 0) != -1 & W >>> 0 < Z >>> 0)) {\n                            break\n                        }\n                        ac = Z - W | 0;\n                        Z = ac >>> 0 > (o + 40 | 0) >>> 0;\n                        Y = Z ? W : -1;\n                        if ((Y | 0) != -1) {\n                            aa = Z ? ac : ad;\n                            ab = Y;\n                            T = 352\n                        }\n                    }\n                } while (0);\n                do {\n                    if ((T | 0) == 352) {\n                        ad = (c[124] | 0) + aa | 0;\n                        c[124] = ad;\n                        if (ad >>> 0 > (c[125] | 0) >>> 0) {\n                            c[125] = ad\n                        }\n                        ad = c[22] | 0;\n                        L524: do {\n                            if ((ad | 0) == 0) {\n                                S = c[20] | 0;\n                                if ((S | 0) == 0 | ab >>> 0 < S >>> 0) {\n                                    c[20] = ab\n                                }\n                                c[128] = ab;\n                                c[129] = aa;\n                                c[131] = 0;\n                                c[25] = c[10];\n                                c[24] = -1;\n                                S = 0;\n                                do {\n                                    Y = S << 1;\n                                    ac = 104 + (Y << 2) | 0;\n                                    c[104 + (Y + 3 << 2) >> 2] = ac;\n                                    c[104 + (Y + 2 << 2) >> 2] = ac;\n                                    S = S + 1 | 0;\n                                } while (S >>> 0 < 32 >>> 0);\n                                S = ab + 8 | 0;\n                                if ((S & 7 | 0) == 0) {\n                                    ae = 0\n                                } else {\n                                    ae = -S & 7\n                                }\n                                S = aa - 40 - ae | 0;\n                                c[22] = ab + ae;\n                                c[19] = S;\n                                c[ab + (ae + 4) >> 2] = S | 1;\n                                c[ab + (aa - 36) >> 2] = 40;\n                                c[23] = c[14]\n                            } else {\n                                S = 512;\n                                while (1) {\n                                    af = c[S >> 2] | 0;\n                                    ag = S + 4 | 0;\n                                    ah = c[ag >> 2] | 0;\n                                    if ((ab | 0) == (af + ah | 0)) {\n                                        T = 364;\n                                        break\n                                    }\n                                    ac = c[S + 8 >> 2] | 0;\n                                    if ((ac | 0) == 0) {\n                                        break\n                                    } else {\n                                        S = ac\n                                    }\n                                }\n                                do {\n                                    if ((T | 0) == 364) {\n                                        if ((c[S + 12 >> 2] & 8 | 0) != 0) {\n                                            break\n                                        }\n                                        ac = ad;\n                                        if (!(ac >>> 0 >= af >>> 0 & ac >>> 0 < ab >>> 0)) {\n                                            break\n                                        }\n                                        c[ag >> 2] = ah + aa;\n                                        ac = c[22] | 0;\n                                        Y = (c[19] | 0) + aa | 0;\n                                        Z = ac;\n                                        W = ac + 8 | 0;\n                                        if ((W & 7 | 0) == 0) {\n                                            ai = 0\n                                        } else {\n                                            ai = -W & 7\n                                        }\n                                        W = Y - ai | 0;\n                                        c[22] = Z + ai;\n                                        c[19] = W;\n                                        c[Z + (ai + 4) >> 2] = W | 1;\n                                        c[Z + (Y + 4) >> 2] = 40;\n                                        c[23] = c[14];\n                                        break L524\n                                    }\n                                } while (0);\n                                if (ab >>> 0 < (c[20] | 0) >>> 0) {\n                                    c[20] = ab\n                                }\n                                S = ab + aa | 0;\n                                Y = 512;\n                                while (1) {\n                                    al = Y | 0;\n                                    if ((c[al >> 2] | 0) == (S | 0)) {\n                                        T = 374;\n                                        break\n                                    }\n                                    Z = c[Y + 8 >> 2] | 0;\n                                    if ((Z | 0) == 0) {\n                                        break\n                                    } else {\n                                        Y = Z\n                                    }\n                                }\n                                do {\n                                    if ((T | 0) == 374) {\n                                        if ((c[Y + 12 >> 2] & 8 | 0) != 0) {\n                                            break\n                                        }\n                                        c[al >> 2] = ab;\n                                        S = Y + 4 | 0;\n                                        c[S >> 2] = (c[S >> 2] | 0) + aa;\n                                        S = ab + 8 | 0;\n                                        if ((S & 7 | 0) == 0) {\n                                            ap = 0\n                                        } else {\n                                            ap = -S & 7\n                                        }\n                                        S = ab + (aa + 8) | 0;\n                                        if ((S & 7 | 0) == 0) {\n                                            aq = 0\n                                        } else {\n                                            aq = -S & 7\n                                        }\n                                        S = ab + (aq + aa) | 0;\n                                        Z = S;\n                                        W = ap + o | 0;\n                                        ac = ab + W | 0;\n                                        _ = ac;\n                                        K = S - (ab + ap) - o | 0;\n                                        c[ab + (ap + 4) >> 2] = o | 3;\n                                        do {\n                                            if ((Z | 0) == (c[22] | 0)) {\n                                                J = (c[19] | 0) + K | 0;\n                                                c[19] = J;\n                                                c[22] = _;\n                                                c[ab + (W + 4) >> 2] = J | 1\n                                            } else {\n                                                if ((Z | 0) == (c[21] | 0)) {\n                                                    J = (c[18] | 0) + K | 0;\n                                                    c[18] = J;\n                                                    c[21] = _;\n                                                    c[ab + (W + 4) >> 2] = J | 1;\n                                                    c[ab + (J + W) >> 2] = J;\n                                                    break\n                                                }\n                                                J = aa + 4 | 0;\n                                                X = c[ab + (J + aq) >> 2] | 0;\n                                                if ((X & 3 | 0) == 1) {\n                                                    $ = X & -8;\n                                                    V = X >>> 3;\n                                                    L569: do {\n                                                        if (X >>> 0 < 256 >>> 0) {\n                                                            U = c[ab + ((aq | 8) + aa) >> 2] | 0;\n                                                            Q = c[ab + (aa + 12 + aq) >> 2] | 0;\n                                                            R = 104 + (V << 1 << 2) | 0;\n                                                            do {\n                                                                if ((U | 0) != (R | 0)) {\n                                                                    if (U >>> 0 < (c[20] | 0) >>> 0) {\n                                                                        an();\n                                                                        return 0\n                                                                    }\n                                                                    if ((c[U + 12 >> 2] | 0) == (Z | 0)) {\n                                                                        break\n                                                                    }\n                                                                    an();\n                                                                    return 0\n                                                                }\n                                                            } while (0);\n                                                            if ((Q | 0) == (U | 0)) {\n                                                                c[16] = c[16] & ~(1 << V);\n                                                                break\n                                                            }\n                                                            do {\n                                                                if ((Q | 0) == (R | 0)) {\n                                                                    ar = Q + 8 | 0\n                                                                } else {\n                                                                    if (Q >>> 0 < (c[20] | 0) >>> 0) {\n                                                                        an();\n                                                                        return 0\n                                                                    }\n                                                                    m = Q + 8 | 0;\n                                                                    if ((c[m >> 2] | 0) == (Z | 0)) {\n                                                                        ar = m;\n                                                                        break\n                                                                    }\n                                                                    an();\n                                                                    return 0\n                                                                }\n                                                            } while (0);\n                                                            c[U + 12 >> 2] = Q;\n                                                            c[ar >> 2] = U\n                                                        } else {\n                                                            R = S;\n                                                            m = c[ab + ((aq | 24) + aa) >> 2] | 0;\n                                                            P = c[ab + (aa + 12 + aq) >> 2] | 0;\n                                                            do {\n                                                                if ((P | 0) == (R | 0)) {\n                                                                    O = aq | 16;\n                                                                    g = ab + (J + O) | 0;\n                                                                    L = c[g >> 2] | 0;\n                                                                    if ((L | 0) == 0) {\n                                                                        e = ab + (O + aa) | 0;\n                                                                        O = c[e >> 2] | 0;\n                                                                        if ((O | 0) == 0) {\n                                                                            as = 0;\n                                                                            break\n                                                                        } else {\n                                                                            at = O;\n                                                                            au = e\n                                                                        }\n                                                                    } else {\n                                                                        at = L;\n                                                                        au = g\n                                                                    }\n                                                                    while (1) {\n                                                                        g = at + 20 | 0;\n                                                                        L = c[g >> 2] | 0;\n                                                                        if ((L | 0) != 0) {\n                                                                            at = L;\n                                                                            au = g;\n                                                                            continue\n                                                                        }\n                                                                        g = at + 16 | 0;\n                                                                        L = c[g >> 2] | 0;\n                                                                        if ((L | 0) == 0) {\n                                                                            break\n                                                                        } else {\n                                                                            at = L;\n                                                                            au = g\n                                                                        }\n                                                                    }\n                                                                    if (au >>> 0 < (c[20] | 0) >>> 0) {\n                                                                        an();\n                                                                        return 0\n                                                                    } else {\n                                                                        c[au >> 2] = 0;\n                                                                        as = at;\n                                                                        break\n                                                                    }\n                                                                } else {\n                                                                    g = c[ab + ((aq | 8) + aa) >> 2] | 0;\n                                                                    if (g >>> 0 < (c[20] | 0) >>> 0) {\n                                                                        an();\n                                                                        return 0\n                                                                    }\n                                                                    L = g + 12 | 0;\n                                                                    if ((c[L >> 2] | 0) != (R | 0)) {\n                                                                        an();\n                                                                        return 0\n                                                                    }\n                                                                    e = P + 8 | 0;\n                                                                    if ((c[e >> 2] | 0) == (R | 0)) {\n                                                                        c[L >> 2] = P;\n                                                                        c[e >> 2] = g;\n                                                                        as = P;\n                                                                        break\n                                                                    } else {\n                                                                        an();\n                                                                        return 0\n                                                                    }\n                                                                }\n                                                            } while (0);\n                                                            if ((m | 0) == 0) {\n                                                                break\n                                                            }\n                                                            P = ab + (aa + 28 + aq) | 0;\n                                                            U = 368 + (c[P >> 2] << 2) | 0;\n                                                            do {\n                                                                if ((R | 0) == (c[U >> 2] | 0)) {\n                                                                    c[U >> 2] = as;\n                                                                    if ((as | 0) != 0) {\n                                                                        break\n                                                                    }\n                                                                    c[17] = c[17] & ~(1 << c[P >> 2]);\n                                                                    break L569\n                                                                } else {\n                                                                    if (m >>> 0 < (c[20] | 0) >>> 0) {\n                                                                        an();\n                                                                        return 0\n                                                                    }\n                                                                    Q = m + 16 | 0;\n                                                                    if ((c[Q >> 2] | 0) == (R | 0)) {\n                                                                        c[Q >> 2] = as\n                                                                    } else {\n                                                                        c[m + 20 >> 2] = as\n                                                                    }\n                                                                    if ((as | 0) == 0) {\n                                                                        break L569\n                                                                    }\n                                                                }\n                                                            } while (0);\n                                                            if (as >>> 0 < (c[20] | 0) >>> 0) {\n                                                                an();\n                                                                return 0\n                                                            }\n                                                            c[as + 24 >> 2] = m;\n                                                            R = aq | 16;\n                                                            P = c[ab + (R + aa) >> 2] | 0;\n                                                            do {\n                                                                if ((P | 0) != 0) {\n                                                                    if (P >>> 0 < (c[20] | 0) >>> 0) {\n                                                                        an();\n                                                                        return 0\n                                                                    } else {\n                                                                        c[as + 16 >> 2] = P;\n                                                                        c[P + 24 >> 2] = as;\n                                                                        break\n                                                                    }\n                                                                }\n                                                            } while (0);\n                                                            P = c[ab + (J + R) >> 2] | 0;\n                                                            if ((P | 0) == 0) {\n                                                                break\n                                                            }\n                                                            if (P >>> 0 < (c[20] | 0) >>> 0) {\n                                                                an();\n                                                                return 0\n                                                            } else {\n                                                                c[as + 20 >> 2] = P;\n                                                                c[P + 24 >> 2] = as;\n                                                                break\n                                                            }\n                                                        }\n                                                    } while (0);\n                                                    av = ab + (($ | aq) + aa) | 0;\n                                                    aw = $ + K | 0\n                                                } else {\n                                                    av = Z;\n                                                    aw = K\n                                                }\n                                                J = av + 4 | 0;\n                                                c[J >> 2] = c[J >> 2] & -2;\n                                                c[ab + (W + 4) >> 2] = aw | 1;\n                                                c[ab + (aw + W) >> 2] = aw;\n                                                J = aw >>> 3;\n                                                if (aw >>> 0 < 256 >>> 0) {\n                                                    V = J << 1;\n                                                    X = 104 + (V << 2) | 0;\n                                                    P = c[16] | 0;\n                                                    m = 1 << J;\n                                                    do {\n                                                        if ((P & m | 0) == 0) {\n                                                            c[16] = P | m;\n                                                            ax = X;\n                                                            ay = 104 + (V + 2 << 2) | 0\n                                                        } else {\n                                                            J = 104 + (V + 2 << 2) | 0;\n                                                            U = c[J >> 2] | 0;\n                                                            if (U >>> 0 >= (c[20] | 0) >>> 0) {\n                                                                ax = U;\n                                                                ay = J;\n                                                                break\n                                                            }\n                                                            an();\n                                                            return 0\n                                                        }\n                                                    } while (0);\n                                                    c[ay >> 2] = _;\n                                                    c[ax + 12 >> 2] = _;\n                                                    c[ab + (W + 8) >> 2] = ax;\n                                                    c[ab + (W + 12) >> 2] = X;\n                                                    break\n                                                }\n                                                V = ac;\n                                                m = aw >>> 8;\n                                                do {\n                                                    if ((m | 0) == 0) {\n                                                        az = 0\n                                                    } else {\n                                                        if (aw >>> 0 > 16777215 >>> 0) {\n                                                            az = 31;\n                                                            break\n                                                        }\n                                                        P = (m + 1048320 | 0) >>> 16 & 8;\n                                                        $ = m << P;\n                                                        J = ($ + 520192 | 0) >>> 16 & 4;\n                                                        U = $ << J;\n                                                        $ = (U + 245760 | 0) >>> 16 & 2;\n                                                        Q = 14 - (J | P | $) + (U << $ >>> 15) | 0;\n                                                        az = aw >>> ((Q + 7 | 0) >>> 0) & 1 | Q << 1\n                                                    }\n                                                } while (0);\n                                                m = 368 + (az << 2) | 0;\n                                                c[ab + (W + 28) >> 2] = az;\n                                                c[ab + (W + 20) >> 2] = 0;\n                                                c[ab + (W + 16) >> 2] = 0;\n                                                X = c[17] | 0;\n                                                Q = 1 << az;\n                                                if ((X & Q | 0) == 0) {\n                                                    c[17] = X | Q;\n                                                    c[m >> 2] = V;\n                                                    c[ab + (W + 24) >> 2] = m;\n                                                    c[ab + (W + 12) >> 2] = V;\n                                                    c[ab + (W + 8) >> 2] = V;\n                                                    break\n                                                }\n                                                if ((az | 0) == 31) {\n                                                    aA = 0\n                                                } else {\n                                                    aA = 25 - (az >>> 1) | 0\n                                                }\n                                                Q = aw << aA;\n                                                X = c[m >> 2] | 0;\n                                                while (1) {\n                                                    if ((c[X + 4 >> 2] & -8 | 0) == (aw | 0)) {\n                                                        break\n                                                    }\n                                                    aB = X + 16 + (Q >>> 31 << 2) | 0;\n                                                    m = c[aB >> 2] | 0;\n                                                    if ((m | 0) == 0) {\n                                                        T = 447;\n                                                        break\n                                                    } else {\n                                                        Q = Q << 1;\n                                                        X = m\n                                                    }\n                                                }\n                                                if ((T | 0) == 447) {\n                                                    if (aB >>> 0 < (c[20] | 0) >>> 0) {\n                                                        an();\n                                                        return 0\n                                                    } else {\n                                                        c[aB >> 2] = V;\n                                                        c[ab + (W + 24) >> 2] = X;\n                                                        c[ab + (W + 12) >> 2] = V;\n                                                        c[ab + (W + 8) >> 2] = V;\n                                                        break\n                                                    }\n                                                }\n                                                Q = X + 8 | 0;\n                                                m = c[Q >> 2] | 0;\n                                                $ = c[20] | 0;\n                                                if (X >>> 0 < $ >>> 0) {\n                                                    an();\n                                                    return 0\n                                                }\n                                                if (m >>> 0 < $ >>> 0) {\n                                                    an();\n                                                    return 0\n                                                } else {\n                                                    c[m + 12 >> 2] = V;\n                                                    c[Q >> 2] = V;\n                                                    c[ab + (W + 8) >> 2] = m;\n                                                    c[ab + (W + 12) >> 2] = X;\n                                                    c[ab + (W + 24) >> 2] = 0;\n                                                    break\n                                                }\n                                            }\n                                        } while (0);\n                                        n = ab + (ap | 8) | 0;\n                                        return n | 0\n                                    }\n                                } while (0);\n                                Y = ad;\n                                W = 512;\n                                while (1) {\n                                    aC = c[W >> 2] | 0;\n                                    if (aC >>> 0 <= Y >>> 0) {\n                                        aD = c[W + 4 >> 2] | 0;\n                                        aE = aC + aD | 0;\n                                        if (aE >>> 0 > Y >>> 0) {\n                                            break\n                                        }\n                                    }\n                                    W = c[W + 8 >> 2] | 0\n                                }\n                                W = aC + (aD - 39) | 0;\n                                if ((W & 7 | 0) == 0) {\n                                    aF = 0\n                                } else {\n                                    aF = -W & 7\n                                }\n                                W = aC + (aD - 47 + aF) | 0;\n                                ac = W >>> 0 < (ad + 16 | 0) >>> 0 ? Y : W;\n                                W = ac + 8 | 0;\n                                _ = ab + 8 | 0;\n                                if ((_ & 7 | 0) == 0) {\n                                    aG = 0\n                                } else {\n                                    aG = -_ & 7\n                                }\n                                _ = aa - 40 - aG | 0;\n                                c[22] = ab + aG;\n                                c[19] = _;\n                                c[ab + (aG + 4) >> 2] = _ | 1;\n                                c[ab + (aa - 36) >> 2] = 40;\n                                c[23] = c[14];\n                                c[ac + 4 >> 2] = 27;\n                                c[W >> 2] = c[128];\n                                c[W + 4 >> 2] = c[129];\n                                c[W + 8 >> 2] = c[130];\n                                c[W + 12 >> 2] = c[131];\n                                c[128] = ab;\n                                c[129] = aa;\n                                c[131] = 0;\n                                c[130] = W;\n                                W = ac + 28 | 0;\n                                c[W >> 2] = 7;\n                                if ((ac + 32 | 0) >>> 0 < aE >>> 0) {\n                                    _ = W;\n                                    while (1) {\n                                        W = _ + 4 | 0;\n                                        c[W >> 2] = 7;\n                                        if ((_ + 8 | 0) >>> 0 < aE >>> 0) {\n                                            _ = W\n                                        } else {\n                                            break\n                                        }\n                                    }\n                                }\n                                if ((ac | 0) == (Y | 0)) {\n                                    break\n                                }\n                                _ = ac - ad | 0;\n                                W = Y + (_ + 4) | 0;\n                                c[W >> 2] = c[W >> 2] & -2;\n                                c[ad + 4 >> 2] = _ | 1;\n                                c[Y + _ >> 2] = _;\n                                W = _ >>> 3;\n                                if (_ >>> 0 < 256 >>> 0) {\n                                    K = W << 1;\n                                    Z = 104 + (K << 2) | 0;\n                                    S = c[16] | 0;\n                                    m = 1 << W;\n                                    do {\n                                        if ((S & m | 0) == 0) {\n                                            c[16] = S | m;\n                                            aH = Z;\n                                            aI = 104 + (K + 2 << 2) | 0\n                                        } else {\n                                            W = 104 + (K + 2 << 2) | 0;\n                                            Q = c[W >> 2] | 0;\n                                            if (Q >>> 0 >= (c[20] | 0) >>> 0) {\n                                                aH = Q;\n                                                aI = W;\n                                                break\n                                            }\n                                            an();\n                                            return 0\n                                        }\n                                    } while (0);\n                                    c[aI >> 2] = ad;\n                                    c[aH + 12 >> 2] = ad;\n                                    c[ad + 8 >> 2] = aH;\n                                    c[ad + 12 >> 2] = Z;\n                                    break\n                                }\n                                K = ad;\n                                m = _ >>> 8;\n                                do {\n                                    if ((m | 0) == 0) {\n                                        aJ = 0\n                                    } else {\n                                        if (_ >>> 0 > 16777215 >>> 0) {\n                                            aJ = 31;\n                                            break\n                                        }\n                                        S = (m + 1048320 | 0) >>> 16 & 8;\n                                        Y = m << S;\n                                        ac = (Y + 520192 | 0) >>> 16 & 4;\n                                        W = Y << ac;\n                                        Y = (W + 245760 | 0) >>> 16 & 2;\n                                        Q = 14 - (ac | S | Y) + (W << Y >>> 15) | 0;\n                                        aJ = _ >>> ((Q + 7 | 0) >>> 0) & 1 | Q << 1\n                                    }\n                                } while (0);\n                                m = 368 + (aJ << 2) | 0;\n                                c[ad + 28 >> 2] = aJ;\n                                c[ad + 20 >> 2] = 0;\n                                c[ad + 16 >> 2] = 0;\n                                Z = c[17] | 0;\n                                Q = 1 << aJ;\n                                if ((Z & Q | 0) == 0) {\n                                    c[17] = Z | Q;\n                                    c[m >> 2] = K;\n                                    c[ad + 24 >> 2] = m;\n                                    c[ad + 12 >> 2] = ad;\n                                    c[ad + 8 >> 2] = ad;\n                                    break\n                                }\n                                if ((aJ | 0) == 31) {\n                                    aK = 0\n                                } else {\n                                    aK = 25 - (aJ >>> 1) | 0\n                                }\n                                Q = _ << aK;\n                                Z = c[m >> 2] | 0;\n                                while (1) {\n                                    if ((c[Z + 4 >> 2] & -8 | 0) == (_ | 0)) {\n                                        break\n                                    }\n                                    aL = Z + 16 + (Q >>> 31 << 2) | 0;\n                                    m = c[aL >> 2] | 0;\n                                    if ((m | 0) == 0) {\n                                        T = 482;\n                                        break\n                                    } else {\n                                        Q = Q << 1;\n                                        Z = m\n                                    }\n                                }\n                                if ((T | 0) == 482) {\n                                    if (aL >>> 0 < (c[20] | 0) >>> 0) {\n                                        an();\n                                        return 0\n                                    } else {\n                                        c[aL >> 2] = K;\n                                        c[ad + 24 >> 2] = Z;\n                                        c[ad + 12 >> 2] = ad;\n                                        c[ad + 8 >> 2] = ad;\n                                        break\n                                    }\n                                }\n                                Q = Z + 8 | 0;\n                                _ = c[Q >> 2] | 0;\n                                m = c[20] | 0;\n                                if (Z >>> 0 < m >>> 0) {\n                                    an();\n                                    return 0\n                                }\n                                if (_ >>> 0 < m >>> 0) {\n                                    an();\n                                    return 0\n                                } else {\n                                    c[_ + 12 >> 2] = K;\n                                    c[Q >> 2] = K;\n                                    c[ad + 8 >> 2] = _;\n                                    c[ad + 12 >> 2] = Z;\n                                    c[ad + 24 >> 2] = 0;\n                                    break\n                                }\n                            }\n                        } while (0);\n                        ad = c[19] | 0;\n                        if (ad >>> 0 <= o >>> 0) {\n                            break\n                        }\n                        _ = ad - o | 0;\n                        c[19] = _;\n                        ad = c[22] | 0;\n                        Q = ad;\n                        c[22] = Q + o;\n                        c[Q + (o + 4) >> 2] = _ | 1;\n                        c[ad + 4 >> 2] = o | 3;\n                        n = ad + 8 | 0;\n                        return n | 0\n                    }\n                } while (0);\n                c[(am() | 0) >> 2] = 12;\n                n = 0;\n                return n | 0\n            }\n\n            function aQ(a) {\n                a = a | 0;\n                var b = 0,\n                    d = 0,\n                    e = 0,\n                    f = 0,\n                    g = 0,\n                    h = 0,\n                    i = 0,\n                    j = 0,\n                    k = 0,\n                    l = 0,\n                    m = 0,\n                    n = 0,\n                    o = 0,\n                    p = 0,\n                    q = 0,\n                    r = 0,\n                    s = 0,\n                    t = 0,\n                    u = 0,\n                    v = 0,\n                    w = 0,\n                    x = 0,\n                    y = 0,\n                    z = 0,\n                    A = 0,\n                    B = 0,\n                    C = 0,\n                    D = 0,\n                    E = 0,\n                    F = 0,\n                    G = 0,\n                    H = 0,\n                    I = 0,\n                    J = 0,\n                    K = 0,\n                    L = 0,\n                    M = 0,\n                    N = 0,\n                    O = 0;\n                if ((a | 0) == 0) {\n                    return\n                }\n                b = a - 8 | 0;\n                d = b;\n                e = c[20] | 0;\n                if (b >>> 0 < e >>> 0) {\n                    an()\n                }\n                f = c[a - 4 >> 2] | 0;\n                g = f & 3;\n                if ((g | 0) == 1) {\n                    an()\n                }\n                h = f & -8;\n                i = a + (h - 8) | 0;\n                j = i;\n                L741: do {\n                    if ((f & 1 | 0) == 0) {\n                        k = c[b >> 2] | 0;\n                        if ((g | 0) == 0) {\n                            return\n                        }\n                        l = -8 - k | 0;\n                        m = a + l | 0;\n                        n = m;\n                        o = k + h | 0;\n                        if (m >>> 0 < e >>> 0) {\n                            an()\n                        }\n                        if ((n | 0) == (c[21] | 0)) {\n                            p = a + (h - 4) | 0;\n                            if ((c[p >> 2] & 3 | 0) != 3) {\n                                q = n;\n                                r = o;\n                                break\n                            }\n                            c[18] = o;\n                            c[p >> 2] = c[p >> 2] & -2;\n                            c[a + (l + 4) >> 2] = o | 1;\n                            c[i >> 2] = o;\n                            return\n                        }\n                        p = k >>> 3;\n                        if (k >>> 0 < 256 >>> 0) {\n                            k = c[a + (l + 8) >> 2] | 0;\n                            s = c[a + (l + 12) >> 2] | 0;\n                            t = 104 + (p << 1 << 2) | 0;\n                            do {\n                                if ((k | 0) != (t | 0)) {\n                                    if (k >>> 0 < e >>> 0) {\n                                        an()\n                                    }\n                                    if ((c[k + 12 >> 2] | 0) == (n | 0)) {\n                                        break\n                                    }\n                                    an()\n                                }\n                            } while (0);\n                            if ((s | 0) == (k | 0)) {\n                                c[16] = c[16] & ~(1 << p);\n                                q = n;\n                                r = o;\n                                break\n                            }\n                            do {\n                                if ((s | 0) == (t | 0)) {\n                                    u = s + 8 | 0\n                                } else {\n                                    if (s >>> 0 < e >>> 0) {\n                                        an()\n                                    }\n                                    v = s + 8 | 0;\n                                    if ((c[v >> 2] | 0) == (n | 0)) {\n                                        u = v;\n                                        break\n                                    }\n                                    an()\n                                }\n                            } while (0);\n                            c[k + 12 >> 2] = s;\n                            c[u >> 2] = k;\n                            q = n;\n                            r = o;\n                            break\n                        }\n                        t = m;\n                        p = c[a + (l + 24) >> 2] | 0;\n                        v = c[a + (l + 12) >> 2] | 0;\n                        do {\n                            if ((v | 0) == (t | 0)) {\n                                w = a + (l + 20) | 0;\n                                x = c[w >> 2] | 0;\n                                if ((x | 0) == 0) {\n                                    y = a + (l + 16) | 0;\n                                    z = c[y >> 2] | 0;\n                                    if ((z | 0) == 0) {\n                                        A = 0;\n                                        break\n                                    } else {\n                                        B = z;\n                                        C = y\n                                    }\n                                } else {\n                                    B = x;\n                                    C = w\n                                }\n                                while (1) {\n                                    w = B + 20 | 0;\n                                    x = c[w >> 2] | 0;\n                                    if ((x | 0) != 0) {\n                                        B = x;\n                                        C = w;\n                                        continue\n                                    }\n                                    w = B + 16 | 0;\n                                    x = c[w >> 2] | 0;\n                                    if ((x | 0) == 0) {\n                                        break\n                                    } else {\n                                        B = x;\n                                        C = w\n                                    }\n                                }\n                                if (C >>> 0 < e >>> 0) {\n                                    an()\n                                } else {\n                                    c[C >> 2] = 0;\n                                    A = B;\n                                    break\n                                }\n                            } else {\n                                w = c[a + (l + 8) >> 2] | 0;\n                                if (w >>> 0 < e >>> 0) {\n                                    an()\n                                }\n                                x = w + 12 | 0;\n                                if ((c[x >> 2] | 0) != (t | 0)) {\n                                    an()\n                                }\n                                y = v + 8 | 0;\n                                if ((c[y >> 2] | 0) == (t | 0)) {\n                                    c[x >> 2] = v;\n                                    c[y >> 2] = w;\n                                    A = v;\n                                    break\n                                } else {\n                                    an()\n                                }\n                            }\n                        } while (0);\n                        if ((p | 0) == 0) {\n                            q = n;\n                            r = o;\n                            break\n                        }\n                        v = a + (l + 28) | 0;\n                        m = 368 + (c[v >> 2] << 2) | 0;\n                        do {\n                            if ((t | 0) == (c[m >> 2] | 0)) {\n                                c[m >> 2] = A;\n                                if ((A | 0) != 0) {\n                                    break\n                                }\n                                c[17] = c[17] & ~(1 << c[v >> 2]);\n                                q = n;\n                                r = o;\n                                break L741\n                            } else {\n                                if (p >>> 0 < (c[20] | 0) >>> 0) {\n                                    an()\n                                }\n                                k = p + 16 | 0;\n                                if ((c[k >> 2] | 0) == (t | 0)) {\n                                    c[k >> 2] = A\n                                } else {\n                                    c[p + 20 >> 2] = A\n                                }\n                                if ((A | 0) == 0) {\n                                    q = n;\n                                    r = o;\n                                    break L741\n                                }\n                            }\n                        } while (0);\n                        if (A >>> 0 < (c[20] | 0) >>> 0) {\n                            an()\n                        }\n                        c[A + 24 >> 2] = p;\n                        t = c[a + (l + 16) >> 2] | 0;\n                        do {\n                            if ((t | 0) != 0) {\n                                if (t >>> 0 < (c[20] | 0) >>> 0) {\n                                    an()\n                                } else {\n                                    c[A + 16 >> 2] = t;\n                                    c[t + 24 >> 2] = A;\n                                    break\n                                }\n                            }\n                        } while (0);\n                        t = c[a + (l + 20) >> 2] | 0;\n                        if ((t | 0) == 0) {\n                            q = n;\n                            r = o;\n                            break\n                        }\n                        if (t >>> 0 < (c[20] | 0) >>> 0) {\n                            an()\n                        } else {\n                            c[A + 20 >> 2] = t;\n                            c[t + 24 >> 2] = A;\n                            q = n;\n                            r = o;\n                            break\n                        }\n                    } else {\n                        q = d;\n                        r = h\n                    }\n                } while (0);\n                d = q;\n                if (d >>> 0 >= i >>> 0) {\n                    an()\n                }\n                A = a + (h - 4) | 0;\n                e = c[A >> 2] | 0;\n                if ((e & 1 | 0) == 0) {\n                    an()\n                }\n                do {\n                    if ((e & 2 | 0) == 0) {\n                        if ((j | 0) == (c[22] | 0)) {\n                            B = (c[19] | 0) + r | 0;\n                            c[19] = B;\n                            c[22] = q;\n                            c[q + 4 >> 2] = B | 1;\n                            if ((q | 0) != (c[21] | 0)) {\n                                return\n                            }\n                            c[21] = 0;\n                            c[18] = 0;\n                            return\n                        }\n                        if ((j | 0) == (c[21] | 0)) {\n                            B = (c[18] | 0) + r | 0;\n                            c[18] = B;\n                            c[21] = q;\n                            c[q + 4 >> 2] = B | 1;\n                            c[d + B >> 2] = B;\n                            return\n                        }\n                        B = (e & -8) + r | 0;\n                        C = e >>> 3;\n                        L843: do {\n                            if (e >>> 0 < 256 >>> 0) {\n                                u = c[a + h >> 2] | 0;\n                                g = c[a + (h | 4) >> 2] | 0;\n                                b = 104 + (C << 1 << 2) | 0;\n                                do {\n                                    if ((u | 0) != (b | 0)) {\n                                        if (u >>> 0 < (c[20] | 0) >>> 0) {\n                                            an()\n                                        }\n                                        if ((c[u + 12 >> 2] | 0) == (j | 0)) {\n                                            break\n                                        }\n                                        an()\n                                    }\n                                } while (0);\n                                if ((g | 0) == (u | 0)) {\n                                    c[16] = c[16] & ~(1 << C);\n                                    break\n                                }\n                                do {\n                                    if ((g | 0) == (b | 0)) {\n                                        D = g + 8 | 0\n                                    } else {\n                                        if (g >>> 0 < (c[20] | 0) >>> 0) {\n                                            an()\n                                        }\n                                        f = g + 8 | 0;\n                                        if ((c[f >> 2] | 0) == (j | 0)) {\n                                            D = f;\n                                            break\n                                        }\n                                        an()\n                                    }\n                                } while (0);\n                                c[u + 12 >> 2] = g;\n                                c[D >> 2] = u\n                            } else {\n                                b = i;\n                                f = c[a + (h + 16) >> 2] | 0;\n                                t = c[a + (h | 4) >> 2] | 0;\n                                do {\n                                    if ((t | 0) == (b | 0)) {\n                                        p = a + (h + 12) | 0;\n                                        v = c[p >> 2] | 0;\n                                        if ((v | 0) == 0) {\n                                            m = a + (h + 8) | 0;\n                                            k = c[m >> 2] | 0;\n                                            if ((k | 0) == 0) {\n                                                E = 0;\n                                                break\n                                            } else {\n                                                F = k;\n                                                G = m\n                                            }\n                                        } else {\n                                            F = v;\n                                            G = p\n                                        }\n                                        while (1) {\n                                            p = F + 20 | 0;\n                                            v = c[p >> 2] | 0;\n                                            if ((v | 0) != 0) {\n                                                F = v;\n                                                G = p;\n                                                continue\n                                            }\n                                            p = F + 16 | 0;\n                                            v = c[p >> 2] | 0;\n                                            if ((v | 0) == 0) {\n                                                break\n                                            } else {\n                                                F = v;\n                                                G = p\n                                            }\n                                        }\n                                        if (G >>> 0 < (c[20] | 0) >>> 0) {\n                                            an()\n                                        } else {\n                                            c[G >> 2] = 0;\n                                            E = F;\n                                            break\n                                        }\n                                    } else {\n                                        p = c[a + h >> 2] | 0;\n                                        if (p >>> 0 < (c[20] | 0) >>> 0) {\n                                            an()\n                                        }\n                                        v = p + 12 | 0;\n                                        if ((c[v >> 2] | 0) != (b | 0)) {\n                                            an()\n                                        }\n                                        m = t + 8 | 0;\n                                        if ((c[m >> 2] | 0) == (b | 0)) {\n                                            c[v >> 2] = t;\n                                            c[m >> 2] = p;\n                                            E = t;\n                                            break\n                                        } else {\n                                            an()\n                                        }\n                                    }\n                                } while (0);\n                                if ((f | 0) == 0) {\n                                    break\n                                }\n                                t = a + (h + 20) | 0;\n                                u = 368 + (c[t >> 2] << 2) | 0;\n                                do {\n                                    if ((b | 0) == (c[u >> 2] | 0)) {\n                                        c[u >> 2] = E;\n                                        if ((E | 0) != 0) {\n                                            break\n                                        }\n                                        c[17] = c[17] & ~(1 << c[t >> 2]);\n                                        break L843\n                                    } else {\n                                        if (f >>> 0 < (c[20] | 0) >>> 0) {\n                                            an()\n                                        }\n                                        g = f + 16 | 0;\n                                        if ((c[g >> 2] | 0) == (b | 0)) {\n                                            c[g >> 2] = E\n                                        } else {\n                                            c[f + 20 >> 2] = E\n                                        }\n                                        if ((E | 0) == 0) {\n                                            break L843\n                                        }\n                                    }\n                                } while (0);\n                                if (E >>> 0 < (c[20] | 0) >>> 0) {\n                                    an()\n                                }\n                                c[E + 24 >> 2] = f;\n                                b = c[a + (h + 8) >> 2] | 0;\n                                do {\n                                    if ((b | 0) != 0) {\n                                        if (b >>> 0 < (c[20] | 0) >>> 0) {\n                                            an()\n                                        } else {\n                                            c[E + 16 >> 2] = b;\n                                            c[b + 24 >> 2] = E;\n                                            break\n                                        }\n                                    }\n                                } while (0);\n                                b = c[a + (h + 12) >> 2] | 0;\n                                if ((b | 0) == 0) {\n                                    break\n                                }\n                                if (b >>> 0 < (c[20] | 0) >>> 0) {\n                                    an()\n                                } else {\n                                    c[E + 20 >> 2] = b;\n                                    c[b + 24 >> 2] = E;\n                                    break\n                                }\n                            }\n                        } while (0);\n                        c[q + 4 >> 2] = B | 1;\n                        c[d + B >> 2] = B;\n                        if ((q | 0) != (c[21] | 0)) {\n                            H = B;\n                            break\n                        }\n                        c[18] = B;\n                        return\n                    } else {\n                        c[A >> 2] = e & -2;\n                        c[q + 4 >> 2] = r | 1;\n                        c[d + r >> 2] = r;\n                        H = r\n                    }\n                } while (0);\n                r = H >>> 3;\n                if (H >>> 0 < 256 >>> 0) {\n                    d = r << 1;\n                    e = 104 + (d << 2) | 0;\n                    A = c[16] | 0;\n                    E = 1 << r;\n                    do {\n                        if ((A & E | 0) == 0) {\n                            c[16] = A | E;\n                            I = e;\n                            J = 104 + (d + 2 << 2) | 0\n                        } else {\n                            r = 104 + (d + 2 << 2) | 0;\n                            h = c[r >> 2] | 0;\n                            if (h >>> 0 >= (c[20] | 0) >>> 0) {\n                                I = h;\n                                J = r;\n                                break\n                            }\n                            an()\n                        }\n                    } while (0);\n                    c[J >> 2] = q;\n                    c[I + 12 >> 2] = q;\n                    c[q + 8 >> 2] = I;\n                    c[q + 12 >> 2] = e;\n                    return\n                }\n                e = q;\n                I = H >>> 8;\n                do {\n                    if ((I | 0) == 0) {\n                        K = 0\n                    } else {\n                        if (H >>> 0 > 16777215 >>> 0) {\n                            K = 31;\n                            break\n                        }\n                        J = (I + 1048320 | 0) >>> 16 & 8;\n                        d = I << J;\n                        E = (d + 520192 | 0) >>> 16 & 4;\n                        A = d << E;\n                        d = (A + 245760 | 0) >>> 16 & 2;\n                        r = 14 - (E | J | d) + (A << d >>> 15) | 0;\n                        K = H >>> ((r + 7 | 0) >>> 0) & 1 | r << 1\n                    }\n                } while (0);\n                I = 368 + (K << 2) | 0;\n                c[q + 28 >> 2] = K;\n                c[q + 20 >> 2] = 0;\n                c[q + 16 >> 2] = 0;\n                r = c[17] | 0;\n                d = 1 << K;\n                do {\n                    if ((r & d | 0) == 0) {\n                        c[17] = r | d;\n                        c[I >> 2] = e;\n                        c[q + 24 >> 2] = I;\n                        c[q + 12 >> 2] = q;\n                        c[q + 8 >> 2] = q\n                    } else {\n                        if ((K | 0) == 31) {\n                            L = 0\n                        } else {\n                            L = 25 - (K >>> 1) | 0\n                        }\n                        A = H << L;\n                        J = c[I >> 2] | 0;\n                        while (1) {\n                            if ((c[J + 4 >> 2] & -8 | 0) == (H | 0)) {\n                                break\n                            }\n                            M = J + 16 + (A >>> 31 << 2) | 0;\n                            E = c[M >> 2] | 0;\n                            if ((E | 0) == 0) {\n                                N = 659;\n                                break\n                            } else {\n                                A = A << 1;\n                                J = E\n                            }\n                        }\n                        if ((N | 0) == 659) {\n                            if (M >>> 0 < (c[20] | 0) >>> 0) {\n                                an()\n                            } else {\n                                c[M >> 2] = e;\n                                c[q + 24 >> 2] = J;\n                                c[q + 12 >> 2] = q;\n                                c[q + 8 >> 2] = q;\n                                break\n                            }\n                        }\n                        A = J + 8 | 0;\n                        B = c[A >> 2] | 0;\n                        E = c[20] | 0;\n                        if (J >>> 0 < E >>> 0) {\n                            an()\n                        }\n                        if (B >>> 0 < E >>> 0) {\n                            an()\n                        } else {\n                            c[B + 12 >> 2] = e;\n                            c[A >> 2] = e;\n                            c[q + 8 >> 2] = B;\n                            c[q + 12 >> 2] = J;\n                            c[q + 24 >> 2] = 0;\n                            break\n                        }\n                    }\n                } while (0);\n                q = (c[24] | 0) - 1 | 0;\n                c[24] = q;\n                if ((q | 0) == 0) {\n                    O = 520\n                } else {\n                    return\n                }\n                while (1) {\n                    q = c[O >> 2] | 0;\n                    if ((q | 0) == 0) {\n                        break\n                    } else {\n                        O = q + 8 | 0\n                    }\n                }\n                c[24] = -1;\n                return\n            }\n\n            function aR(b, d, e) {\n                b = b | 0;\n                d = d | 0;\n                e = e | 0;\n                var f = 0,\n                    g = 0,\n                    h = 0,\n                    i = 0;\n                f = b + e | 0;\n                if ((e | 0) >= 20) {\n                    d = d & 255;\n                    g = b & 3;\n                    h = d | d << 8 | d << 16 | d << 24;\n                    i = f & ~3;\n                    if (g) {\n                        g = b + 4 - g | 0;\n                        while ((b | 0) < (g | 0)) {\n                            a[b] = d;\n                            b = b + 1 | 0\n                        }\n                    }\n                    while ((b | 0) < (i | 0)) {\n                        c[b >> 2] = h;\n                        b = b + 4 | 0\n                    }\n                }\n                while ((b | 0) < (f | 0)) {\n                    a[b] = d;\n                    b = b + 1 | 0\n                }\n                return b - e | 0\n            }\n\n            function aS(b, d, e) {\n                b = b | 0;\n                d = d | 0;\n                e = e | 0;\n                var f = 0;\n                f = b | 0;\n                if ((b & 3) == (d & 3)) {\n                    while (b & 3) {\n                        if ((e | 0) == 0) return f | 0;\n                        a[b] = a[d] | 0;\n                        b = b + 1 | 0;\n                        d = d + 1 | 0;\n                        e = e - 1 | 0\n                    }\n                    while ((e | 0) >= 4) {\n                        c[b >> 2] = c[d >> 2];\n                        b = b + 4 | 0;\n                        d = d + 4 | 0;\n                        e = e - 4 | 0\n                    }\n                }\n                while ((e | 0) > 0) {\n                    a[b] = a[d] | 0;\n                    b = b + 1 | 0;\n                    d = d + 1 | 0;\n                    e = e - 1 | 0\n                }\n                return f | 0\n            }\n\n            function aT(b) {\n                b = b | 0;\n                var c = 0;\n                c = a[m + (b & 255) | 0] | 0;\n                if ((c | 0) < 8) return c | 0;\n                c = a[m + (b >> 8 & 255) | 0] | 0;\n                if ((c | 0) < 8) return c + 8 | 0;\n                c = a[m + (b >> 16 & 255) | 0] | 0;\n                if ((c | 0) < 8) return c + 16 | 0;\n                return (a[m + (b >>> 24) | 0] | 0) + 24 | 0\n            }\n\n            function aU(b) {\n                b = b | 0;\n                var c = 0;\n                c = b;\n                while (a[c] | 0) {\n                    c = c + 1 | 0\n                }\n                return c - b | 0\n            }\n\n            function aV(a, b) {\n                a = a | 0;\n                b = b | 0;\n                return ar[a & 1](b | 0) | 0\n            }\n\n            function aW(a) {\n                a = a | 0;\n                as[a & 1]()\n            }\n\n            function aX(a, b, c) {\n                a = a | 0;\n                b = b | 0;\n                c = c | 0;\n                return at[a & 1](b | 0, c | 0) | 0\n            }\n\n            function aY(a, b) {\n                a = a | 0;\n                b = b | 0;\n                au[a & 1](b | 0)\n            }\n\n            function aZ(a) {\n                a = a | 0;\n                aa(0);\n                return 0\n            }\n\n            function a_() {\n                aa(1)\n            }\n\n            function a$(a, b) {\n                a = a | 0;\n                b = b | 0;\n                aa(2);\n                return 0\n            }\n\n            function a0(a) {\n                    a = a | 0;\n                    aa(3)\n                }\n                // EMSCRIPTEN_END_FUNCS\n            var ar = [aZ, aZ];\n            var as = [a_, a_];\n            var at = [a$, a$];\n            var au = [a0, a0];\n            return {\n                _strlen: aU,\n                _free: aQ,\n                _XXH32: aO,\n                _memset: aR,\n                _llvm_cttz_i32: aT,\n                _malloc: aP,\n                _LZ4_decompress_safe: aN,\n                _memcpy: aS,\n                _LZ4_compress: aM,\n                runPostSets: aL,\n                stackAlloc: av,\n                stackSave: aw,\n                stackRestore: ax,\n                setThrew: ay,\n                setTempRet0: aB,\n                setTempRet1: aC,\n                setTempRet2: aD,\n                setTempRet3: aE,\n                setTempRet4: aF,\n                setTempRet5: aG,\n                setTempRet6: aH,\n                setTempRet7: aI,\n                setTempRet8: aJ,\n                setTempRet9: aK,\n                dynCall_ii: aV,\n                dynCall_v: aW,\n                dynCall_iii: aX,\n                dynCall_vi: aY\n            }\n            // EMSCRIPTEN_END_ASM\n        })({\n            Math: Math,\n            Int8Array: Int8Array,\n            Int16Array: Int16Array,\n            Int32Array: Int32Array,\n            Uint8Array: Uint8Array,\n            Uint16Array: Uint16Array,\n            Uint32Array: Uint32Array,\n            Float32Array: Float32Array,\n            Float64Array: Float64Array\n        }, {\n            abort: B,\n            assert: w,\n            asmPrintInt: function(a, b) {\n                r.print(\"int \" + a + \",\" + b)\n            },\n            asmPrintFloat: function(a, b) {\n                r.print(\"float \" + a + \",\" + b)\n            },\n            min: Fa,\n            invoke_ii: function(a, b) {\n                try {\n                    return r.dynCall_ii(a, b)\n                } catch (c) {\n                    \"number\" !== typeof c && \"longjmp\" !== c && e(c), $.setThrew(1, 0)\n                }\n            },\n            invoke_v: function(a) {\n                try {\n                    r.dynCall_v(a)\n                } catch (b) {\n                    \"number\" !==\n                    typeof b && \"longjmp\" !== b && e(b), $.setThrew(1, 0)\n                }\n            },\n            invoke_iii: function(a, b, c) {\n                try {\n                    return r.dynCall_iii(a, b, c)\n                } catch (d) {\n                    \"number\" !== typeof d && \"longjmp\" !== d && e(d), $.setThrew(1, 0)\n                }\n            },\n            invoke_vi: function(a, b) {\n                try {\n                    r.dynCall_vi(a, b)\n                } catch (c) {\n                    \"number\" !== typeof c && \"longjmp\" !== c && e(c), $.setThrew(1, 0)\n                }\n            },\n            _sysconf: function(a) {\n                switch (a) {\n                    case 30:\n                        return 4096;\n                    case 132:\n                    case 133:\n                    case 12:\n                    case 137:\n                    case 138:\n                    case 15:\n                    case 235:\n                    case 16:\n                    case 17:\n                    case 18:\n                    case 19:\n                    case 20:\n                    case 149:\n                    case 13:\n                    case 10:\n                    case 236:\n                    case 153:\n                    case 9:\n                    case 21:\n                    case 22:\n                    case 159:\n                    case 154:\n                    case 14:\n                    case 77:\n                    case 78:\n                    case 139:\n                    case 80:\n                    case 81:\n                    case 79:\n                    case 82:\n                    case 68:\n                    case 67:\n                    case 164:\n                    case 11:\n                    case 29:\n                    case 47:\n                    case 48:\n                    case 95:\n                    case 52:\n                    case 51:\n                    case 46:\n                        return 200809;\n                    case 27:\n                    case 246:\n                    case 127:\n                    case 128:\n                    case 23:\n                    case 24:\n                    case 160:\n                    case 161:\n                    case 181:\n                    case 182:\n                    case 242:\n                    case 183:\n                    case 184:\n                    case 243:\n                    case 244:\n                    case 245:\n                    case 165:\n                    case 178:\n                    case 179:\n                    case 49:\n                    case 50:\n                    case 168:\n                    case 169:\n                    case 175:\n                    case 170:\n                    case 171:\n                    case 172:\n                    case 97:\n                    case 76:\n                    case 32:\n                    case 173:\n                    case 35:\n                        return -1;\n                    case 176:\n                    case 177:\n                    case 7:\n                    case 155:\n                    case 8:\n                    case 157:\n                    case 125:\n                    case 126:\n                    case 92:\n                    case 93:\n                    case 129:\n                    case 130:\n                    case 131:\n                    case 94:\n                    case 91:\n                        return 1;\n                    case 74:\n                    case 60:\n                    case 69:\n                    case 70:\n                    case 4:\n                        return 1024;\n                    case 31:\n                    case 42:\n                    case 72:\n                        return 32;\n                    case 87:\n                    case 26:\n                    case 33:\n                        return 2147483647;\n                    case 34:\n                    case 1:\n                        return 47839;\n                    case 38:\n                    case 36:\n                        return 99;\n                    case 43:\n                    case 37:\n                        return 2048;\n                    case 0:\n                        return 2097152;\n                    case 3:\n                        return 65536;\n                    case 28:\n                        return 32768;\n                    case 44:\n                        return 32767;\n                    case 75:\n                        return 16384;\n                    case 39:\n                        return 1E3;\n                    case 89:\n                        return 700;\n                    case 71:\n                        return 256;\n                    case 40:\n                        return 255;\n                    case 2:\n                        return 100;\n                    case 180:\n                        return 64;\n                    case 25:\n                        return 20;\n                    case 5:\n                        return 16;\n                    case 6:\n                        return 6;\n                    case 73:\n                        return 4;\n                    case 84:\n                        return 1\n                }\n                kb(R.C);\n                return -1\n            },\n            _sbrk: lb,\n            ___setErrNo: kb,\n            ___errno_location: function() {\n                return jb\n            },\n            _abort: function() {\n                r.abort()\n            },\n            _time: function(a) {\n                var b = Math.floor(Date.now() / 1E3);\n                a && (H[a >> 2] = b);\n                return b\n            },\n            _fflush: q(),\n            STACKTOP: u,\n            STACK_MAX: Ra,\n            tempDoublePtr: eb,\n            ABORT: xa,\n            cttz_i8: hb,\n            ctlz_i8: 1,\n            NaN: NaN,\n            Infinity: Infinity\n        }, N),\n        mb = r._strlen = $._strlen,\n        tc = r._free = $._free,\n        uc = r._XXH32 = $._XXH32,\n        fb = r._memset = $._memset,\n        ib = r._llvm_cttz_i32 = $._llvm_cttz_i32,\n        L = r._malloc = $._malloc,\n        vc = r._LZ4_decompress_safe = $._LZ4_decompress_safe,\n        gb = r._memcpy = $._memcpy,\n        wc = r._LZ4_compress = $._LZ4_compress,\n        db = r.runPostSets = $.runPostSets;\n    r.dynCall_ii = $.dynCall_ii;\n    r.dynCall_v = $.dynCall_v;\n    r.dynCall_iii = $.dynCall_iii;\n    r.dynCall_vi = $.dynCall_vi;\n    qa = function(a) {\n        return $.stackAlloc(a)\n    };\n    ja = function() {\n        return $.stackSave()\n    };\n    ka = function(a) {\n        $.stackRestore(a)\n    };\n\n    function xc(a) {\n        this.name = \"ExitStatus\";\n        this.message = \"Program terminated with exit(\" + a + \")\";\n        this.status = a\n    }\n    xc.prototype = Error();\n    var yc, zc = m,\n        ab = function Ac() {\n            !r.calledRun && Bc && Cc();\n            r.calledRun || (ab = Ac)\n        };\n    r.callMain = r.fd = function(a) {\n        function b() {\n            for (var a = 0; 3 > a; a++) d.push(0)\n        }\n        w(0 == Q, \"cannot call main when async dependencies remain! (listen on __ATMAIN__)\");\n        w(0 == Ta.length, \"cannot call main when preRun functions remain to be called\");\n        a = a || [];\n        ca && zc !== m && r.P(\"preload time: \" + (Date.now() - zc) + \" ms\");\n        Xa || (Xa = l, O(P));\n        var c = a.length + 1,\n            d = [K(D(\"/bin/this.program\"), \"i8\", 0)];\n        b();\n        for (var f = 0; f < c - 1; f += 1) d.push(K(D(a[f]), \"i8\", 0)), b();\n        d.push(0);\n        d = K(d, \"i32\", 0);\n        yc = u;\n        try {\n            var g = r._main(c, d, 0);\n            r.noExitRuntime || Dc(g)\n        } catch (h) {\n            h instanceof\n            xc || (\"SimulateInfiniteLoop\" == h ? r.noExitRuntime = l : (h && (\"object\" === typeof h && h.stack) && r.P(\"exception thrown: \" + [h, h.stack]), e(h)))\n        } finally {}\n    };\n\n    function Cc(a) {\n        function b() {\n            Xa || (Xa = l, O(P));\n            O(Ua);\n            r.calledRun = l;\n            r._main && Bc && r.callMain(a);\n            if (r.postRun)\n                for (\"function\" == typeof r.postRun && (r.postRun = [r.postRun]); r.postRun.length;) Za(r.postRun.shift());\n            O(Wa)\n        }\n        a = a || r.arguments;\n        zc === m && (zc = Date.now());\n        if (0 < Q) r.P(\"run() called, but dependencies remain, so not running\");\n        else {\n            if (r.preRun)\n                for (\"function\" == typeof r.preRun && (r.preRun = [r.preRun]); r.preRun.length;) Ya(r.preRun.shift());\n            O(Ta);\n            0 < Q || (r.setStatus ? (r.setStatus(\"Running...\"), setTimeout(function() {\n                setTimeout(function() {\n                        r.setStatus(\"\")\n                    },\n                    1);\n                xa || b()\n            }, 1)) : b())\n        }\n    }\n    r.run = r.xd = Cc;\n\n    function Dc(a) {\n        xa = l;\n        u = yc;\n        O(Va);\n        e(new xc(a))\n    }\n    r.exit = r.kd = Dc;\n\n    function B(a) {\n        a && (r.print(a), r.P(a));\n        xa = l;\n        e(\"abort() at \" + Ma())\n    }\n    r.abort = r.abort = B;\n    if (r.preInit)\n        for (\"function\" == typeof r.preInit && (r.preInit = [r.preInit]); 0 < r.preInit.length;) r.preInit.pop()();\n    var Bc = l;\n    r.noInitialRun && (Bc = p);\n    Cc();\n\n    function Ec(a) {\n        return a + (a / 255 | 0) + 16\n    }\n    var Fc = [m, m, m, m, 65536, 262144, 1048576, 4194304],\n        Gc = this;\n    Gc.decompress = function(a) {\n        var g = new DataView(a.buffer, a.byteOffset, a.byteLength);\n        3131965165 !== g.getUint32(0, true) && e(Error(\"lz4: invalid magic number\"));\n        var size = g.getUint32(4, true);\n        var csize = g.getUint32(8, true);\n        var inbuf = L(csize);\n        var outbuf = L(size);\n\t\tM.set(a.subarray(12), inbuf);\n\t\tvc(inbuf, outbuf, csize, size) !== size && e(Error(\"lz4: error decompress\"));\n\t\tvar buf = new Uint8Array(M.subarray(outbuf, outbuf + size));\n        tc(inbuf);\n        tc(outbuf);\n        return buf;\n    };\n    r._LZ4_compressBound = Ec;\n    \"function\" === typeof define && define.amd ? define(\"lz4\", function() {\n        return Gc\n    }) : ba && (module.exports = Gc);\n\n}).call(lz4);\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/imgui_remote_client/imgui/main.css",
    "content": "body {\n\toverflow\t: hidden;\n\tpadding\t\t: 0;\n\tmargin\t\t: 0;\n\n\tcolor\t\t: #222;\n\tbackground-color: #333;\n}\n.form-style-6{\n    font: 100% Arial, Helvetica, sans-serif;\n    max-width: 300px;\n    margin: 10px auto;\n    padding: 16px;\n    background: #F7F7F7;\n}\n.form-style-6 h1{\n    background: #409FC1;\n    padding: 15px 0;\n    font-size: 100%;\n    font-weight: 100;\n    text-align: center;\n    color: #fff;\n    margin: -16px -16px 16px -16px;\n}\n.form-style-6 input[type=\"text\"],\n.form-style-6 input[type=\"date\"],\n.form-style-6 input[type=\"datetime\"],\n.form-style-6 input[type=\"email\"],\n.form-style-6 input[type=\"number\"],\n.form-style-6 input[type=\"search\"],\n.form-style-6 input[type=\"time\"],\n.form-style-6 input[type=\"url\"],\n.form-style-6 textarea,\n.form-style-6 select \n{\n    -webkit-transition: all 0.30s ease-in-out;\n    -moz-transition: all 0.30s ease-in-out;\n    -ms-transition: all 0.30s ease-in-out;\n    -o-transition: all 0.30s ease-in-out;\n    outline: none;\n    box-sizing: border-box;\n    -webkit-box-sizing: border-box;\n    -moz-box-sizing: border-box;\n    width: 100%;\n    background: #fff;\n    margin-bottom: 4%;\n    border: 1px solid #ccc;\n    padding: 2%;\n    color: #555;\n    text-align: center;\n    font: 100% Arial, Helvetica, sans-serif;\n}\n.form-style-6 input[type=\"text\"]:focus,\n.form-style-6 input[type=\"date\"]:focus,\n.form-style-6 input[type=\"datetime\"]:focus,\n.form-style-6 input[type=\"email\"]:focus,\n.form-style-6 input[type=\"number\"]:focus,\n.form-style-6 input[type=\"search\"]:focus,\n.form-style-6 input[type=\"time\"]:focus,\n.form-style-6 input[type=\"url\"]:focus,\n.form-style-6 textarea:focus,\n.form-style-6 select:focus\n{\n    box-shadow: 0 0 5px #409FC1;\n    padding: 3%;\n    border: 1px solid #409FC1;\n}\n.button{\n    box-sizing: border-box;\n    -webkit-box-sizing: border-box;\n    -moz-box-sizing: border-box;\n    width: 100%;\n    padding: 3%;\n    background: #409FC1;\n    border-bottom: 2px solid #3080AF;\n    border-top-style: none;\n    border-right-style: none;\n    border-left-style: none;    \n    color: #fff;\n}\n.form-style-6 input[type=\"submit\"]:hover,\n.form-style-6 input[type=\"button\"]:hover{\n    background: #2EBC99;\n}\n#imgui {\n    margin-top: 10px;\n    color: #444;\n    font: 75% Arial, Helvetica, sans-serif;\n}"
  },
  {
    "path": "3rdparty/Cinder-VNM/imgui_remote_client/imgui.html",
    "content": "<!DOCTYPE html>\n<html><head>\n<title>Remote ImGui</title>\n<meta charset=\"UTF-8\">\n<script type=\"text/javascript\" src=\"imgui/three.min.js\"></script>\n<script type=\"text/javascript\" src=\"imgui/detector.js\"></script>\n<script type=\"text/javascript\" src=\"imgui/lz4.js\"></script>\n<script type=\"text/javascript\" src=\"imgui/dat.gui.min.js\"></script>\n<script type=\"text/javascript\" src=\"imgui.js\"></script>\n<link  href=\"imgui/main.css\" rel=\"stylesheet\"/>\n\n<style>\n    #imgui_container\n    {\n        touch-action: none; /* Disable touch behaviors, like pan and zoom */\n    }\n    body \n    {\n    \tposition: fixed; \n\t    overflow-y: scroll;\n    \twidth: 100%;\n    }\n</style>\n\n</head>\n<body>\n\t<div id=\"imgui_connect\" class=\"form-style-6\">\n\t\t<h1>Remote ImGui</h1>\n\t\t<input type=\"text\" id=\"host\" placeholder=\"PS Address\"></input>\n\t\t<button class=\"button\" value=\"Connect\" onclick=\"onClickConnect()\">Connect</button>\n\t\t<br/><br/>\n\t\t<a id=\"imgui\" href=\"https://github.com/JordiRos/remoteimgui\">Remote ImGui</a>\n\t</div>\n\n\t<div id=\"imgui_container\"></div>\n\n\t<script>\n\t\tdocument.ontouchmove = function(event)\n\t\t{\n    \t\tevent.preventDefault();\n\t\t}\n\t\t// parse index.html?host=address\n\t\tdocument.getElementById('host').value = getQueryVariable(\"host\");\n\t\tif (document.getElementById('host').value != \"\") {\n\t\t\t// if found, connect!\n\t\t\tonClickConnect();\n\t\t}\n\t\telse {\n\t\t\t// if not found, use local storage for saved settings\n\t\t\tif(localStorage)\n\t\t\t\tdocument.getElementById('host').value = localStorage.getItem(\"imgui_host\");\n\t\t}\n\n\t\tfunction getQueryVariable( variable ) {\n\t  \t\tvar query = window.location.search.substring(1);\n\t  \t\tvar vars = query.split(\"&\");\n\t  \t\tfor (var i=0;i<vars.length;i++) {\n\t    \t\tvar pair = vars[i].split(\"=\");\n\t    \t\tif (pair[0] == variable) {\n\t      \t\t\treturn pair[1];\n\t    \t\t}\n\t  \t\t}\n\t  \t\treturn \"\";\n\t\t}\n\n\t\tfunction onClickConnect() {\n\t\t\tvar host = document.getElementById('host').value;\n\t\t\tvar port = 7002;\n\t\t\tif (host != \"\") {\n\t\t\t\tif(localStorage)\n\t\t\t\t\tlocalStorage.setItem(\"imgui_host\", host);\n\t\t\t\tdocument.getElementById(\"imgui_connect\").style.display = 'none';\n\t\t\t\tStartImgui( document.getElementById( 'imgui_container' ), \"ws://\" + host + \":\" + port, 1920, 1080, true );\n         \t}\n\t\t}\t\t\n    </script>\n\n</body>\n</html>\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/imgui_remote_client/imgui.js",
    "content": "//-----------------------------------------------------------------------------\n// Remote Imgui for https://github.com/ocornut/imgui\n// https://github.com/JordiRos/remoteimgui\n// Jordi Ros\n//-----------------------------------------------------------------------------\n\n// utility function to parse an arraybuffer like a stream\nfunction DataStream(data) {\n  var stream = {};\n  stream.buffer = new DataView(data);\n  stream.idx = 0;\n  stream.endian = true;\n  stream.readInt8 = function () {\n    var r = this.buffer.getInt8(this.idx, this.endian);\n    this.idx += 1;\n    return r;\n  };\n  stream.readUint8 = function () {\n    var r = this.buffer.getUint8(this.idx, this.endian);\n    this.idx += 1;\n    return r;\n  };\n  stream.readInt16 = function () {\n    var r = this.buffer.getInt16(this.idx, this.endian);\n    this.idx += 2;\n    return r;\n  };\n  stream.readUint16 = function () {\n    var r = this.buffer.getUint16(this.idx, this.endian);\n    this.idx += 2;\n    return r;\n  };\n  stream.readInt32 = function () {\n    var r = this.buffer.getInt32(this.idx, this.endian);\n    this.idx += 4;\n    return r;\n  };\n  stream.readUint32 = function () {\n    var r = this.buffer.getUint32(this.idx, this.endian);\n    this.idx += 4;\n    return r;\n  };\n  stream.readFloat32 = function () {\n    var r = this.buffer.getFloat32(this.idx, this.endian);\n    this.idx += 4;\n    return r;\n  };\n  stream.readInt16AsFloat32 = function () {\n    var r = this.readInt16();\n    return r * 1.0;\n  };\n  stream.readInt16pAsFloat32 = function () {\n    var r = this.readInt16();\n    return r * (1.0 / 32767.0);\n  };\n  stream.readUint8AsFloat32 = function () {\n    var r = this.readUint8();\n    return r * (1.0 / 255.0);\n  };\n  return stream;\n}\n\n// threejs shader to render with clipping region\nvar ImVS = [\n  \"attribute float alpha;\",\n\n  \"varying vec3 vColor;\",\n  \"varying vec2 vUv;\",\n  \"varying float vAlpha;\",\n\n  \"void main() {\",\n\n  \"vColor = color;\",\n  \"vUv = uv;\",\n  \"vAlpha = alpha;\",\n  \"gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\",\n\n  \"}\",\n].join(\"\\n\");\n\nvar ImFS = [\n  \"varying vec3 vColor;\",\n  \"varying vec2 vUv;\",\n  \"varying float vAlpha;\",\n\n  \"uniform sampler2D tTex;\",\n\n  \"void main() {\",\n  \"gl_FragColor = vec4( vColor, texture2D( tTex, vUv ).a * vAlpha );\",\n  \"}\",\n].join(\"\\n\");\n\nvar ImguiGui = function () {\n  this.window = \"Origin\";\n  this.windows = [\"Origin\"];\n  this.connectionStatus = \"disconnected\";\n};\n\nfunction StartImgui(element, serveruri, targetwidth, targetheight, compressed) {\n  if (!Detector.webgl) Detector.addGetWebGLMessage();\n\n  var gui = new dat.GUI();\n  var datgui = new ImguiGui();\n  var datgui_window = gui.add(datgui, \"window\", datgui.windows);\n  datgui_window.onChange(onFocusWindow);\n  var datgui_connectionStatus = gui.add(datgui, \"connectionStatus\");\n  var websocket, connecting, connected;\n  var server;\n\n  var width = window.innerWidth;\n  var height = window.innerHeight;\n  var targetwidth = targetwidth;\n  var targetheight = targetheight;\n  var clientactive = false;\n  var frame = 0;\n  var mouse = { x: 0, y: 0, l: 0, r: 0, w: 0, update: false };\n  var curElem;\n  var prev_data;\n\n  var camera_offset = { x: 0, y: 0 };\n  var camera_drag = false;\n  var camera_drag_pos = { x: 0, y: 0 };\n  var mouse_left = 0;\n  var mouse_right = 0;\n  var mouse_wheel = 0;\n\n  // renderer\n  var renderer = new THREE.WebGLRenderer();\n  renderer.autoClear = false;\n  renderer.setSize(width, height);\n\n  // camera\n  var camera = new THREE.OrthographicCamera(0, width, 0, height, -1, 1);\n  camera.position.z = 1;\n\n  // plane\n  var scene_background = new THREE.Scene();\n  var plane = new THREE.Mesh(\n    new THREE.PlaneBufferGeometry(targetwidth, targetheight),\n    new THREE.MeshBasicMaterial({ color: 0x72909a, side: THREE.DoubleSide })\n  );\n  plane.position.x = targetwidth / 2;\n  plane.position.y = targetheight / 2;\n  scene_background.add(plane);\n\n  // imgui dynamic geometry / meshes\n  // FIXME: Support for any number of triangles.\n  // material\n  var guniforms = {\n    tTex: { type: \"t\", value: null },\n    uClip: { type: \"v4\", value: new THREE.Vector4() },\n  };\n  var gattributes = {\n    alpha: { type: \"f\", value: null },\n  };\n  var material = new THREE.ShaderMaterial({\n    uniforms: guniforms,\n    attributes: gattributes,\n    vertexShader: ImVS,\n    fragmentShader: ImFS,\n    vertexColors: THREE.VertexColors,\n    transparent: true,\n    side: THREE.DoubleSide,\n  });\n\n  var MAX_DRAW_LISTS = 20;\n  var geometries = [];\n  var scenes = [];\n  var scene;\n  var geometry;\n  for (var i = 0; i < MAX_DRAW_LISTS; i++) {\n    // scene\n    scene = new THREE.Scene();\n    scenes.push(scene);\n    geometry = new THREE.BufferGeometry();\n    var MAX_TRIANGLES = 21844; // *3 ~= 65536\n    geometry.addAttribute(\n      \"index\",\n      new THREE.BufferAttribute(new Uint16Array(MAX_TRIANGLES * 3), 1)\n    );\n    geometry.addAttribute(\n      \"position\",\n      new THREE.BufferAttribute(new Float32Array(MAX_TRIANGLES * 3 * 3), 3)\n    );\n    geometry.addAttribute(\n      \"uv\",\n      new THREE.BufferAttribute(new Float32Array(MAX_TRIANGLES * 2 * 3), 2)\n    );\n    geometry.addAttribute(\n      \"color\",\n      new THREE.BufferAttribute(new Float32Array(MAX_TRIANGLES * 3 * 3), 3)\n    );\n    geometry.addAttribute(\n      \"alpha\",\n      new THREE.BufferAttribute(new Float32Array(MAX_TRIANGLES * 1), 1)\n    );\n    geometry.dynamic = true;\n    geometry.offsets = [{ start: 0, index: 0, count: 0 }];\n    geometries.push(geometry);\n\n    var mesh = new THREE.Mesh(geometry, material);\n    mesh.frustumCulled = false;\n    scene.add(mesh);\n  }\n  geometry = null;\n  scene = null;\n  // geometry shortcuts\n  var gindices;\n  var gpositions;\n  var guvs;\n  var gcolors;\n  var galphas;\n  var gcmdcount = 0;\n  var gvtxcount = 0;\n  var gidxcount = 0;\n  var glistcount = 0;\n  var gclips = [];\n\n  // add to element\n  element.appendChild(renderer.domElement);\n\n  // canvas events (will send to imgui)\n  var elem = renderer.domElement;\n  //FF doesn't recognize mousewheel as of FF3.x\n  var mousewheelevt = /Firefox/i.test(navigator.userAgent)\n    ? \"DOMMouseScroll\"\n    : \"mousewheel\";\n  elem.addEventListener(mousewheelevt, onMouseWheel, false);\n\n  elem.addEventListener(\"mousemove\", onMouseMove, false);\n  elem.addEventListener(\"mousedown\", onMouseDown, false);\n  elem.addEventListener(\"mouseup\", onMouseUp, false);\n\n  elem.addEventListener(\"touchmove\", onTouchMove, false);\n  elem.addEventListener(\"touchstart\", onTouchStart, false);\n  elem.addEventListener(\"touchend\", onTouchEnd, false);\n\n  window.addEventListener(\"keydown\", onKeyDown, false);\n  window.addEventListener(\"keyup\", onKeyUp, false);\n  window.addEventListener(\"keypress\", onKeyPress, false);\n\n  window.addEventListener(\"paste\", onPaste, false);\n  window.addEventListener(\"resize\", onWindowResize, false);\n  document.oncontextmenu = document.body.oncontextmenu = function () {\n    return false;\n  };\n\n  // connect websocket to server\n  websocketConnect(serveruri);\n\n  // initial render\n  onRender();\n\n  // keep connected\n  setInterval(function () {\n    if (!connecting && !connected) websocketConnect(serveruri);\n  }, 5000);\n\n  // init websockets\n  function websocketConnect(serveruri) {\n    console.log(\"Remote ImGui: Connecting to \" + serveruri + \"...\");\n    connecting = true;\n    connected = false;\n    datgui_connectionStatus.setValue(\"Connecting\");\n    websocket = new WebSocket(serveruri);\n    websocket.binaryType = \"arraybuffer\";\n    websocket.onopen = function (evt) {\n      console.log(\"Remote ImGui: Connected\");\n      clientactive = false;\n      connecting = false;\n      connected = true;\n      websocket.send(\"ImInit\");\n      gclips.length = 0;\n      onRender();\n      datgui_connectionStatus.setValue(\"Connected\");\n    };\n    websocket.onclose = function (evt) {\n      console.log(\"Remote ImGui: Disconnected\");\n      clientactive = false;\n      connecting = false;\n      connected = false;\n      gclips.length = 0;\n      onRender();\n      datgui_connectionStatus.setValue(\"Disconnected\");\n    };\n    websocket.onmessage = function (evt) {\n      if (typeof evt.data == \"string\") {\n        if (evt.data == \"ImInit\") {\n          console.log(\"ImInit OK\");\n          clientactive = true;\n        } else console.log(\"Unknown message: \" + evt.data);\n      } else {\n        var data;\n        if (compressed) {\n          // log decompress time\n          //var t = performance.now();\n          data = lz4.decompress(new Uint8Array(evt.data)).buffer;\n          //console.log(\"Decompress: \" + (performance.now() - t));\n        } else data = evt.data;\n\n        // message type\n        var type = { TEX_FONT: 255, FRAME_KEY: 254, FRAME_DIFF: 253 };\n        var stream = new DataStream(data);\n        var message_type = stream.readUint8();\n        switch (message_type) {\n          // load font texture\n          case type.TEX_FONT:\n            var w = stream.readUint32();\n            var h = stream.readUint32();\n            var src = new Uint8Array(data, 9);\n            // canvas\n            var canvas = document.createElement(\"canvas\");\n            canvas.id = \"CursorLayer\";\n            canvas.width = w;\n            canvas.height = h;\n            var ctx = canvas.getContext(\"2d\");\n            var imageData = ctx.getImageData(0, 0, w, h);\n            var buf = new ArrayBuffer(imageData.data.length);\n            var buf8 = new Uint8ClampedArray(buf);\n            var data = new Uint32Array(buf);\n            for (var i = 0; i < w * h; i++) data[i] = (src[i] << 24) | 0xffffff;\n            imageData.data.set(buf8);\n            ctx.putImageData(imageData, 0, 0);\n            // texture\n            var map = new THREE.Texture(canvas);\n            map.needsUpdate = true;\n            map.minFilter = map.magFilter = THREE.NearestFilter;\n            guniforms.tTex.value = map;\n            break;\n          // full frame data\n          case type.FRAME_KEY:\n            onMessage(stream);\n            prev_data = data;\n            break;\n          // use previous frame to compose current frame\n          case type.FRAME_DIFF:\n            var buffer = new Uint8Array(data);\n            var prev_buffer = new Uint8Array(prev_data);\n            for (var i = 1; i < buffer.length; i++) {\n              if (i < prev_buffer.length) {\n                buffer[i] = buffer[i] + prev_buffer[i];\n              }\n            }\n            onMessage(stream);\n            prev_data = data;\n            break;\n        }\n      }\n    };\n    websocket.onerror = function (evt) {\n      console.log(\"ERROR: \" + evt.data);\n      clientactive = false;\n      connecting = false;\n      connected = false;\n      gclips.length = 0;\n      onRender();\n      datgui_connectionStatus.setValue(\"ERROR: \" + evt.data);\n    };\n  }\n\n  function onWindowResize() {\n    width = window.innerWidth;\n    height = window.innerHeight;\n    renderer.setSize(window.innerWidth, window.innerHeight);\n    camera = new THREE.OrthographicCamera(0, width, 0, height, -1, 1);\n    camera.position.z = 1;\n  }\n\n  function onMouseMove(event) {\n    if (!event) event = window.event;\n\n    if (camera_drag) {\n      camera_offset.x += camera_drag_pos.x - event.clientX;\n      camera_offset.y += camera_drag_pos.y - event.clientY;\n      camera_drag_pos.x = event.clientX;\n      camera_drag_pos.y = event.clientY;\n    } else {\n      var x = event.clientX + camera.position.x;\n      var y = event.clientY + camera.position.y;\n      if (clientactive)\n        websocket.send(\n          \"ImMouseMove=\" + x + \",\" + y + \",\" + mouse_left + \",\" + mouse_right\n        );\n    }\n  }\n\n  function onMouseDown(event) {\n    if (!event) event = window.event;\n    event.preventDefault();\n    if (event.button == 0) mouse_left = 1;\n    if (event.button == 2) mouse_right = 1;\n    camera_drag = event.ctrlKey;\n    if (camera_drag) {\n      camera_drag_pos.x = event.clientX;\n      camera_drag_pos.y = event.clientY;\n    } else {\n      if (clientactive) {\n        websocket.send(\"ImMousePress=\" + mouse_left + \",\" + mouse_right);\n      }\n    }\n  }\n\n  function onMouseUp(event) {\n    if (!event) event = window.event;\n    event.preventDefault();\n    if (event.button == 0) mouse_left = 0;\n    if (event.button == 2) mouse_right = 0;\n    if (camera_drag) {\n      camera_drag = false;\n    } else {\n      if (clientactive) {\n        websocket.send(\"ImMousePress=\" + mouse_left + \",\" + mouse_right);\n      }\n    }\n  }\n\n  var getPointerEvent = function (event) {\n    return event.originalEvent.targetTouches\n      ? event.originalEvent.targetTouches[0]\n      : event;\n  };\n  var touchStarted = false, // detect if a touch event is sarted\n    currX = 0,\n    currY = 0,\n    cachedX = 0,\n    cachedY = 0,\n    touchDragging = false,\n    touchInertial = false,\n    touchPressTimeout;\n\n  function onTouchStart(event) {\n    if (!event) event = window.event;\n    event.preventDefault();\n    var pointer = event; //getPointerEvent(event);\n    if (touchInertial) {\n      clearInterval(ticker);\n      touchInertial = false;\n    }\n    // caching the current x\n    cachedX = currX = pointer.pageX;\n    // caching the current y\n    cachedY = currY = pointer.pageY;\n    // a touch event is detected\n    websocket.send(\"ImMouseMove=\" + currX + \",\" + currY + \",0,0\");\n\n    setTimeout(function () {\n      touchStarted = true;\n      //if ((cachedX === currX) && !touchStarted && (cachedY === currY))\n      //console.log(\"50ms ImMousePress=1,0\");\n      websocket.send(\"ImMousePress=1,0\");\n      // detecting if after 200ms the finger is still in the same position\n      clearTimeout(touchPressTimeout);\n      touchPressTimeout = setTimeout(function () {\n        if (cachedX === currX && cachedY === currY) {\n          //console.log(\"200ms ImMousePress=0,0\");\n          websocket.send(\"ImMousePress=0,0\");\n          touchStarted = false;\n        }\n      }, 150);\n    }, 50);\n  }\n  var amplitude,\n    initialVelocity,\n    step,\n    ticker,\n    position,\n    timeConstant = 325,\n    scaleFactor = 2,\n    updateInterval = 20;\n  function onTouchEnd(event) {\n    if (!event) event = window.event;\n    event.preventDefault();\n    // here we can consider finished the touch event\n    if (touchDragging) {\n      amplitude = initialVelocity * scaleFactor;\n      targetPosition = position + amplitude;\n      timestamp = Date.now();\n      touchInertial = true;\n      ticker = setInterval(function () {\n        var elapsed = Date.now() - timestamp;\n        var delta = amplitude * Math.exp(-elapsed / timeConstant);\n        websocket.send(\"ImMouseWheelDelta=\" + delta);\n        position = targetPosition - delta;\n        if (elapsed > 6 * timeConstant) {\n          touchInertial = false;\n          clearInterval(ticker);\n        }\n      }, updateInterval);\n    } else if (touchStarted) {\n      clearTimeout(touchPressTimeout);\n      //console.log(\"ontouchend ImMousePress=0,0\");\n      websocket.send(\"ImMousePress=0,0\");\n    }\n    touchStarted = false;\n    touchDragging = false;\n  }\n\n  function onTouchMove(event) {\n    if (!event) event = window.event;\n    event.preventDefault();\n    var pointer = event; //getPointerEvent(e);\n    currX = pointer.pageX;\n    currY = pointer.pageY;\n    if (touchStarted) {\n      // here you are swiping\n      if (clientactive) {\n        touchDragging = true;\n        var diffY = (currY - cachedY) * 5;\n        cachedY = currY;\n        initialVelocity = diffY;\n        //websocket.send(\"ImMouseMove=\" + currX + \",\" + currY + \",1,0\");\n        console.log(\"ImMouseWheelDelta=\" + diffY);\n        websocket.send(\"ImMouseWheelDelta=\" + diffY);\n      }\n    }\n  }\n\n  function onMouseWheel(event) {\n    if (!event) event = window.event;\n    event.preventDefault();\n    //if( event.which == 1 ) mouse_wheel += event.wheelDelta;\n    if (/*event.which == 1 && */clientactive) {\n      var delta = event.detail ? (event.detail * -120) / 4 : event.wheelDelta;\n      websocket.send(\"ImMouseWheelDelta=\" + delta);\n    }\n  }\n\n  var osxCommandKey = false;\n  function isSpecialKey(event) {\n    var key = event.which;\n    if (\n      (key == 91 && event.metaKey) || // Mac Command (Left)\n      (key == 93 && event.metaKey)\n    ) {\n      // Mac Command (Right)\n      osxCommandKey = true;\n      event.ctrlKey = true;\n      return true;\n    }\n    if (\n      key < 32 ||\n      (key >= 37 && key <= 40) || // Arrows\n      key == 46 || // Mac Backspace\n      (key >= 112 && key <= 123)\n    ) {\n      return true;\n    }\n    if (key == 65 || key == 67 || key == 88 || key == 86) {\n      // 'A', 'C', 'X', 'V'\n      if (osxCommandKey || event.ctrlKey) return true;\n    }\n  }\n\n  function onKeyDown(event) {\n    if (!event) event = window.event;\n\n    // do not prevent paste\n    if (event.which == 86 && (event.ctrlKey || osxCommandKey)) {\n      // CTRL+V\n      return;\n    }\n    // prevent special keys\n    if (isSpecialKey(event)) {\n      event.preventDefault();\n      if (clientactive) {\n        var isCtrl = osxCommandKey || event.ctrlKey ? 1 : 0;\n        websocket.send(\n          \"ImKeyDown=\" +\n            event.which +\n            \",\" +\n            (event.shiftKey ? 1 : 0) +\n            \",\" +\n            isCtrl\n        );\n      }\n    }\n  }\n\n  function onKeyUp(event) {\n    if (!event) event = window.event;\n    if (event.which != 0) {\n      if (osxCommandKey || isSpecialKey(event)) {\n        osxCommandKey = false;\n        if (clientactive) {\n          websocket.send(\"ImKeyUp=\" + event.which);\n        }\n      }\n    }\n  }\n\n  function onKeyPress(event) {\n    if (!event) event = window.event;\n    if (clientactive) {\n      websocket.send(\"ImKeyPress=\" + event.charCode);\n    }\n  }\n\n  function onPaste(event) {\n    if (!event) event = window.event;\n    event.preventDefault();\n    if (event.which != 0) {\n      if (clientactive) {\n        websocket.send(\"ImClipboard=\" + event.clipboardData.getData(\"Text\"));\n        setTimeout(function () {\n          websocket.send(\"ImKeyDown=86,0,1\");\n        }, 100);\n      }\n    }\n  }\n\n  function onMessage(data) {\n    if (!onRenderBackground()) return;\n    glistcount = data.readUint32();\n    for (var l = 0; l < glistcount; l++) {\n      geometry = geometries[l];\n      gcmdcount = data.readUint32();\n      gvtxcount = data.readUint32();\n      gidxcount = data.readUint32();\n      gindices = geometry.attributes.index.array;\n      gpositions = geometry.attributes.position.array;\n      guvs = geometry.attributes.uv.array;\n      gcolors = geometry.attributes.color.array;\n      galphas = geometry.attributes.alpha.array;\n      gclips.length = 0;\n      curElem = 0;\n      // command lists\n      for (var i = 0; i < gcmdcount; i++) {\n        var num = data.readUint32();\n        var x = data.readFloat32();\n        var y = data.readFloat32();\n        var w = data.readFloat32();\n        var h = data.readFloat32();\n        gclips.push({\n          start: curElem,\n          index: 0,\n          count: num,\n          clip: new THREE.Vector4(x, y, w, h),\n        });\n        curElem += num;\n      }\n      // all vertices\n      for (var i = 0; i < gvtxcount; i++) {\n        addVtx(data, i);\n      }\n      for (var i = 0; i < gidxcount; i++) {\n        addIdx(data, i);\n      }\n      geometry.attributes.position.needsUpdate = true;\n      geometry.attributes.uv.needsUpdate = true;\n      geometry.attributes.color.needsUpdate = true;\n      geometry.attributes.alpha.needsUpdate = true;\n      geometry.attributes.index.needsUpdate = true;\n      // update render and dat.gui\n      onRenderTriangles(scenes[l]);\n    }\n    onUpdateGui();\n  }\n\n  function addVtx(data, idx) {\n    var vidx = idx * 3;\n    var uidx = idx * 2;\n    var cidx = idx * 3;\n    var aidx = idx;\n    gpositions[vidx + 0] = data.readInt16AsFloat32();\n    gpositions[vidx + 1] = data.readInt16AsFloat32();\n    gpositions[vidx + 2] = 0;\n    guvs[uidx + 0] = data.readInt16pAsFloat32();\n    guvs[uidx + 1] = 1 - data.readInt16pAsFloat32();\n    gcolors[cidx + 0] = data.readUint8AsFloat32();\n    gcolors[cidx + 1] = data.readUint8AsFloat32();\n    gcolors[cidx + 2] = data.readUint8AsFloat32();\n    galphas[aidx] = data.readUint8AsFloat32();\n  }\n\n  function addIdx(data, idx) {\n    gindices[idx] = data.readUint16();\n  }\n\n  function onRender() {\n    // Use this to only render selected window\n    //var idx = ( datgui.window == 'All' ) ? -1 : parseInt( datgui.window ) - 1;\n    if (onRenderBackground()) {\n      //onRenderTriangles();\n    }\n  }\n\n  function onRenderBackground() {\n    if (clientactive) {\n      renderer.enableScissorTest(false);\n      renderer.setClearColor(0x72909a);\n      renderer.clear(true, true, false);\n      // render background (visual reference of device canvas)\n      renderer.render(scene_background, camera);\n      return true;\n    } else {\n      // darken background\n      renderer.enableScissorTest(false);\n      renderer.setClearColor(0x444444);\n      renderer.clear(true, true, false);\n      return false;\n    }\n  }\n\n  function onRenderTriangles(scene) {\n    camera.position.x = camera_offset.x;\n    camera.position.y = camera_offset.y;\n    renderer.enableScissorTest(true);\n    // render command lists (or selected one)\n    for (var i = 0; i < gclips.length; i++) {\n      geometry.offsets[0].start = gclips[i].start;\n      geometry.offsets[0].index = gclips[i].index;\n      geometry.offsets[0].count = gclips[i].count;\n\n      renderer.setScissor(\n        gclips[i].clip.x,\n        height - gclips[i].clip.w,\n        gclips[i].clip.z - gclips[i].clip.x,\n        gclips[i].clip.w - gclips[i].clip.y\n      );\n\n      renderer.render(scene, camera);\n    }\n  }\n\n  function onUpdateGui() {\n    if (datgui.windows.length != gcmdcount + 1) {\n      datgui.windows = [\"Origin\"];\n      for (var i = 0; i < gcmdcount; i++) datgui.windows[i + 1] = i + 1;\n      gui.remove(datgui_window);\n      datgui_window = gui.add(datgui, \"window\", datgui.windows);\n      datgui_window.onChange(onFocusWindow);\n    }\n  }\n\n  function onFocusWindow(value) {\n    if (value == \"Origin\") {\n      camera_offset.x = 0;\n      camera_offset.y = 0;\n    } else {\n      var idx = parseInt(value) - 1;\n      camera_offset.x = Math.round(\n        -50 + ((gclips[idx].clip.x + 1) * width) / 2.0\n      );\n      camera_offset.y = Math.round(\n        -50 + ((gclips[idx].clip.y + 1) * height) / 2.0\n      );\n    }\n  }\n}\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/include/AnsiToUtf.h",
    "content": "#pragma once\r\n\r\n#if defined( CINDER_MSW )\n#include <string>\r\n#include <windows.h>\r\n\r\n// Utf16(unicode) is preferred by Windows system\r\n// Utf8 is preferred by Cinder\r\n// Ansi is preferred by native application (notepad/VisualStudio)\r\nstatic std::wstring AnsiToUtf16( const std::string& str )\r\n{\r\n    int textlen ;\r\n    textlen = MultiByteToWideChar( CP_ACP, 0, str.c_str(),-1, NULL,0 ); \r\n    wchar_t* buf = (wchar_t *)malloc((textlen+1)*sizeof(wchar_t)); \r\n    memset(buf,0,(textlen+1)*sizeof(wchar_t)); \r\n    MultiByteToWideChar(CP_ACP, 0,str.c_str(),-1,(LPWSTR)buf,textlen ); \r\n\r\n    std::wstring result(buf);\r\n    free(buf);\r\n    return result;\r\n}\r\n\r\nstatic std::string Utf16ToAnsi( const std::wstring& str )\r\n{\r\n    int textlen;\r\n    textlen = WideCharToMultiByte( CP_ACP, 0, str.c_str(), -1, NULL, 0, NULL, NULL );\r\n    char* buf =(char *)malloc((textlen+1)*sizeof(char));\r\n    memset( buf, 0, sizeof(char) * ( textlen + 1 ) );\r\n    WideCharToMultiByte( CP_ACP, 0, str.c_str(), -1, buf, textlen, NULL, NULL );\r\n\r\n    std::string result(buf);\r\n    free(buf);\r\n    return result;\r\n}\r\n\r\nstatic std::wstring Utf8ToUtf16( const std::string& str )\r\n{\r\n    int textlen ;\r\n    textlen = MultiByteToWideChar( CP_UTF8, 0, str.c_str(),-1, NULL,0 ); \r\n    wchar_t* buf = (wchar_t *)malloc((textlen+1)*sizeof(wchar_t)); \r\n    memset(buf,0,(textlen+1)*sizeof(wchar_t)); \r\n    MultiByteToWideChar(CP_UTF8, 0,str.c_str(),-1,(LPWSTR)buf,textlen ); \r\n\r\n    std::wstring result(buf);\r\n    free(buf);\r\n    return result;\r\n}\r\n\r\nstatic std::string Utf16ToUtf8( const std::wstring& str )\r\n{\r\n    int textlen;\r\n    textlen = WideCharToMultiByte( CP_UTF8, 0, str.c_str(), -1, NULL, 0, NULL, NULL );\r\n    char* buf =(char *)malloc((textlen+1)*sizeof(char));\r\n    memset(buf, 0, sizeof(char) * ( textlen + 1 ) );\r\n    WideCharToMultiByte( CP_UTF8, 0, str.c_str(), -1, buf, textlen, NULL, NULL );\r\n\r\n    std::string result(buf);\r\n    free(buf);\r\n    return result;\r\n}\r\n\r\nstatic std::string AnsiToUtf8( const std::string& str )\r\n{\r\n    return Utf16ToUtf8(AnsiToUtf16(str));\r\n}\r\n\r\nstatic std::string Utf8ToAnsi( const std::string& str )\r\n{\r\n    return Utf16ToAnsi(Utf8ToUtf16(str));\r\n}\r\n#endif\r\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/include/AssetManager.h",
    "content": "#pragma once\r\n\r\n#include \"cinder/gl/Texture.h\"\r\n#include \"cinder/gl/VboMesh.h\"\r\n#include \"cinder/gl/GlslProg.h\"\r\n#include \"cinder/audio/Voice.h\"\r\n\r\n#include <string>\r\n#include <vector>\r\n\r\n#define TEXTURE_3D_ENABLED 0\r\n\r\nnamespace am // am -> asset manager\r\n{\r\n    void addAssetDirectory(const ci::fs::path& dirPath);\r\n\r\n    ci::BufferRef& buffer(const std::string& relativeName);\r\n\r\n    ci::SurfaceRef& surface(const std::string& relativeName, bool forceAlpha = false);\r\n    ci::Surface16uRef& surface16u(const std::string& relativeName, bool forceAlpha = false);\r\n    ci::Surface32fRef& surface32f(const std::string& relativeName, bool forceAlpha = false);\r\n    ci::ChannelRef& channel(const std::string& relativeName);\r\n    ci::Channel16uRef& channel16u(const std::string& relativeName);\r\n\r\n    // Supports jpg, png, bmp, tga, dds, ktx, hdr etc.\r\n    // Special support: \"checkerboard\"\r\n#if ! defined( CINDER_GL_ES )\r\n    //ci::gl::Texture1dRef& texture1d(const std::string& relativeName, const ci::gl::Texture1d::Format& format = ci::gl::Texture1d::Format(), bool isAsync = false);\r\n#endif\r\n    ci::gl::Texture2dRef& texture2d(const std::string& relativeName,\r\n                                    const ci::gl::Texture2d::Format& format = ci::gl::Texture2d::Format()\r\n                                        .mipmap().minFilter(GL_LINEAR_MIPMAP_LINEAR).magFilter(GL_LINEAR).wrap(GL_REPEAT),\r\n                                    bool isAsync = false);\r\n#if TEXTURE_3D_ENABLED\r\n    ci::gl::Texture3dRef& texture3d(const std::string& relativeName, const ci::gl::Texture3d::Format& format = ci::gl::Texture3d::Format()\r\n                                    .mipmap().minFilter(GL_LINEAR_MIPMAP_LINEAR).magFilter(GL_LINEAR),\r\n                                    bool isAsync = false);\r\n#endif\r\n    ci::gl::TextureCubeMapRef& textureCubeMap(const std::string& relativeName,\r\n                                              const ci::gl::TextureCubeMap::Format& format = ci::gl::TextureCubeMap::Format()\r\n                                              .mipmap().minFilter(GL_LINEAR_MIPMAP_LINEAR).magFilter(GL_LINEAR),\r\n                                              bool isAsync = false);\r\n\r\n    // Supports obj, msh.\r\n    // Special support: \"Rect\", \"Icosahedron\", \"Icosphere\", \"Teapot\", \"Circle\", \"Ring\", \"Sphere\", \"Capsule\" etc\r\n    ci::TriMeshRef& triMesh(const std::string& objFileName, const std::string& mtlFileName = \"\");\r\n\r\n    ci::gl::VboMeshRef& vboMesh(const std::string& objFileName, const std::string& mtlFileName = \"\");\r\n\r\n    // Special support built-in shaders: \"passthrough\", \"lambert texture\", \"color\", \"texture\", \"lambert\", \"color texture\" etc\r\n    ci::gl::GlslProgRef& glslProg(const std::string& vsFileName, const std::string& fsFileName = \"\", ci::gl::GlslProg::Format format = {});\r\n\r\n    std::string& str(const std::string& relativeName);\r\n\r\n    std::vector<std::string>& longPaths(const std::string& relativeFolderName);\r\n    std::vector<std::string>& shortPaths(const std::string& relativeFolderName);\r\n\r\n    ci::audio::VoiceRef& voice(const std::string& relativeName);\r\n}\r\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/include/CaptureHelper.h",
    "content": "#pragma once\n\n#include \"cinder/app/App.h\"\n#include \"cinder/Capture.h\"\n#include \"cinder/Log.h\"\n#include \"cinder/ip/Flip.h\"\n#include \"cinder/gl/Texture.h\"\n\nusing namespace ci;\nusing namespace ci::app;\n\nstruct CaptureHelper\n{\n    Surface         surface;\n    gl::TextureRef  texture;\n    ivec2           size;\n    bool            flip;\n    std::string     deviceName;\n    bool            isBackCamera;\n    \n    bool isReady()\n    {\n        return texture != nullptr;\n    }\n    \n    bool checkNewFrame()\n    {\n        bool ret = hasNewFrame;\n        if (hasNewFrame) hasNewFrame = false;\n        return ret;\n    }\n    \n    void setup(int32_t width = 640, int32_t height = 480, const Capture::DeviceRef device = Capture::DeviceRef())\n    {\n        try\n        {\n            hasNewFrame = false;\n\n            capture = Capture::create(width, height, device);\n            capture->start();\n            flip = false;\n            deviceName = capture->getDevice()->getName();\n            isBackCamera = (deviceName.find(\"Back\") != std::string::npos);\n            \n            auto updateFn = [this]\n            {\n                if (capture && capture->checkNewFrame())\n                {\n                    surface = *capture->getSurface();\n                    if (flip) ip::flipHorizontal(&surface);\n\n                    size = surface.getSize();\n                    \n                    if (!texture)\n                    {\n                        // Capture images come back as top-down, and it's more efficient to keep them that way\n                        gl::Texture::Format format;\n//                        format.loadTopDown();\n                        texture = gl::Texture::create( surface, format);\n                    }\n                    else\n                    {\n                        texture->update( surface );\n                    }\n                    \n                    hasNewFrame = true;\n                }\n            };\n            App::get()->getSignalUpdate().connect(updateFn);\n            \n        }\n        catch ( ci::Exception &exc )\n        {\n            CI_LOG_EXCEPTION( \"Failed to init capture \", exc );\n        }\n    }\n    \n    static void printDevices()\n    {\n        for ( const auto &device : Capture::getDevices() )\n        {\n            console() << \"Device: \" << device->getName() << \" \"\n#if defined( CINDER_COCOA_TOUCH )\n            << ( device->isFrontFacing() ? \"Front\" : \"Rear\" ) << \"-facing\"\n#endif\n            << std::endl;\n        }\n    }\n    \nprivate:\n    \n    CaptureRef  capture;\n    bool        hasNewFrame;\n\n};\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/include/CinderGuizmo.h",
    "content": "#pragma once\r\n\r\n#include <glm/mat4x4.hpp>\r\n\r\nnamespace ImGui\r\n{\r\n    void EnableGizmo(bool enable);\r\n    bool EditGizmo(const glm::mat4& cameraView, const glm::mat4& cameraProjection, glm::mat4* matrix);\r\n    void DecomposeMatrixToComponents(const glm::mat4& transform, glm::vec3& matrixTranslation, glm::vec3& matrixRotation, glm::vec3& matrixScale);\r\n    bool ViewManipulate(glm::mat4& cameraView, float length, const glm::ivec2& position, const glm::ivec2& size = { 128, 128 }, uint32_t backgroundColor = 0x10101010);\r\n}"
  },
  {
    "path": "3rdparty/Cinder-VNM/include/CinderImGui.h",
    "content": "/*\n Cinder-ImGui\n This code is intended for use with Cinder\n and Omar Cornut ImGui C++ libraries.\n \n http://libcinder.org\n https://github.com/ocornut\n \n Copyright (c) 2013-2015, Simon Geilfus - All rights reserved.\n \n Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n the following conditions are met:\n \n * Redistributions of source code must retain the above copyright notice, this list of conditions and\n the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n the following disclaimer in the documentation and/or other materials provided with the distribution.\n \n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n POSSIBILITY OF SUCH DAMAGE.\n */\n#pragma once\n\n#include <memory>\n#include <vector>\n#include <map>\n\n#include \"cinder/app/App.h\"\n#include \"cinder/CinderAssert.h\"\n#include \"cinder/Color.h\"\n#include \"cinder/Noncopyable.h\"\n#include \"cinder/Vector.h\"\n#include \"cinder/Filesystem.h\"\n\n// forward declarations\nnamespace cinder {\n\ttypedef std::shared_ptr<class DataSource> DataSourceRef;\n\tnamespace app { typedef std::shared_ptr<class Window> WindowRef; }\n\tnamespace gl { typedef std::shared_ptr<class Texture2d> Texture2dRef; }\n}\n\n// Custom implicit cast operators\n#ifndef CINDER_IMGUI_NO_IMPLICIT_CASTS\n#define IM_VEC2_CLASS_EXTRA                                             \\\nImVec2(const glm::vec2& f) { x = f.x; y = f.y; }                        \\\noperator glm::vec2() const { return glm::vec2(x,y); }                   \\\nImVec2(const glm::ivec2& f) { x = f.x; y = f.y; }                       \\\noperator glm::ivec2() const { return glm::ivec2(x,y); }\n\n#define IM_VEC4_CLASS_EXTRA                                             \\\nImVec4(const glm::vec4& f) { x = f.x; y = f.y; z = f.z; w = f.w; }      \\\noperator glm::vec4() const { return glm::vec4(x,y,z,w); }               \\\nImVec4(const ci::ColorA& f) { x = f.r; y = f.g; z = f.b; w = f.a; }     \\\noperator ci::ColorA() const { return ci::ColorA(x,y,z,w); }             \\\nImVec4(const ci::Color& f) { x = f.r; y = f.g; z = f.b; w = 1.0f; }     \\\noperator ci::Color() const { return ci::Color(x,y,z); }\n#endif\n\n#include \"CinderImGuiExports.h\"\n#include \"imgui.h\"\n\n#ifndef CINDER_IMGUI_NO_NAMESPACE_ALIAS\nnamespace ui = ImGui;\n#endif\n\n#define CINDER_IMGUI_TEXTURE_UNIT 8\n\n//! cinder imgui namespace\nnamespace ImGui {\n\t\n\tstruct IMGUI_API Options {\n\t\t//! defaults to using the current window, the basic ImGui font and the dark theme\n\t\tOptions();\n\t\t\n\t\t//! sets the window that will be used to connect the signals and render ImGui\n\t\tOptions& window( const ci::app::WindowRef &window );\n\t\t//! species whether the block should call ImGui::NewFrame and ImGui::Render automatically. Default to true.\n\t\tOptions& autoRender( bool autoRender );\n\t\t\n\t\t//! sets the font to use in ImGui\n\t\tOptions& font( const ci::fs::path &fontPath, float size );\n\t\t//! sets the list of available fonts to use in ImGui\n\t\tOptions& fonts( const std::vector<std::pair<ci::fs::path,float>> &fontPaths, bool merge = true );\n\t\t//! sets the font to use in ImGui\n\t\tOptions& fontGlyphRanges( const std::string &name, const std::vector<ImWchar> &glyphRanges );\n        //! sets global font scale\n        Options& fontGlobalScale( float scale );\n\n\t\t//! Global alpha applies to everything in ImGui\n\t\tOptions& alpha( float a );\n\t\t//! Padding within a window\n\t\tOptions& windowPadding( const glm::vec2 &padding );\n\t\t//! Minimum window size\n\t\tOptions& windowMinSize( const glm::vec2 &minSize );\n\t\t//! Radius of window corners rounding. Set to 0.0f to have rectangular windows\n\t\tOptions& windowRounding( float rounding );\n\t\t//! Alignment for title bar text\n\t\tOptions& windowTitleAlign( const glm::vec2 &align );\n\t\t//! Radius of child window corners rounding. Set to 0.0f to have rectangular windows\n\t\tOptions& childRounding( float rounding );\n\t\t//! Padding within a framed rectangle (used by most widgets)\n\t\tOptions& framePadding( const glm::vec2 &padding );\n\t\t//! Radius of frame corners rounding. Set to 0.0f to have rectangular frame (used by most widgets).\n\t\tOptions& frameRounding( float rounding );\n\t\t//! Horizontal and vertical spacing between widgets/lines\n\t\tOptions& itemSpacing( const glm::vec2 &spacing );\n\t\t//! Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)\n\t\tOptions& itemInnerSpacing( const glm::vec2 &spacing );\n\t\t//! Expand bounding box for touch-based system where touch position is not accurate enough (unnecessary for mouse inputs). Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget running. So dont grow this too much!\n\t\tOptions& touchExtraPadding( const glm::vec2 &padding );\n\t\t//! Horizontal spacing when entering a tree node\n\t\tOptions& indentSpacing( float spacing );\n\t\t//! Minimum horizontal spacing between two columns\n\t\tOptions& columnsMinSpacing( float minSpacing );\n\t\t//! Width of the vertical scroll bar, Height of the horizontal scrollbar\n\t\tOptions& scrollBarSize( float size );\n\t\t//! Radius of grab corners for scrollbar\n\t\tOptions& scrollbarRounding( float rounding );\n\t\t//! Minimum width/height of a grab box for slider/scrollbar\n\t\tOptions& grabMinSize( float minSize );\n\t\t//! Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.\n\t\tOptions& grabRounding( float rounding );\n\t\t//! Alignment of button text when button is larger than text. Defaults to (0.5f,0.5f) for horizontally+vertically centered.\n\t\tOptions& buttonTextAlign( const ci::vec2 &textAlign );            \n\t\t//! Window positions are clamped to be visible within the display area by at least this amount. Only covers regular windows.\n\t\tOptions& displayWindowPadding( const glm::vec2 &padding );\n\t\t//! If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows.\n\t\tOptions& displaySafeAreaPadding( const glm::vec2 &padding );\n\t\t//! Enable anti-aliasing on lines/borders. Disable if you are really tight on CPU/GPU.\n\t\tOptions& antiAliasedLines( bool antiAliasing );\n\t\t//! Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.)\n\t\tOptions& antiAliasedFill( bool antiAliasing );\n\t\t//! Tessellation tolerance. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.\n\t\tOptions& curveTessellationTol( float tessTolerance );\n\t\t\n\t\t//! sets imgui ini file path\n\t\tOptions& iniPath( const ci::fs::path &path );\n\t\t\n\t\t//! sets imgui original theme\n\t\tOptions& defaultTheme();\n\t\t//! sets the dark theme\n\t\tOptions& darkTheme();\n\t\t//! sets theme colors\n\t\tOptions& color( ImGuiCol option, const ci::ColorA &color );\n\t\t\n\t\t//! returns whether the block should call ImGui::NewFrame and ImGui::Render automatically\n\t\tbool isAutoRenderEnabled() const { return mAutoRender; }\n\t\t//! returns the window that will be use to connect the signals and render ImGui\n\t\tci::app::WindowRef getWindow() const { return mWindow; }\n\t\t//! returns the list of available fonts to use in ImGui\n\t\tconst std::vector<std::pair<ci::fs::path,float>>& getFonts() const { return mFonts; }\n\t\t//! returns the glyph ranges if available for this font\n\t\tconst ImWchar* getFontGlyphRanges( const std::string &name ) const;\n\t\t//! returns whether the fonts need to be merged\n\t\tbool getFontMergeMode() const { return mMergeFonts; }\n\t\t//! returns the window that will be use to connect the signals and render ImGui\n\t\tconst ImGuiStyle& getStyle() const { return mStyle; }\n\t\t//! returns imgui ini file path\n\t\tconst ci::fs::path& getIniPath() const { return mIniPath; }\n\t\t\n\tprotected:\n\t\tbool\t\t\t\t\t\t\tmAutoRender;\n\t\tImGuiStyle\t\t\t\t\t\tmStyle;\n\t\tbool\t\t\t\t\t\t\tmMergeFonts;\n\t\tstd::vector<std::pair<ci::fs::path,float>>\tmFonts;\n\t\tstd::map<std::string,std::vector<ImWchar>>\tmFontsGlyphRanges;\n\t\tci::app::WindowRef\t\t\t\tmWindow;\n\t\tci::fs::path\t\t\t\t\tmIniPath;\n\t};\n\t\n\t//! initializes ImGui and the Renderer\n\tIMGUI_API void    initialize( const Options &options = Options() );\n\t//! connects window signals to imgui events\n\tIMGUI_API void    connectWindow( ci::app::WindowRef window );\n\t//! disconnects window signals from imgui\n\tIMGUI_API void    disconnectWindow( ci::app::WindowRef window );\n\t\n\t// Cinder Helpers\n\tIMGUI_API void Image( const ci::gl::Texture2dRef &texture, const ImVec2& size, const ImVec2& uv0 = ImVec2(0,1), const ImVec2& uv1 = ImVec2(1,0), const ImVec4& tint_col = ImVec4(1,1,1,1), const ImVec4& border_col = ImVec4(0,0,0,0) );\n\tIMGUI_API bool ImageButton( const ci::gl::Texture2dRef &texture, const ImVec2& size, const ImVec2& uv0 = ImVec2(0,1),  const ImVec2& uv1 = ImVec2(1,0), int frame_padding = -1, const ImVec4& bg_col = ImVec4(0,0,0,1), const ImVec4& tint_col = ImVec4(1,1,1,1) );\n\tIMGUI_API void PushFont( const std::string& name = \"\" );\n\t\n\t// Std Helpers\n\tIMGUI_API bool Combo(const char* label, int* currIndex, const std::vector<std::string>& values, ImGuiComboFlags flags = 0);\n\tIMGUI_API bool ListBox( const char* label, int* current_item, const std::vector<std::string>& items, int height_in_items = -1);\n\tIMGUI_API bool InputText( const char* label, std::string* buf, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL);\n\tIMGUI_API bool InputTextMultiline( const char* label, std::string* buf, const ImVec2& size = ImVec2(0,0), ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL);\n\t\n\t// Getters/Setters Helpers\n\ttemplate<typename T>\n\tbool InputText( const char* label, T *object, std::string( T::*get )() const, void( T::*set )( const std::string& ), ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL );\n\ttemplate<typename T>\n\tbool Checkbox(const char* label, T *object, bool( T::*get )() const, void( T::*set )( bool ) );\n\ttemplate<typename T>\n\tbool DragFloat(const char* label, T *object, float( T::*get )() const, void( T::*set )( float ), float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* display_format = \"%.3f\", float power = 1.0f);     // If v_min >= v_max we have no bound\n\ttemplate<typename T>\n\tbool DragFloat2(const char* label, T *object, ci::vec2( T::*get )() const, void( T::*set )( const ci::vec2& ), float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* display_format = \"%.3f\", float power = 1.0f);\n\ttemplate<typename T>\n\tbool DragFloat3(const char* label, T *object, ci::vec3( T::*get )() const, void( T::*set )( const ci::vec3& ), float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* display_format = \"%.3f\", float power = 1.0f);\n\ttemplate<typename T>\n\tbool DragFloat4(const char* label, T *object, ci::vec4( T::*get )() const, void( T::*set )( const ci::vec4& ), float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* display_format = \"%.3f\", float power = 1.0f);\n\ttemplate<typename T>\n\tbool DragInt(const char* label, T *object, int( T::*get )() const, void( T::*set )( int ), float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* display_format = \"%.0f\");     // If v_min >= v_max we have no bound\n\ttemplate<typename T>\n\tbool DragInt2(const char* label, T *object, ci::ivec2( T::*get )() const, void( T::*set )( const ci::ivec2& ), float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* display_format = \"%.0f\" );\n\ttemplate<typename T>\n\tbool DragInt3(const char* label, T *object, ci::ivec3( T::*get )() const, void( T::*set )( const ci::ivec3& ), float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* display_format = \"%.0f\" );\n\ttemplate<typename T>\n\tbool DragInt4(const char* label, T *object, ci::ivec4( T::*get )() const, void( T::*set )( const ci::ivec4& ), float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* display_format = \"%.0f\" );\n\ttemplate<typename T>\n\tbool ColorPicker3( const char* label, T *object, ci::Color( T::*get )() const, void( T::*set )( const ci::Color& ) );\n\ttemplate<typename T>\n\tbool ColorPicker4( const char* label, T *object, ci::ColorA( T::*get )() const, void( T::*set )( const ci::ColorA& ) );\n\n\t// Scoped objects goodness (push the state when created and pop it when destroyed)\n\n\tstruct IMGUI_API ScopedWindow : public ci::Noncopyable {\n\t\tScopedWindow( const std::string &name = \"Debug\", ImGuiWindowFlags flags = 0 );\n\t\t~ScopedWindow();\n\t};\n\tstruct IMGUI_API ScopedChild : public ci::Noncopyable {\n\t\tScopedChild( const std::string &name, glm::vec2 size = glm::vec2(0), bool border = false, ImGuiWindowFlags extraFlags = 0 );\n\t\t~ScopedChild();\n\t};\n\tstruct IMGUI_API ScopedGroup : public ci::Noncopyable {\n\t\tScopedGroup();\n\t\t~ScopedGroup();\n\t};\n\tstruct IMGUI_API ScopedFont : public ci::Noncopyable {\n\t\tScopedFont( ImFont* font );\n\t\tScopedFont( const std::string &name );\n\t\t~ScopedFont();\n\t};\n\tstruct IMGUI_API ScopedStyleColor : public ci::Noncopyable {\n\t\tScopedStyleColor( ImGuiCol idx, const ImVec4& col );\n\t\t~ScopedStyleColor();\n\t};\n\tstruct IMGUI_API ScopedStyleVar : public ci::Noncopyable {\n\t\tScopedStyleVar( ImGuiStyleVar idx, float val );\n\t\tScopedStyleVar( ImGuiStyleVar idx, const ImVec2 &val );\n\t\t~ScopedStyleVar();\n\t};\n\tstruct IMGUI_API ScopedItemWidth : public ci::Noncopyable {\n\t\tScopedItemWidth( float itemWidth );\n\t\t~ScopedItemWidth();\n\t};\n\tstruct IMGUI_API ScopedTextWrapPos : public ci::Noncopyable {\n\t\tScopedTextWrapPos( float wrapPosX = 0.0f );\n\t\t~ScopedTextWrapPos();\n\t};\n\tstruct IMGUI_API ScopedId : public ci::Noncopyable {\n\t\tScopedId( const std::string &name );\n\t\tScopedId( const void *ptrId );\n\t\tScopedId( const int intId );\n\t\t~ScopedId();\n\t};\n\tstruct IMGUI_API ScopedMainMenuBar : public ci::Noncopyable {\n\t\tScopedMainMenuBar();\n\t\t~ScopedMainMenuBar();\n\tprotected:\n\t\tbool mOpened;\n\t};\n\tstruct IMGUI_API ScopedMenuBar : public ci::Noncopyable {\n\t\tScopedMenuBar();\n\t\t~ScopedMenuBar();\n\tprotected:\n\t\tbool mOpened;\n\t};\n\n\n\t// Custom widgets\n\tIMGUI_API bool FilePicker( const char* label, ci::fs::path* path, bool open = true, const ci::fs::path &initialPath = ci::fs::path(), std::vector<std::string> extensions = std::vector<std::string>() );\n\tIMGUI_API bool IconButton( const char* icon, const ImVec2& size = ImVec2(0,0), bool frame = false );\n\tIMGUI_API bool IconToggle( const char* iconEnabled, const char* iconDisabled, bool *enabled, const ImVec2& size = ImVec2(0,0), bool frame = false );\n\n\t// Dock From LumixEngine\n\t// https://github.com/nem0/LumixEngine/blob/master/external/imgui/imgui_dock.h\n\t// https://github.com/ocornut/imgui/issues/351\n\t// #define IMGUI_DOCK\n#if defined( IMGUI_DOCK )\n\tIMGUI_API void ShutdownDock();\n\tIMGUI_API void RootDock(const ImVec2& pos, const ImVec2& size);\n\tIMGUI_API bool BeginDock(const char* label, bool* opened = nullptr, ImGuiWindowFlags extra_flags = 0);\n\tIMGUI_API void EndDock();\n\tIMGUI_API void SetDockActive();\n#endif\n\n\t// Getters/Setters Helpers Implementation\n\ttemplate<typename T>\n\tbool InputText( const char* label, T *object, std::string( T::*get )() const, void( T::*set )( const std::string& ), ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data )\n\t{\n\t\tstd::string text = (object->*get)();\n\t\tif( InputText( label, &text, flags, callback, user_data ) ){\n\t\t\t(object->*set)( text );\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\ttemplate<typename T>\n\tbool Checkbox(const char* label, T *object, bool( T::*get )() const, void( T::*set )( bool ) )\n\t{\n\t\tbool value = (object->*get)();\n\t\tif( Checkbox( label, &value ) ){\n\t\t\t(object->*set)( value );\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\ttemplate<typename T>\n\tbool DragFloat(const char* label, T *object, float( T::*get )() const, void( T::*set )( float ), float v_speed, float v_min, float v_max, const char* display_format, float power )\n\t{\n\t\tfloat value = (object->*get)();\n\t\tif( DragFloat( label, &value, v_speed, v_min, v_max, display_format, power ) ){\n\t\t\t(object->*set)( value );\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\ttemplate<typename T>\n\tbool DragFloat2(const char* label, T *object, ci::vec2( T::*get )() const, void( T::*set )( const ci::vec2& ), float v_speed, float v_min, float v_max, const char* display_format, float power )\n\t{\n\t\tci::vec2 value = (object->*get)();\n\t\tif( DragFloat2( label, &value[0], v_speed, v_min, v_max, display_format, power ) ){\n\t\t\t(object->*set)( value );\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\ttemplate<typename T>\n\tbool DragFloat3(const char* label, T *object, ci::vec3( T::*get )() const, void( T::*set )( const ci::vec3& ), float v_speed, float v_min, float v_max, const char* display_format, float power )\n\t{\n\t\tci::vec3 value = (object->*get)();\n\t\tif( DragFloat3( label, &value[0], v_speed, v_min, v_max, display_format, power ) ){\n\t\t\t(object->*set)( value );\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\ttemplate<typename T>\n\tbool DragFloat4(const char* label, T *object, ci::vec4( T::*get )() const, void( T::*set )( const ci::vec4& ), float v_speed, float v_min, float v_max, const char* display_format, float power )\n\t{\n\t\tci::vec4 value = (object->*get)();\n\t\tif( DragFloat4( label, &value[0], v_speed, v_min, v_max, display_format, power ) ){\n\t\t\t(object->*set)( value );\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\ttemplate<typename T>\n\tbool DragInt(const char* label, T *object, int( T::*get )() const, void( T::*set )( int ), float v_speed, int v_min, int v_max, const char* display_format )\n\t{\n\t\tint value = (object->*get)();\n\t\tif( DragInt( label, &value, v_speed, v_min, v_max, display_format ) ){\n\t\t\t(object->*set)( value );\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\ttemplate<typename T>\n\tbool DragInt2(const char* label, T *object, ci::ivec2( T::*get )() const, void( T::*set )( const ci::ivec2& ), float v_speed, int v_min, int v_max, const char* display_format )\n\t{\n\t\tci::ivec2 value = (object->*get)();\n\t\tif( DragInt2( label, &value[0], v_speed, v_min, v_max, display_format ) ){\n\t\t\t(object->*set)( value );\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\ttemplate<typename T>\n\tbool DragInt3(const char* label, T *object, ci::ivec3( T::*get )() const, void( T::*set )( const ci::ivec3& ), float v_speed, int v_min, int v_max, const char* display_format )\n\t{\n\t\tci::ivec3 value = (object->*get)();\n\t\tif( DragInt3( label, &value[0], v_speed, v_min, v_max, display_format ) ){\n\t\t\t(object->*set)( value );\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\ttemplate<typename T>\n\tbool DragInt4(const char* label, T *object, ci::ivec4( T::*get )() const, void( T::*set )( const ci::ivec4& ), float v_speed, int v_min, int v_max, const char* display_format )\n\t{\n\t\tci::ivec4 value = (object->*get)();\n\t\tif( DragInt4( label, &value[0], v_speed, v_min, v_max, display_format ) ){\n\t\t\t(object->*set)( value );\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\ttemplate<typename T>\n\tbool ColorPicker3( const char* label, T *object, ci::Color( T::*get )() const, void( T::*set )( const ci::Color& ) )\n\t{\n\t\tci::Color value = (object->*get)();\n\t\tif( ColorPicker3( label, &value[0] ) ){\n\t\t\t(object->*set)( value );\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\ttemplate<typename T>\n\tbool ColorPicker4( const char* label, T *object, ci::ColorA( T::*get )() const, void( T::*set )( const ci::ColorA& ) )\n\t{\n\t\tci::ColorA value = (object->*get)();\n\t\tif( ColorPicker4( label, &value[0] ) ){\n\t\t\t(object->*set)( value );\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n}"
  },
  {
    "path": "3rdparty/Cinder-VNM/include/CinderImGuiExports.h",
    "content": "/*\n Cinder-ImGui\n This code is intended for use with Cinder\n and Omar Cornut ImGui C++ libraries.\n \n http://libcinder.org\n https://github.com/ocornut\n \n Copyright (c) 2013-2015, Simon Geilfus - All rights reserved.\n \n Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n the following conditions are met:\n \n * Redistributions of source code must retain the above copyright notice, this list of conditions and\n the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n the following disclaimer in the documentation and/or other materials provided with the distribution.\n \n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n POSSIBILITY OF SUCH DAMAGE.\n */\n#pragma once\n\n// symbol export\n#if defined( IMGUI_API_EXPORT )\n\t#define IMGUI_API __declspec( dllexport )\n#elif defined( CINDER_SHARED )\n\t#define IMGUI_API __declspec( dllimport )\n#endif"
  },
  {
    "path": "3rdparty/Cinder-VNM/include/CinderRemoteImgui.h",
    "content": "#pragma once\r\n\r\n/*\r\nitem.def\r\n    ITEM_DEF(string, REMOTE_GUI_IP, \"127.0.0.1\")\r\n    ITEM_DEF(bool, ENABLE_REMOTE_GUI, false)\r\n    ITEM_DEF(bool, ENABLE_LOCAL_GUI, true)\r\n\r\nsetup():\r\n    createConfigImgui(getWindow(), false, false);\r\n    createRemoteImgui(REMOTE_GUI_IP.c_str());\r\n\r\n    getSignalUpdate().connect([&] {\r\n        updateRemoteImgui(ENABLE_REMOTE_GUI);\r\n        ImGui_ImplCinder_NewFrameGuard(getWindow());\r\n        vnm::drawMinicofigImgui(true);\r\n    });\r\n\r\n    getWindow()->getSignalDraw().connect([&] {\r\n        gl::clear();\r\n\r\n        ImGui_ImplCinder_PostDraw(ENABLE_REMOTE_GUI, ENABLE_LOCAL_GUI);\r\n    });\r\n*/\r\n\r\n#include <memory>\r\n\r\nnamespace cinder::app {\r\n    class Window;\r\n    typedef std::shared_ptr<Window>\t\tWindowRef;\r\n}\r\n\r\nvoid createRemoteImgui(const char* address, int port = 7002);\r\nvoid updateRemoteImgui(bool ENABLE_REMOTE_GUI);\r\n\r\nvoid ImGui_ImplCinder_NewFrameGuard(const cinder::app::WindowRef& window);\r\n\r\nvoid ImGui_ImplCinder_PostDraw(bool ENABLE_REMOTE_GUI, bool ENABLE_LOCAL_GUI);\r\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/include/CubemapRenderer.h",
    "content": "#pragma once\r\n\r\n#include <cinder/gl/gl.h>\r\n#include <cinder/app/App.h>\r\n\r\nstruct CubeMapRenderer\r\n{\r\n    ci::gl::FboCubeMapRef fbo;\r\n    ci::CameraPersp camera;\r\n\r\n    void setup(int width = 1024, int height = 1024)\r\n    {\r\n        fbo = ci::gl::FboCubeMap::create(width, height);\r\n        camera = ci::CameraPersp(fbo->getWidth(), fbo->getHeight(), 90.0f, 1, 1000);\r\n    }\r\n\r\n    ci::signals::Signal<void()> signalDraw;\r\n\r\n    void draw()\r\n    {\r\n        ci::gl::ScopedDebugGroup debug(\"CubeMap::draw()\");\r\n        ci::gl::ScopedMatrices matrices;\r\n        ci::gl::ScopedViewport viewport(fbo->getSize());\r\n        // we need to save the current FBO because we'll be calling bindFramebufferFace() below\r\n        ci::gl::context()->pushFramebuffer();\r\n        for (uint8_t dir = 0; dir < 6; ++dir)\r\n        {\r\n            ci::gl::setProjectionMatrix(camera.getProjectionMatrix());\r\n            ci::gl::setViewMatrix(fbo->calcViewMatrix(GL_TEXTURE_CUBE_MAP_POSITIVE_X + dir, ci::vec3(0)));\r\n            fbo->bindFramebufferFace(GL_TEXTURE_CUBE_MAP_POSITIVE_X + dir);\r\n\r\n            signalDraw.emit();\r\n        }\r\n        // restore the FBO before we bound the various faces of the CubeMapFbo\r\n        ci::gl::context()->popFramebuffer();\r\n    }\r\n\r\n    void bindTexture(int slot = 0)\r\n    {\r\n        fbo->bindTexture(slot);\r\n    }\r\n    void drawDebugView(ci::Rectf screenRect = ci::Rectf(0, 0, 600, 300), int debugType = 0)\r\n    {\r\n        ci::gl::setMatricesWindow(ci::app::getWindowSize());\r\n        ci::gl::ScopedDepth d(false);\r\n        if (debugType == 0)\r\n            ci::gl::drawEquirectangular(fbo->getTextureCubeMap(), screenRect);\r\n        else if (debugType == 0)\r\n            ci::gl::drawHorizontalCross(fbo->getTextureCubeMap(), screenRect);\r\n        else \r\n            ci::gl::drawVerticalCross(fbo->getTextureCubeMap(), screenRect);\r\n    }\r\n};"
  },
  {
    "path": "3rdparty/Cinder-VNM/include/DearLogger.h",
    "content": "#pragma once\n\n#include \"imgui/imgui.h\"\n#include \"cinder/Log.h\"\n\n// Usage:\n//  static ExampleAppLog my_log;\n//  my_log.AddLog(\"Hello %d world\\n\", 123);\n//  my_log.Draw(\"title\");\nnamespace ImGui\n{\n    struct DearLogger : ci::log::Logger\n    {\n        ImGuiTextBuffer     Buf;\n        ImGuiTextFilter     Filter;\n        ImVector<int>       LineOffsets;        // Index to lines offset. We maintain this with AddLog() calls, allowing us to have a random access on lines\n        bool                AutoScroll;\n        bool                ScrollToBottom;\n\n        DearLogger();\n\n        void    Clear();\n\n        void write(const ci::log::Metadata& meta, const std::string& text) override;\n\n\n        void    AddLog(const char* fmt, ...) IM_FMTARGS(2);\n\n        void    Draw(const char* title, bool* p_open = NULL);\n    };\n}\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/include/FontHelper.h",
    "content": "#pragma once\r\n\r\n#include \"cinder/gl/TextureFont.h\"\r\n\r\nstruct FontHelper\r\n{\r\n    static const std::vector<std::string>& getFontNames()\r\n    {\r\n        return ci::Font::getNames();\r\n    }\r\n\r\n    // gl::TextureFontRef texFont = createTextureFont();\r\n    // texFont->drawString(str, {30, 30});\r\n\r\n    // sans-serif: Helvetica, Arial, Verdana, Trebuchet MS\r\n    // serif: Georgia, Times New Roman, Courier\r\n    static ci::gl::TextureFontRef createTextureFont(const std::string& fontName = \"Helvetica\", float fontScale = 24)\r\n    {\r\n        auto font = ci::Font(fontName, fontScale);\r\n        return ci::gl::TextureFont::create(font, ci::gl::TextureFont::Format().premultiply());\r\n    }\r\n};\r\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/include/GLHelper.h",
    "content": "#pragma once\r\n\r\n#include \"cinder/gl/gl.h\"\r\n#include \"cinder/app/App.h\"\r\n#include \"cinder/ip/Flip.h\"\r\n\r\n#if defined( CINDER_GL_ES )\r\nnamespace cinder {\r\n    namespace gl {\r\n        void enableWireframe() {}\r\n        void disableWireframe() {}\r\n        void setWireframeEnabled(bool enable = true) { if (enable) enableWireframe(); else disableWireframe(); }\r\n    }\r\n}\r\n#endif\r\n\r\nci::Surface copyWindowSurfaceWithAlpha() {\r\n    auto area = ci::app::getWindowBounds();\r\n    ci::Surface s(area.getWidth(), area.getHeight(), true);\r\n    glFlush();\r\n    GLint oldPackAlignment;\r\n    glGetIntegerv(GL_PACK_ALIGNMENT, &oldPackAlignment);\r\n    glPixelStorei(GL_PACK_ALIGNMENT, 1);\r\n    glReadPixels(area.x1, ci::app::getWindowHeight() - area.y2, area.getWidth(), area.getHeight(), GL_RGBA, GL_UNSIGNED_BYTE, s.getData());\r\n    glPixelStorei(GL_PACK_ALIGNMENT, oldPackAlignment);\r\n    ci::ip::flipVertical(&s);\r\n    return s;\r\n}\r\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/include/GlslParamsBuilder.h",
    "content": "#pragma once\r\n\r\n#include \"cinder/gl/GlslProg.h\"\r\n#include \"cinder/params/Params.h\"\r\n\r\n#include <unordered_map>\r\n\r\nstruct GlslParamsBuilder\r\n{    \r\n    template <typename T>\r\n    ci::params::InterfaceGl::Options<T> addParam(ci::gl::GlslProgRef glsl, ci::params::InterfaceGlRef params,\r\n                                                 std::string guiName, std::string name, std::unordered_map<std::string, T>& container)\r\n    {\r\n        auto& value = container[name];\r\n        return params->addParam(guiName, &value).updateFn([glsl, name, &value]{\r\n            glsl->uniform(name, value);\r\n        });\r\n    }\r\n    \r\n    GlslParamsBuilder(ci::gl::GlslProgRef glsl, ci::params::InterfaceGlRef params)\r\n    {\r\n        params->addSeparator();\r\n        auto label = glsl->getLabel();\r\n        params->addText(label);\r\n        \r\n        glslProg = glsl;\r\n        //\r\n        // glsl reflection: uniform\r\n        //\r\n        auto activeUniforms = glsl->getActiveUniforms();\r\n        sort(activeUniforms.begin(), activeUniforms.end(), [](const ci::gl::GlslProg::Uniform & a, const ci::gl::GlslProg::Uniform & b) -> bool{\r\n            return a.getName() < b.getName();\r\n        });\r\n        for (auto uniform : activeUniforms)\r\n        {\r\n            if (uniform.getCount() != 1) continue; // skip array\r\n            if (uniform.getUniformSemantic() != ci::gl::UNIFORM_USER_DEFINED) continue; // skip cinder-defined semantic\r\n            auto name = uniform.getName();\r\n            auto guiName = label + \"::\" + name;\r\n            \r\n            switch (uniform.getType())\r\n            {\r\n                case GL_INT:\r\n                case GL_SAMPLER_2D:\r\n                case GL_SAMPLER_CUBE:\r\n                {\r\n                    addParam(glsl, params, guiName, name, namedInts);\r\n                    break;\r\n                }\r\n                case GL_FLOAT:\r\n                {\r\n                    addParam(glsl, params, guiName, name, namedFloats).step(0.1f);\r\n                    break;\r\n                }\r\n                case GL_FLOAT_VEC3:\r\n                {\r\n                    addParam(glsl, params, guiName, name, namedColors); // namedColors or namedVec3s?\r\n                    break;\r\n                }\r\n                case GL_BOOL:\r\n                {\r\n                    addParam(glsl, params, guiName, name, namedBools);\r\n                    break;\r\n                }\r\n                default:\r\n                {\r\n                    params->addText(guiName);\r\n                    break;\r\n                }\r\n            }\r\n        }\r\n        \r\n    }\r\n    \r\n    void applyUniforms()\r\n    {\r\n        for (auto& kv : namedInts) glslProg->uniform(kv.first, kv.second);\r\n        for (auto& kv : namedBools) glslProg->uniform(kv.first, kv.second);\r\n        for (auto& kv : namedFloats) glslProg->uniform(kv.first, kv.second);\r\n        for (auto& kv : namedVec3s) glslProg->uniform(kv.first, kv.second);\r\n        for (auto& kv : namedColors) glslProg->uniform(kv.first, kv.second);\r\n        for (auto& kv : namedColorAs) glslProg->uniform(kv.first, kv.second);\r\n    }\r\n    \r\n    ci::gl::GlslProgRef glslProg;\r\n    \r\n    std::unordered_map<std::string, int> namedInts;\r\n    std::unordered_map<std::string, bool> namedBools;\r\n    std::unordered_map<std::string, float> namedFloats;\r\n    std::unordered_map<std::string, ci::vec3> namedVec3s;\r\n    std::unordered_map<std::string, ci::Color> namedColors;\r\n    std::unordered_map<std::string, ci::ColorA> namedColorAs;\r\n};\r\n\r\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/include/GlslParamsBuilderImgui.h",
    "content": "#pragma once\r\n\r\n#include \"cinder/gl/GlslProg.h\"\r\n#include \"MiniConfigImgui.h\"\r\n\r\n#include <unordered_map>\r\n\r\nstruct GlslParamsBuilderImgui\r\n{\r\n    GlslParamsBuilderImgui() {}\r\n    \r\n    GlslParamsBuilderImgui(ci::gl::GlslProgRef glsl)\r\n    {\r\n        glslProg = glsl;\r\n        if (!glslProg) return;\r\n        //\r\n        // glsl reflection: uniform\r\n        //\r\n        activeUniforms = glsl->getActiveUniforms();\r\n        sort(activeUniforms.begin(), activeUniforms.end(), [](const ci::gl::GlslProg::Uniform & a, const ci::gl::GlslProg::Uniform & b) -> bool{\r\n            return a.getName() < b.getName();\r\n        });\r\n        \r\n        connection = App::get()->getSignalUpdate().connect(std::bind(&GlslParamsBuilderImgui::drawImgui, this));\r\n    }\r\n    \r\n    ~GlslParamsBuilderImgui()\r\n    {\r\n        connection.disconnect();\r\n    }\r\n    \r\n    void applyUniforms()\r\n    {\r\n        if (!glslProg) return;\r\n\r\n        for (auto& kv : namedInts) glslProg->uniform(kv.first, kv.second);\r\n        for (auto& kv : namedBools) glslProg->uniform(kv.first, kv.second);\r\n        for (auto& kv : namedFloats) glslProg->uniform(kv.first, kv.second);\r\n        for (auto& kv : namedVec2s) glslProg->uniform(kv.first, kv.second);\r\n        for (auto& kv : namedVec3s) glslProg->uniform(kv.first, kv.second);\r\n        for (auto& kv : namedVec4s) glslProg->uniform(kv.first, kv.second);\r\n    }\r\n    \r\n    ci::gl::GlslProgRef glslProg;\r\n    std::vector<gl::GlslProg::Uniform> activeUniforms;\r\n    \r\n    std::unordered_map<std::string, int> namedInts;\r\n    std::unordered_map<std::string, bool> namedBools;\r\n    std::unordered_map<std::string, float> namedFloats;\r\n    std::unordered_map<std::string, ci::vec2> namedVec2s;\r\n    std::unordered_map<std::string, ci::vec3> namedVec3s;\r\n    std::unordered_map<std::string, ci::vec4> namedVec4s;\r\n    \r\nprivate:\r\n    \r\n    ci::signals::Connection connection;\r\n    \r\n    template <typename T>\r\n    void addParam(ci::gl::GlslProgRef glsl,\r\n                  std::string guiName, std::string name, std::unordered_map<std::string, T>& container)\r\n    {\r\n        auto& value = container[name];\r\n        if (vnm::addImguiParam(guiName.c_str(), value))\r\n        {\r\n            glsl->uniform(name, value);\r\n        };\r\n    }\r\n    \r\n    void drawImgui()\r\n    {\r\n        ui::ScopedWindow window(\"Config\");\r\n        \r\n        auto label = glslProg->getLabel();\r\n        if (!ui::CollapsingHeader(label.c_str(), ImGuiTreeNodeFlags_DefaultOpen))\r\n            return;\r\n        \r\n        for (auto uniform : activeUniforms)\r\n        {\r\n            if (uniform.getCount() != 1) continue; // skip array\r\n            if (uniform.getUniformSemantic() != ci::gl::UNIFORM_USER_DEFINED) continue; // skip cinder-defined semantic\r\n            auto name = uniform.getName();\r\n            auto guiName = name + \" @ \" + label;\r\n            \r\n            switch (uniform.getType())\r\n            {\r\n                case GL_INT:\r\n                case GL_SAMPLER_2D:\r\n                case GL_SAMPLER_CUBE:\r\n                {\r\n                    addParam(glslProg, guiName, name, namedInts);\r\n                    break;\r\n                }\r\n                case GL_FLOAT:\r\n                {\r\n                    addParam(glslProg, guiName, name, namedFloats);\r\n                    break;\r\n                }\r\n                case GL_FLOAT_VEC2:\r\n                {\r\n                    addParam(glslProg, guiName, name, namedVec2s);\r\n                    break;\r\n                }\r\n                case GL_FLOAT_VEC3:\r\n                {\r\n                    addParam(glslProg, guiName, name, namedVec3s);\r\n                    break;\r\n                }\r\n                case GL_FLOAT_VEC4:\r\n                {\r\n                    addParam(glslProg, guiName, name, namedVec4s);\r\n                    break;\r\n                }\r\n                case GL_BOOL:\r\n                {\r\n                    addParam(glslProg, guiName, name, namedBools);\r\n                    break;\r\n                }\r\n                default:\r\n                {\r\n                    ui::Text(\"%s\", guiName.c_str());\r\n                    break;\r\n                }\r\n            }\r\n        }\r\n        \r\n    };\r\n    \r\n};\r\n\r\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/include/LimitSingleInstance.h",
    "content": "#pragma once\r\n\r\n#include <windows.h> \r\n\r\n//This code is from Q243953 in case you lose the article and wonder\r\n//where this code came from.\r\n//http://support.microsoft.com/kb/243953/en-us\r\nclass LimitSingleInstance\r\n{\r\nprotected:\r\n    DWORD  m_dwLastError;\r\n    HANDLE m_hMutex;\r\n\r\npublic:\r\n    LimitSingleInstance(char *strMutexName)\r\n    {\r\n        //Make sure that you use a name that is unique for this application otherwise\r\n        //two apps may think they are the same if they are using same name for\r\n        //3rd parm to CreateMutex\r\n        m_hMutex = CreateMutexA(NULL, FALSE, strMutexName); //do early\r\n        m_dwLastError = GetLastError(); //save for use later...\r\n    }\r\n\r\n    ~LimitSingleInstance() \r\n    {\r\n        if (m_hMutex)  //Do not forget to close handles.\r\n        {\r\n            CloseHandle(m_hMutex); //Do as late as possible.\r\n            m_hMutex = NULL; //Good habit to be in.\r\n        }\r\n    }\r\n\r\n    BOOL IsAnotherInstanceRunning() \r\n    {\r\n        return (ERROR_ALREADY_EXISTS == m_dwLastError);\r\n    }\r\n};\r\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/include/MiniConfig.h",
    "content": "#pragma once\r\n\r\n#include <string>\r\n#include \"cinder/Vector.h\"\r\n#include \"cinder/Quaternion.h\"\r\n#include \"cinder/Color.h\"\r\n\r\nusing std::string;\r\nusing ci::vec3;\r\nusing ci::quat;\r\nusing ci::Color;\r\nusing ci::ColorA;\r\n\r\n#define ITEM_DEF_FILE \"item.def\"\r\n#define CONFIG_XML \"MiniConfig.xml\"\r\n\r\n#define GROUP_DEF(grp)\r\n#define ITEM_DEF(type, var, default) extern type var;\r\n#define ITEM_DEF_MINMAX(type, var, default, Min, Max) ITEM_DEF(type, var, default);\r\n#include ITEM_DEF_FILE\r\n#undef ITEM_DEF_MINMAX\r\n#undef ITEM_DEF\r\n#undef GROUP_DEF\r\n\r\n// item.def is the place to define your global variables\r\n// in the format of\r\n//\r\n/*\r\nITEM_DEF(int, APP_WIDTH, 882)\r\nITEM_DEF(int, APP_HEIGHT, 725)\r\nITEM_DEF(string, NAME, \"vinjn\")\r\nITEM_DEF(float, velocity, 3.0f)\r\n\r\nITEM_DEF_MINMAX(float, delay, 3.0f, 0.0f, 10.0f)\r\n\r\n*/\r\n\r\nvoid readConfig();\r\nvoid writeConfig();\r\nvoid revertToDefaultValues();\r\nvoid takeScreenShot(); // wait! why is it here?\r\n\r\nnamespace cinder { namespace params {\r\nclass InterfaceGl;\r\n} }\r\n\r\n/*\r\n#include \"cinder/params/Params.h\"\r\n\r\nauto params = createConfigUI({ 200, 300 });\r\nvector<string> stateNames = { \"Earth\", \"City\" };\r\nADD_ENUM_TO_INT(params.get(), APP_STATE, stateNames);\r\n*/\r\n\r\n#define ADD_ENUM_TO_INT(params_ptr, INT_VALUE, vectorOfEnumNames)    \\\r\n    params_ptr->removeParam(#INT_VALUE);                             \\\r\n    params_ptr->addParam(#INT_VALUE, vectorOfEnumNames, &INT_VALUE);\r\n\r\nstd::shared_ptr<ci::params::InterfaceGl> createConfigUI(const ci::ivec2& size);\r\n\r\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/include/MiniConfigImgui.h",
    "content": "#pragma once\r\n\r\n#include \"MiniConfig.h\"\r\n#include \"CinderImGui.h\"\r\n#include <cinder/Utilities.h>\r\n#include <cinder/app/App.h>\r\n\r\nusing namespace ci;\r\nusing namespace ci::app;\r\nusing namespace std;\r\n\r\nnamespace vnm\r\n{\r\n    void drawFrameTime()\r\n    {\r\n        ImGuiIO& io = ImGui::GetIO();\r\n        static float values[300] = {};\r\n        static int values_offset = 0;\r\n        values[values_offset] = io.DeltaTime * 1000;\r\n        values_offset = (values_offset + 1) % IM_ARRAYSIZE(values);\r\n        ImGui::PlotLines(\"frame time (ms)\", values, IM_ARRAYSIZE(values), values_offset, NULL, 0.0f, 30, ImVec2(0, 80));\r\n    }\r\n\r\n    bool addImguiParam(const char* label, int& v)\r\n    {\r\n        ImGuiInputTextFlags flags = 0;\r\n        if (label[0] == '_') flags = ImGuiInputTextFlags_ReadOnly;\r\n        return ImGui::InputInt(label, &v, 1, 100, flags);\r\n    }\r\n\r\n    bool addImguiParam(const char* label, float& v)\r\n    {\r\n        ImGuiInputTextFlags flags = 0;\r\n        if (label[0] == '_') flags = ImGuiInputTextFlags_ReadOnly;\r\n        return ImGui::InputFloat(label, &v, 0, 0, \"%.3f\", flags);\r\n    }\r\n\r\n    bool addImguiParam(const char* label, double& v)\r\n    {\r\n        ImGuiInputTextFlags flags = 0;\r\n        if (label[0] == '_') flags = ImGuiInputTextFlags_ReadOnly;\r\n        return ImGui::InputDouble(label, &v, 0, 0, \"%.6f\", flags);\r\n    }\r\n\r\n    bool addImguiParam(const char* label, float& v, float min, float max)\r\n    {\r\n        v = std::max(std::min(v, max), min);\r\n        return ImGui::DragFloat(label, &v, 1.0f, min, max);\r\n    }\r\n\r\n    bool addImguiParam(const char* label, double& v, double min, double max)\r\n    {\r\n        v = std::max(std::min(v, max), min);\r\n        return ImGui::DragScalar(label, ImGuiDataType_Double, &v, 1.0f, &min, &max, \"%.8f\");\r\n    }\r\n\r\n    bool addImguiParam(const char* label, int& v, int min, int max)\r\n    {\r\n        v = std::max(std::min(v, max), min);\r\n        return ImGui::DragInt(label, &v, 1.0f, min, max);\r\n    }\r\n\r\n    bool addImguiParamSlider(const char* label, float& v, float min, float max)\r\n    {\r\n        return ImGui::SliderFloat(label, &v, min, max);\r\n    }\r\n\r\n    bool addImguiParamSlider(const char* label, double& v, double min, double max)\r\n    {\r\n        return ImGui::SliderScalar(label, ImGuiDataType_Double, &v, &min, &max, \"%.8f\");\r\n    }\r\n\r\n    bool addImguiParamSlider(const char* label, int& v, int min, int max)\r\n    {\r\n        return ImGui::SliderInt(label, &v, min, max);\r\n    }\r\n\r\n    bool addImguiParam(const char* label, bool& v)\r\n    {\r\n        return ImGui::Checkbox(label, &v);\r\n    }\r\n\r\n    bool addImguiParamRadio(const char* label, int& v, int v_button)\r\n    {\r\n        return ImGui::RadioButton(label, &v, v_button);\r\n    }\r\n\r\n    bool addImguiParam(const char* label, string& v)\r\n    {\r\n        ImGuiInputTextFlags flags = 0;\r\n        if (label[0] == '_') flags = ImGuiInputTextFlags_ReadOnly;\r\n        return ImGui::InputText(label, &v, flags);\r\n    }\r\n\r\n    bool addImguiParam(const char* label, quat& v)\r\n    {\r\n        ImGuiInputTextFlags flags = 0;\r\n        if (label[0] == '_') flags = ImGuiInputTextFlags_ReadOnly;\r\n        return ImGui::InputFloat4(label, &v.x, NULL, flags);\r\n    }\r\n\r\n    bool addImguiParam(const char* label, vec2& v)\r\n    {\r\n        ImGuiInputTextFlags flags = 0;\r\n        if (label[0] == '_') flags = ImGuiInputTextFlags_ReadOnly;\r\n        return ImGui::InputFloat2(label, &v.x, NULL, flags);\r\n    }\r\n\r\n    bool addImguiParam(const char* label, ivec2& v)\r\n    {\r\n        ImGuiInputTextFlags flags = 0;\r\n        if (label[0] == '_') flags = ImGuiInputTextFlags_ReadOnly;\r\n        return ImGui::InputInt2(label, &v.x, flags);\r\n    }\r\n\r\n    bool addImguiParam(const char* label, vec3& v)\r\n    {\r\n        ImGuiInputTextFlags flags = 0;\r\n        if (label[0] == '_') flags = ImGuiInputTextFlags_ReadOnly;\r\n        return ImGui::InputFloat3(label, &v.x, NULL, flags);\r\n    }\r\n\r\n    bool addImguiParam(const char* label, vec4& v)\r\n    {\r\n        ImGuiInputTextFlags flags = 0;\r\n        if (label[0] == '_') flags = ImGuiInputTextFlags_ReadOnly;\r\n        return ImGui::InputFloat4(label, &v.x, NULL, flags);\r\n    }\r\n\r\n    bool addImguiParam(const char* label, Color& v)\r\n    {\r\n        return ImGui::ColorEdit3(label, &v.r);\r\n    }\r\n\r\n    bool addImguiParam(const char* label, ColorA& v)\r\n    {\r\n        return ImGui::ColorEdit4(label, &v.r, true);\r\n    }\r\n\r\n    void drawMinicofigImgui(bool createNewWindow = false)\r\n    {\r\n        if (createNewWindow)\r\n            ImGui::Begin(CONFIG_XML, NULL, ImGuiWindowFlags_AlwaysAutoResize);\r\n\r\n        if (ImGui::Button(\"Save\"))\r\n        {\r\n            writeConfig();\r\n        }\r\n\r\n        ImGui::SameLine();\r\n        if (ImGui::Button(\"Screenshot\"))\r\n        {\r\n            takeScreenShot();\r\n        }\r\n\r\n        ImGui::SameLine();\r\n        if (ImGui::Button(\"Quit\"))\r\n        {\r\n            App::get()->quit();\r\n        }\r\n        \r\n        auto profilerHtml = getAssetPath(\"webui_remotery/index.html\");\r\n        if (fs::exists(profilerHtml))\r\n        {\r\n            ImGui::SameLine();\r\n            if (ImGui::Button(\"Profiler\"))\r\n            {\r\n                launchWebBrowser(Url(profilerHtml.string(), true));\r\n            }\r\n        }\r\n\r\n#if !defined(NDEBUG) && !defined(IMGUI_DISABLE_DEMO_WINDOWS)\r\n        static bool isDemoWindowOpened = false;\r\n        if (ImGui::Button(\"ShowDemoWindow\"))\r\n            isDemoWindowOpened = !isDemoWindowOpened;\r\n        if (isDemoWindowOpened)\r\n            ImGui::ShowDemoWindow(&isDemoWindowOpened);\r\n#endif  \r\n        \r\n#define GROUP_DEF(grp)                      } if (ImGui::CollapsingHeader(#grp, #grp[0] == '_' ? ImGuiTreeNodeFlags_CollapsingHeader : ImGuiTreeNodeFlags_DefaultOpen)) {\r\n#define ITEM_DEF(type, var, default)        addImguiParam(#var, var);\r\n#define ITEM_DEF_DIGIT(type, var, default, Min, Max)   addImguiParam(#var, var, Min, Max);\r\n#define ITEM_DEF_MINMAX(type, var, default, Min, Max)  addImguiParamSlider(#var, var, Min, Max);\r\n#define ITEM_DEF_RADIO(label, var, button)             addImguiParamRadio(#label, var, button);\r\n#define GROUP_DEF_RADIO(var, default)\r\n        if (true)\r\n        {\r\n#include \"item.def\"\r\n        }\r\n#undef GROUP_DEF_RADIO\r\n#undef ITEM_DEF_RADIO\r\n#undef ITEM_DEF_MINMAX\r\n#undef ITEM_DEF_DIGIT\r\n#undef ITEM_DEF\r\n#undef GROUP_DEF\r\n\r\n        if (createNewWindow)\r\n            ImGui::End();\r\n    }\r\n}\r\n\r\n//! autoDraw: Specify whether the block should call vnm::drawMinicofigImgui automatically. Default to true.\r\n//! autoRender: Specify whether the block should call ImGui::NewFrame and ImGui::Render automatically. Default to true.\r\nvoid createConfigImgui(WindowRef window = getWindow(), bool autoDraw = true, bool autoRender = true)\r\n{\r\n    auto option = ImGui::Options()\r\n        .window(window)\r\n        .autoRender(autoRender)\r\n        .iniPath(App::get()->getAppPath() / \"imgui.ini\");\r\n    ImGui::initialize(option);\r\n    if (autoDraw)\r\n        App::get()->getSignalUpdate().connect([] {vnm::drawMinicofigImgui(true); });\r\n}\r\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/include/MotionHelper.h",
    "content": "#pragma once\n\n#include \"cinder/MotionManager.h\"\n#include \"cinder/app/App.h\"\n#include \"cinder/Log.h\"\n\nusing namespace ci;\nusing namespace ci::app;\n\nstruct MotionHelper\n{\n    mat4            deviceRotation;\n\n    void setup()\n    {\n        CI_LOG_V( \"gyro available: \" << MotionManager::isGyroAvailable() );\n        \n        MotionManager::enable( 1000.0f/*, MotionManager::SensorMode::Accelerometer*/ );\n        \n        auto updateFn = [this]\n        {\n            if ( MotionManager::isEnabled() )\n            {\n                deviceRotation = inverse( MotionManager::getRotationMatrix() );\n            }\n        };\n        \n        App::get()->getSignalUpdate().connect(updateFn);\n    }\n    \n};\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/include/NvOptimusEnablement.h",
    "content": "/*\n Nvidia Enablement\n Copyright (c) 2016, Simon Geilfus, All rights reserved.\n \n Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n the following conditions are met:\n \n * Redistributions of source code must retain the above copyright notice, this list of conditions and\n\tthe following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n\tthe following disclaimer in the documentation and/or other materials provided with the distribution.\n \n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n POSSIBILITY OF SUCH DAMAGE.\n */\n\n#pragma once\n\n#if defined(_WIN32) || defined(__WIN32__) || defined(WIN32)\n#ifndef DISABLE_NVIDIA_ENABLEMENT\n#include <windows.h>\n\nextern \"C\" \n{ \n\t_declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001; \n}\n\n#endif\n#endif"
  },
  {
    "path": "3rdparty/Cinder-VNM/include/OscHelper.h",
    "content": "#pragma once\r\n\r\n#include \"cinder/osc/Osc.h\"\r\n#include \"cinder/Log.h\"\r\n\r\nstruct OscHelper\r\n{\r\n    static std::unique_ptr<cinder::osc::SenderUdp> createSender(const std::string& remoteIp, uint16_t remotePort)\r\n    {\r\n        auto sender = std::make_unique<cinder::osc::SenderUdp>(10000, remoteIp, remotePort);\r\n        try\r\n        {\r\n            sender->bind();\r\n            CI_LOG_I(\"sender->bind() \" << remoteIp << \":\" << remotePort);\r\n        }\r\n        catch (const cinder::Exception &ex)\r\n        {\r\n            CI_LOG_EXCEPTION(\"sender->bind() fails \", ex);\r\n        }\r\n\r\n        return sender;\r\n    }\r\n\r\n    static std::unique_ptr<cinder::osc::ReceiverUdp> createReceiver(uint16_t localPort)\r\n    {\r\n        auto receiver = std::make_unique<cinder::osc::ReceiverUdp>(localPort);\r\n        try\r\n        {\r\n            receiver->bind();\r\n            CI_LOG_I(\"sender->bind() \" << localPort);\r\n        }\r\n        catch (const cinder::Exception &ex)\r\n        {\r\n            CI_LOG_EXCEPTION(\"receiver->bind() fails\", ex);\r\n        }\r\n\r\n        receiver->listen([](asio::error_code ec, asio::ip::udp::endpoint ep) -> bool {\r\n            if (ec) {\r\n                CI_LOG_E(\"Error on listener: \" << ec.message() << \" Error Value: \" << ec.value());\r\n                return false;\r\n            }\r\n            else\r\n                return true;\r\n        });\r\n\r\n        return receiver;\r\n\r\n#if 0\r\n        mOscReceiver->setListener(\"/start\", [&](const osc::Message& message) {\r\n            console() << message;\r\n        });\r\n#endif\r\n    }\r\n};\r\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/include/SharedMemory.h",
    "content": "#pragma once\n\n#include <string>\n#include <stdio.h>\n#include <sys/stat.h>\n#ifdef _WIN32\n#include <windows.h>\n#include <conio.h>\n#include <tchar.h>\n#else\n#include <sys/shm.h>\n#endif\n\n\n/*\nSharedMemory by Trent Brooks\nOpenframeworks example of a memory mapped file for sharing data between multiple applications.\n- https://en.wikipedia.org/wiki/Memory-mapped_file\n\nThanks to sloopi & KJ1 on the openframeworks forum for introducing me to 'memory mapped files'\n- http://forum.openframeworks.cc/index.php/topic,11730.msg55510.html#msg55510\n\nTODO::\n- need to allow reconnection for the client when server closes the shared memory without having to connect() in update/every frame\n- example for sharing non image data- eg. floats, ints, std::strings, etc.\n*/\n\n\ntemplate <typename T>\nclass SharedMemory {\n\npublic:\n\n    SharedMemory();\n    ~SharedMemory();\n\n    void setup(std::string memKey, int size, bool isServer);\n\n    bool connect();\n    void close();\n\n    void setData(T* sourceData);\n\n    // data to share\n    const T* getData() const;\n\nprotected:\n\n    bool isServer; // only the server can 'close' the shared data\n    std::string memoryKey;\n    int memorySize;\n\n    //unsigned char *sharedData;\n    T* sharedData;\n    bool isReady;\n\n#ifdef _WIN32\n    std::wstring tMemoryKey;\n    HANDLE hMapFile;\n#endif\n};\n\n\n//--------------------------------------------------------------\n/* \nImplementation\nKeeping implementation inside the .h to make the client side neater.\nOtherwise the testApp has to import SharedMemory.cpp as well as SharedMemory.h\n*/\n//--------------------------------------------------------------\ntemplate <typename T>\nSharedMemory<T>::SharedMemory(){\n\n    sharedData = NULL;\n    isServer = false;\n    memoryKey = \"\";\n    memorySize = 0;\n    isReady = false;\n}\n\ntemplate <typename T>\nSharedMemory<T>::~SharedMemory(){\n    close();\n}\n\ntemplate <typename T>\nvoid SharedMemory<T>::setup(std::string memoryKey, int memorySize, bool isServer) {\n\n    this->memoryKey = memoryKey;\n    this->memorySize = memorySize;\n    this->isServer = isServer;\n\n#ifdef _WIN32\n    tMemoryKey = std::wstring(memoryKey.begin(), memoryKey.end());\n#endif\n}\n\ntemplate <typename T>\nvoid SharedMemory<T>::close() {\n\n    if(isServer) {\n#ifdef _WIN32\n        UnmapViewOfFile(sharedData);\n        CloseHandle(hMapFile);\n#else\n        munmap(sharedData, memorySize);\n        shm_unlink(memoryKey.c_str());\n#endif\n    }\n\n}\n\ntemplate <typename T>\nbool SharedMemory<T>::connect() {\n#ifdef _WIN32\n\n    if(isServer) {\n        // server must use CreateFileMapping\n        hMapFile = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, memorySize, tMemoryKey.c_str());\n    } else {\n        hMapFile = OpenFileMapping(FILE_MAP_ALL_ACCESS, false, tMemoryKey.c_str());\n    }\n    if(hMapFile == NULL) {\n        isReady = false;\n        return false;\n    }\n\n    sharedData = (T*) MapViewOfFile(hMapFile,FILE_MAP_ALL_ACCESS, 0, 0, memorySize);\n    if(sharedData == NULL) {\n        CloseHandle(hMapFile);\n        isReady = false;\n        return false;\n    }\n#else\n\n    // create/connect to shared memory from dummy file\n    int descriptor = shm_open(memoryKey.c_str(), O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);\n    if(descriptor == -1) {\n        isReady = false;\n        return false;\n    }\n\n    // map to memory\n    ftruncate(descriptor, memorySize);\n    sharedData = (T*) mmap(NULL, memorySize, PROT_WRITE | PROT_READ, MAP_SHARED, descriptor, 0);\n    if(sharedData == NULL) {\n        if(isServer) shm_unlink(memoryKey.c_str());\n        isReady = false;\n        return false;\n    }\n\n#endif\n\n    isReady = true;\n    return true;\n}\n\n// copies source data to shared data\ntemplate <typename T>\nvoid SharedMemory<T>::setData(T* sourceData) {\n    memcpy(sharedData, sourceData, memorySize);\n}\n\n// returns shared data\ntemplate <typename T>\nconst T* SharedMemory<T>::getData() const{\n    return sharedData;\n}\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/include/StateMachine.h",
    "content": "#pragma once\r\n\r\n#include <memory>\r\n#include <string>\r\n\r\n#if 0\r\nstruct AwesomeApp;\r\n\r\nstruct StateIdle : public State<AwesomeApp>\r\n{\r\n    GET_SINGLETON_IMPL(StateIdle);\r\n\r\n    //void enter(AwesomeApp* app);\r\n    //void update(AwesomeApp* app);\r\n    //void draw(AwesomeApp* app);\r\n    //void exit(AwesomeApp* app);\r\n    //void sendMessage(AwesomeApp* app, const std::string& msg);\r\n};\r\n\r\nstruct StatePlay : public State<AwesomeApp>\r\n{\r\n    GET_SINGLETON_IMPL(StatePlay);\r\n\r\n    //void enter(AwesomeApp* app);\r\n    //void update(AwesomeApp* app);\r\n    //void draw(AwesomeApp* app);\r\n    //void exit(AwesomeApp* app);\r\n    //void sendMessage(AwesomeApp* app, const std::string& msg);\r\n};\r\n\r\nstruct AwesomeApp : public App,StateMachine<AwesomeApp>\r\n{\r\n    AwesomeApp()\r\n    {\r\n        setOwner(this);\r\n\r\n        getSignalUpdate().connect([&] {\r\n            updateFSM();\r\n        });\r\n\r\n        getWindow()->getSignalDraw().connect([&] {\r\n            drawFSM();\r\n        });\r\n    }\r\n}\r\n#endif\r\n\r\ntemplate <typename T>\r\nstruct State\r\n{\r\n    typedef std::shared_ptr<State<T>> Ref;\r\n\r\n    virtual std::string getName() { return \"State\"; }\r\n\r\n    virtual void enter(T* owner)    {};\r\n    virtual void update(T* owner)   {};\r\n    virtual void draw(T* owner)     {};\r\n    virtual void exit(T* owner)     {};\r\n    virtual void sendMessage(T* owner, const std::string& msg) {};\r\n};\r\n\r\n#define GET_SINGLETON_IMPL(classname) \\\r\n    static Ref get()\\\r\n{\\\r\n    static Ref sInstance = Ref(new classname);\\\r\n    return sInstance;\\\r\n}\\\r\nstd::string getName() {return #classname;}\r\n\r\ntemplate <typename T>\r\nstruct StateMachine\r\n{\r\n    typedef typename State<T>::Ref StateRef;\r\n    StateRef mCurrentState;\r\n    StateRef mPrevState;\r\n    T* mOwner = nullptr;\r\n\r\n    void setOwner(T* owner)\r\n    {\r\n        mOwner = owner;\r\n    };\r\n\r\n    void updateFSM()\r\n    {\r\n        if (mCurrentState)\r\n            mCurrentState->update(mOwner);\r\n    }\r\n\r\n    void drawFSM()\r\n    {\r\n        if (mCurrentState)\r\n            mCurrentState->draw(mOwner);\r\n    }\r\n\r\n    void sendMessage(const std::string& msg)\r\n    {\r\n        if (mCurrentState)\r\n            mCurrentState->sendMessage(mOwner, msg);\r\n    }\r\n\r\n    void changeToPreviousState()\r\n    {\r\n        changeToState(mPrevState);\r\n    }\r\n\r\n    void changeToState(const StateRef& newState)\r\n    {\r\n        if (mCurrentState == newState)\r\n            return;\r\n\r\n        if (mCurrentState)\r\n        {\r\n            mPrevState = mCurrentState;\r\n            mCurrentState->exit(mOwner);\r\n        }\r\n        mCurrentState = newState;\r\n        mCurrentState->enter(mOwner);\r\n    }\r\n};\r\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/include/TextureHelper.h",
    "content": "#pragma once\r\n\r\n#include \"cinder/gl/Texture.h\"\r\n\r\nusing namespace ci;\r\n\r\ntemplate <typename T>\r\nvoid updateTexture(gl::TextureRef &tex, const T &src, const gl::Texture2d::Format& format = gl::Texture2d::Format())\r\n{\r\n    if (src.getWidth() == 0) return;\r\n\r\n    if (!tex \r\n        || tex->getWidth() != src.getWidth()\r\n        || tex->getHeight() != src.getHeight())\r\n    {\r\n        tex = gl::Texture2d::create(src, format);\r\n    }\r\n    else\r\n    {\r\n        tex->update(src);\r\n    }\r\n}\r\n\r\nstatic gl::Texture::Format getTextureFormatUINT16()\r\n{\r\n    return gl::Texture::Format()\r\n        .dataType(GL_UNSIGNED_SHORT)\r\n        .internalFormat(GL_R16UI)\r\n        .minFilter(GL_NEAREST)\r\n        .immutableStorage();\r\n}\r\n\r\nstatic gl::TextureCubeMap::Format getTextureFormatHDRCubeMap()\r\n{\r\n    return gl::TextureCubeMap::Format()\r\n        .mipmap()\r\n        .internalFormat(GL_RGB16F)\r\n        .minFilter(GL_LINEAR_MIPMAP_LINEAR)\r\n        .magFilter(GL_LINEAR)\r\n        .immutableStorage();\r\n}\r\n\r\nstatic gl::Texture::Format getTextureFormatDefault()\r\n{\r\n    return gl::Texture::Format()\r\n        .mipmap()\r\n        .minFilter(GL_LINEAR_MIPMAP_LINEAR)\r\n        .magFilter(GL_LINEAR)\r\n        .wrap(GL_REPEAT);\r\n}\r\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/include/TuioHelper.h",
    "content": "#pragma once\r\n\r\n#include \"cinder/osc/Osc.h\"\r\n#include \"cinder/Log.h\"\r\n\r\nstruct TuioHelper\r\n{\r\n    static std::unique_ptr<cinder::osc::SenderUdp> createSender(const std::string& remoteIp, uint16_t remotePort)\r\n    {\r\n        auto sender = std::make_unique<cinder::osc::SenderUdp>(10000, remoteIp, remotePort);\r\n        try\r\n        {\r\n            sender->bind();\r\n            CI_LOG_I(\"sender->bind() \" << remoteIp << \":\" << remotePort);\r\n        }\r\n        catch (const cinder::Exception &ex)\r\n        {\r\n            CI_LOG_EXCEPTION(\"sender->bind() fails \", ex);\r\n        }\r\n\r\n        return sender;\r\n    }\r\n\r\n    static std::unique_ptr<cinder::osc::ReceiverUdp> createReceiver(uint16_t localPort)\r\n    {\r\n        auto receiver = std::make_unique<cinder::osc::ReceiverUdp>(localPort);\r\n        try\r\n        {\r\n            receiver->bind();\r\n            CI_LOG_I(\"sender->bind() \" << localPort);\r\n        }\r\n        catch (const cinder::Exception &ex)\r\n        {\r\n            CI_LOG_EXCEPTION(\"receiver->bind() fails\", ex);\r\n        }\r\n\r\n        receiver->listen([](asio::error_code ec, asio::ip::udp::endpoint ep) -> bool {\r\n            if (ec) {\r\n                CI_LOG_E(\"Error on listener: \" << ec.message() << \" Error Value: \" << ec.value());\r\n                return false;\r\n            }\r\n            else\r\n                return true;\r\n        });\r\n\r\n        return receiver;\r\n    }\r\n};\r\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/include/renderdoc_app.h",
    "content": "/******************************************************************************\n * The MIT License (MIT)\n *\n * Copyright (c) 2019-2020 Baldur Karlsson\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n ******************************************************************************/\n\n#pragma once\n\n//////////////////////////////////////////////////////////////////////////////////////////////////\n//\n// Documentation for the API is available at https://renderdoc.org/docs/in_application_api.html\n//\n\n#if !defined(RENDERDOC_NO_STDINT)\n#include <stdint.h>\n#endif\n\n#if defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER)\n#define RENDERDOC_CC __cdecl\n#elif defined(__linux__)\n#define RENDERDOC_CC\n#elif defined(__APPLE__)\n#define RENDERDOC_CC\n#else\n#error \"Unknown platform\"\n#endif\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n//////////////////////////////////////////////////////////////////////////////////////////////////\n// Constants not used directly in below API\n\n// This is a GUID/magic value used for when applications pass a path where shader debug\n// information can be found to match up with a stripped shader.\n// the define can be used like so: const GUID RENDERDOC_ShaderDebugMagicValue =\n// RENDERDOC_ShaderDebugMagicValue_value\n#define RENDERDOC_ShaderDebugMagicValue_struct                                \\\n  {                                                                           \\\n    0xeab25520, 0x6670, 0x4865, 0x84, 0x29, 0x6c, 0x8, 0x51, 0x54, 0x00, 0xff \\\n  }\n\n// as an alternative when you want a byte array (assuming x86 endianness):\n#define RENDERDOC_ShaderDebugMagicValue_bytearray                                                 \\\n  {                                                                                               \\\n    0x20, 0x55, 0xb2, 0xea, 0x70, 0x66, 0x65, 0x48, 0x84, 0x29, 0x6c, 0x8, 0x51, 0x54, 0x00, 0xff \\\n  }\n\n// truncated version when only a uint64_t is available (e.g. Vulkan tags):\n#define RENDERDOC_ShaderDebugMagicValue_truncated 0x48656670eab25520ULL\n\n//////////////////////////////////////////////////////////////////////////////////////////////////\n// RenderDoc capture options\n//\n\ntypedef enum RENDERDOC_CaptureOption {\n  // Allow the application to enable vsync\n  //\n  // Default - enabled\n  //\n  // 1 - The application can enable or disable vsync at will\n  // 0 - vsync is force disabled\n  eRENDERDOC_Option_AllowVSync = 0,\n\n  // Allow the application to enable fullscreen\n  //\n  // Default - enabled\n  //\n  // 1 - The application can enable or disable fullscreen at will\n  // 0 - fullscreen is force disabled\n  eRENDERDOC_Option_AllowFullscreen = 1,\n\n  // Record API debugging events and messages\n  //\n  // Default - disabled\n  //\n  // 1 - Enable built-in API debugging features and records the results into\n  //     the capture, which is matched up with events on replay\n  // 0 - no API debugging is forcibly enabled\n  eRENDERDOC_Option_APIValidation = 2,\n  eRENDERDOC_Option_DebugDeviceMode = 2,    // deprecated name of this enum\n\n  // Capture CPU callstacks for API events\n  //\n  // Default - disabled\n  //\n  // 1 - Enables capturing of callstacks\n  // 0 - no callstacks are captured\n  eRENDERDOC_Option_CaptureCallstacks = 3,\n\n  // When capturing CPU callstacks, only capture them from drawcalls.\n  // This option does nothing without the above option being enabled\n  //\n  // Default - disabled\n  //\n  // 1 - Only captures callstacks for drawcall type API events.\n  //     Ignored if CaptureCallstacks is disabled\n  // 0 - Callstacks, if enabled, are captured for every event.\n  eRENDERDOC_Option_CaptureCallstacksOnlyDraws = 4,\n\n  // Specify a delay in seconds to wait for a debugger to attach, after\n  // creating or injecting into a process, before continuing to allow it to run.\n  //\n  // 0 indicates no delay, and the process will run immediately after injection\n  //\n  // Default - 0 seconds\n  //\n  eRENDERDOC_Option_DelayForDebugger = 5,\n\n  // Verify buffer access. This includes checking the memory returned by a Map() call to\n  // detect any out-of-bounds modification, as well as initialising buffers with undefined contents\n  // to a marker value to catch use of uninitialised memory.\n  //\n  // NOTE: This option is only valid for OpenGL and D3D11. Explicit APIs such as D3D12 and Vulkan do\n  // not do the same kind of interception & checking and undefined contents are really undefined.\n  //\n  // Default - disabled\n  //\n  // 1 - Verify buffer access\n  // 0 - No verification is performed, and overwriting bounds may cause crashes or corruption in\n  //     RenderDoc.\n  eRENDERDOC_Option_VerifyBufferAccess = 6,\n\n  // The old name for eRENDERDOC_Option_VerifyBufferAccess was eRENDERDOC_Option_VerifyMapWrites.\n  // This option now controls the filling of uninitialised buffers with 0xdddddddd which was\n  // previously always enabled\n  eRENDERDOC_Option_VerifyMapWrites = eRENDERDOC_Option_VerifyBufferAccess,\n\n  // Hooks any system API calls that create child processes, and injects\n  // RenderDoc into them recursively with the same options.\n  //\n  // Default - disabled\n  //\n  // 1 - Hooks into spawned child processes\n  // 0 - Child processes are not hooked by RenderDoc\n  eRENDERDOC_Option_HookIntoChildren = 7,\n\n  // By default RenderDoc only includes resources in the final capture necessary\n  // for that frame, this allows you to override that behaviour.\n  //\n  // Default - disabled\n  //\n  // 1 - all live resources at the time of capture are included in the capture\n  //     and available for inspection\n  // 0 - only the resources referenced by the captured frame are included\n  eRENDERDOC_Option_RefAllResources = 8,\n\n  // **NOTE**: As of RenderDoc v1.1 this option has been deprecated. Setting or\n  // getting it will be ignored, to allow compatibility with older versions.\n  // In v1.1 the option acts as if it's always enabled.\n  //\n  // By default RenderDoc skips saving initial states for resources where the\n  // previous contents don't appear to be used, assuming that writes before\n  // reads indicate previous contents aren't used.\n  //\n  // Default - disabled\n  //\n  // 1 - initial contents at the start of each captured frame are saved, even if\n  //     they are later overwritten or cleared before being used.\n  // 0 - unless a read is detected, initial contents will not be saved and will\n  //     appear as black or empty data.\n  eRENDERDOC_Option_SaveAllInitials = 9,\n\n  // In APIs that allow for the recording of command lists to be replayed later,\n  // RenderDoc may choose to not capture command lists before a frame capture is\n  // triggered, to reduce overheads. This means any command lists recorded once\n  // and replayed many times will not be available and may cause a failure to\n  // capture.\n  //\n  // NOTE: This is only true for APIs where multithreading is difficult or\n  // discouraged. Newer APIs like Vulkan and D3D12 will ignore this option\n  // and always capture all command lists since the API is heavily oriented\n  // around it and the overheads have been reduced by API design.\n  //\n  // 1 - All command lists are captured from the start of the application\n  // 0 - Command lists are only captured if their recording begins during\n  //     the period when a frame capture is in progress.\n  eRENDERDOC_Option_CaptureAllCmdLists = 10,\n\n  // Mute API debugging output when the API validation mode option is enabled\n  //\n  // Default - enabled\n  //\n  // 1 - Mute any API debug messages from being displayed or passed through\n  // 0 - API debugging is displayed as normal\n  eRENDERDOC_Option_DebugOutputMute = 11,\n\n  // Option to allow vendor extensions to be used even when they may be\n  // incompatible with RenderDoc and cause corrupted replays or crashes.\n  //\n  // Default - inactive\n  //\n  // No values are documented, this option should only be used when absolutely\n  // necessary as directed by a RenderDoc developer.\n  eRENDERDOC_Option_AllowUnsupportedVendorExtensions = 12,\n\n} RENDERDOC_CaptureOption;\n\n// Sets an option that controls how RenderDoc behaves on capture.\n//\n// Returns 1 if the option and value are valid\n// Returns 0 if either is invalid and the option is unchanged\ntypedef int(RENDERDOC_CC *pRENDERDOC_SetCaptureOptionU32)(RENDERDOC_CaptureOption opt, uint32_t val);\ntypedef int(RENDERDOC_CC *pRENDERDOC_SetCaptureOptionF32)(RENDERDOC_CaptureOption opt, float val);\n\n// Gets the current value of an option as a uint32_t\n//\n// If the option is invalid, 0xffffffff is returned\ntypedef uint32_t(RENDERDOC_CC *pRENDERDOC_GetCaptureOptionU32)(RENDERDOC_CaptureOption opt);\n\n// Gets the current value of an option as a float\n//\n// If the option is invalid, -FLT_MAX is returned\ntypedef float(RENDERDOC_CC *pRENDERDOC_GetCaptureOptionF32)(RENDERDOC_CaptureOption opt);\n\ntypedef enum RENDERDOC_InputButton {\n  // '0' - '9' matches ASCII values\n  eRENDERDOC_Key_0 = 0x30,\n  eRENDERDOC_Key_1 = 0x31,\n  eRENDERDOC_Key_2 = 0x32,\n  eRENDERDOC_Key_3 = 0x33,\n  eRENDERDOC_Key_4 = 0x34,\n  eRENDERDOC_Key_5 = 0x35,\n  eRENDERDOC_Key_6 = 0x36,\n  eRENDERDOC_Key_7 = 0x37,\n  eRENDERDOC_Key_8 = 0x38,\n  eRENDERDOC_Key_9 = 0x39,\n\n  // 'A' - 'Z' matches ASCII values\n  eRENDERDOC_Key_A = 0x41,\n  eRENDERDOC_Key_B = 0x42,\n  eRENDERDOC_Key_C = 0x43,\n  eRENDERDOC_Key_D = 0x44,\n  eRENDERDOC_Key_E = 0x45,\n  eRENDERDOC_Key_F = 0x46,\n  eRENDERDOC_Key_G = 0x47,\n  eRENDERDOC_Key_H = 0x48,\n  eRENDERDOC_Key_I = 0x49,\n  eRENDERDOC_Key_J = 0x4A,\n  eRENDERDOC_Key_K = 0x4B,\n  eRENDERDOC_Key_L = 0x4C,\n  eRENDERDOC_Key_M = 0x4D,\n  eRENDERDOC_Key_N = 0x4E,\n  eRENDERDOC_Key_O = 0x4F,\n  eRENDERDOC_Key_P = 0x50,\n  eRENDERDOC_Key_Q = 0x51,\n  eRENDERDOC_Key_R = 0x52,\n  eRENDERDOC_Key_S = 0x53,\n  eRENDERDOC_Key_T = 0x54,\n  eRENDERDOC_Key_U = 0x55,\n  eRENDERDOC_Key_V = 0x56,\n  eRENDERDOC_Key_W = 0x57,\n  eRENDERDOC_Key_X = 0x58,\n  eRENDERDOC_Key_Y = 0x59,\n  eRENDERDOC_Key_Z = 0x5A,\n\n  // leave the rest of the ASCII range free\n  // in case we want to use it later\n  eRENDERDOC_Key_NonPrintable = 0x100,\n\n  eRENDERDOC_Key_Divide,\n  eRENDERDOC_Key_Multiply,\n  eRENDERDOC_Key_Subtract,\n  eRENDERDOC_Key_Plus,\n\n  eRENDERDOC_Key_F1,\n  eRENDERDOC_Key_F2,\n  eRENDERDOC_Key_F3,\n  eRENDERDOC_Key_F4,\n  eRENDERDOC_Key_F5,\n  eRENDERDOC_Key_F6,\n  eRENDERDOC_Key_F7,\n  eRENDERDOC_Key_F8,\n  eRENDERDOC_Key_F9,\n  eRENDERDOC_Key_F10,\n  eRENDERDOC_Key_F11,\n  eRENDERDOC_Key_F12,\n\n  eRENDERDOC_Key_Home,\n  eRENDERDOC_Key_End,\n  eRENDERDOC_Key_Insert,\n  eRENDERDOC_Key_Delete,\n  eRENDERDOC_Key_PageUp,\n  eRENDERDOC_Key_PageDn,\n\n  eRENDERDOC_Key_Backspace,\n  eRENDERDOC_Key_Tab,\n  eRENDERDOC_Key_PrtScrn,\n  eRENDERDOC_Key_Pause,\n\n  eRENDERDOC_Key_Max,\n} RENDERDOC_InputButton;\n\n// Sets which key or keys can be used to toggle focus between multiple windows\n//\n// If keys is NULL or num is 0, toggle keys will be disabled\ntypedef void(RENDERDOC_CC *pRENDERDOC_SetFocusToggleKeys)(RENDERDOC_InputButton *keys, int num);\n\n// Sets which key or keys can be used to capture the next frame\n//\n// If keys is NULL or num is 0, captures keys will be disabled\ntypedef void(RENDERDOC_CC *pRENDERDOC_SetCaptureKeys)(RENDERDOC_InputButton *keys, int num);\n\ntypedef enum RENDERDOC_OverlayBits {\n  // This single bit controls whether the overlay is enabled or disabled globally\n  eRENDERDOC_Overlay_Enabled = 0x1,\n\n  // Show the average framerate over several seconds as well as min/max\n  eRENDERDOC_Overlay_FrameRate = 0x2,\n\n  // Show the current frame number\n  eRENDERDOC_Overlay_FrameNumber = 0x4,\n\n  // Show a list of recent captures, and how many captures have been made\n  eRENDERDOC_Overlay_CaptureList = 0x8,\n\n  // Default values for the overlay mask\n  eRENDERDOC_Overlay_Default = (eRENDERDOC_Overlay_Enabled | eRENDERDOC_Overlay_FrameRate |\n                                eRENDERDOC_Overlay_FrameNumber | eRENDERDOC_Overlay_CaptureList),\n\n  // Enable all bits\n  eRENDERDOC_Overlay_All = ~0U,\n\n  // Disable all bits\n  eRENDERDOC_Overlay_None = 0,\n} RENDERDOC_OverlayBits;\n\n// returns the overlay bits that have been set\ntypedef uint32_t(RENDERDOC_CC *pRENDERDOC_GetOverlayBits)();\n// sets the overlay bits with an and & or mask\ntypedef void(RENDERDOC_CC *pRENDERDOC_MaskOverlayBits)(uint32_t And, uint32_t Or);\n\n// this function will attempt to remove RenderDoc's hooks in the application.\n//\n// Note: that this can only work correctly if done immediately after\n// the module is loaded, before any API work happens. RenderDoc will remove its\n// injected hooks and shut down. Behaviour is undefined if this is called\n// after any API functions have been called, and there is still no guarantee of\n// success.\ntypedef void(RENDERDOC_CC *pRENDERDOC_RemoveHooks)();\n\n// DEPRECATED: compatibility for code compiled against pre-1.4.1 headers.\ntypedef pRENDERDOC_RemoveHooks pRENDERDOC_Shutdown;\n\n// This function will unload RenderDoc's crash handler.\n//\n// If you use your own crash handler and don't want RenderDoc's handler to\n// intercede, you can call this function to unload it and any unhandled\n// exceptions will pass to the next handler.\ntypedef void(RENDERDOC_CC *pRENDERDOC_UnloadCrashHandler)();\n\n// Sets the capture file path template\n//\n// pathtemplate is a UTF-8 string that gives a template for how captures will be named\n// and where they will be saved.\n//\n// Any extension is stripped off the path, and captures are saved in the directory\n// specified, and named with the filename and the frame number appended. If the\n// directory does not exist it will be created, including any parent directories.\n//\n// If pathtemplate is NULL, the template will remain unchanged\n//\n// Example:\n//\n// SetCaptureFilePathTemplate(\"my_captures/example\");\n//\n// Capture #1 -> my_captures/example_frame123.rdc\n// Capture #2 -> my_captures/example_frame456.rdc\ntypedef void(RENDERDOC_CC *pRENDERDOC_SetCaptureFilePathTemplate)(const char *pathtemplate);\n\n// returns the current capture path template, see SetCaptureFileTemplate above, as a UTF-8 string\ntypedef const char *(RENDERDOC_CC *pRENDERDOC_GetCaptureFilePathTemplate)();\n\n// DEPRECATED: compatibility for code compiled against pre-1.1.2 headers.\ntypedef pRENDERDOC_SetCaptureFilePathTemplate pRENDERDOC_SetLogFilePathTemplate;\ntypedef pRENDERDOC_GetCaptureFilePathTemplate pRENDERDOC_GetLogFilePathTemplate;\n\n// returns the number of captures that have been made\ntypedef uint32_t(RENDERDOC_CC *pRENDERDOC_GetNumCaptures)();\n\n// This function returns the details of a capture, by index. New captures are added\n// to the end of the list.\n//\n// filename will be filled with the absolute path to the capture file, as a UTF-8 string\n// pathlength will be written with the length in bytes of the filename string\n// timestamp will be written with the time of the capture, in seconds since the Unix epoch\n//\n// Any of the parameters can be NULL and they'll be skipped.\n//\n// The function will return 1 if the capture index is valid, or 0 if the index is invalid\n// If the index is invalid, the values will be unchanged\n//\n// Note: when captures are deleted in the UI they will remain in this list, so the\n// capture path may not exist anymore.\ntypedef uint32_t(RENDERDOC_CC *pRENDERDOC_GetCapture)(uint32_t idx, char *filename,\n                                                      uint32_t *pathlength, uint64_t *timestamp);\n\n// Sets the comments associated with a capture file. These comments are displayed in the\n// UI program when opening.\n//\n// filePath should be a path to the capture file to add comments to. If set to NULL or \"\"\n// the most recent capture file created made will be used instead.\n// comments should be a NULL-terminated UTF-8 string to add as comments.\n//\n// Any existing comments will be overwritten.\ntypedef void(RENDERDOC_CC *pRENDERDOC_SetCaptureFileComments)(const char *filePath,\n                                                              const char *comments);\n\n// returns 1 if the RenderDoc UI is connected to this application, 0 otherwise\ntypedef uint32_t(RENDERDOC_CC *pRENDERDOC_IsTargetControlConnected)();\n\n// DEPRECATED: compatibility for code compiled against pre-1.1.1 headers.\n// This was renamed to IsTargetControlConnected in API 1.1.1, the old typedef is kept here for\n// backwards compatibility with old code, it is castable either way since it's ABI compatible\n// as the same function pointer type.\ntypedef pRENDERDOC_IsTargetControlConnected pRENDERDOC_IsRemoteAccessConnected;\n\n// This function will launch the Replay UI associated with the RenderDoc library injected\n// into the running application.\n//\n// if connectTargetControl is 1, the Replay UI will be launched with a command line parameter\n// to connect to this application\n// cmdline is the rest of the command line, as a UTF-8 string. E.g. a captures to open\n// if cmdline is NULL, the command line will be empty.\n//\n// returns the PID of the replay UI if successful, 0 if not successful.\ntypedef uint32_t(RENDERDOC_CC *pRENDERDOC_LaunchReplayUI)(uint32_t connectTargetControl,\n                                                          const char *cmdline);\n\n// RenderDoc can return a higher version than requested if it's backwards compatible,\n// this function returns the actual version returned. If a parameter is NULL, it will be\n// ignored and the others will be filled out.\ntypedef void(RENDERDOC_CC *pRENDERDOC_GetAPIVersion)(int *major, int *minor, int *patch);\n\n//////////////////////////////////////////////////////////////////////////\n// Capturing functions\n//\n\n// A device pointer is a pointer to the API's root handle.\n//\n// This would be an ID3D11Device, HGLRC/GLXContext, ID3D12Device, etc\ntypedef void *RENDERDOC_DevicePointer;\n\n// A window handle is the OS's native window handle\n//\n// This would be an HWND, GLXDrawable, etc\ntypedef void *RENDERDOC_WindowHandle;\n\n// A helper macro for Vulkan, where the device handle cannot be used directly.\n//\n// Passing the VkInstance to this macro will return the RENDERDOC_DevicePointer to use.\n//\n// Specifically, the value needed is the dispatch table pointer, which sits as the first\n// pointer-sized object in the memory pointed to by the VkInstance. Thus we cast to a void** and\n// indirect once.\n#define RENDERDOC_DEVICEPOINTER_FROM_VKINSTANCE(inst) (*((void **)(inst)))\n\n// This sets the RenderDoc in-app overlay in the API/window pair as 'active' and it will\n// respond to keypresses. Neither parameter can be NULL\ntypedef void(RENDERDOC_CC *pRENDERDOC_SetActiveWindow)(RENDERDOC_DevicePointer device,\n                                                       RENDERDOC_WindowHandle wndHandle);\n\n// capture the next frame on whichever window and API is currently considered active\ntypedef void(RENDERDOC_CC *pRENDERDOC_TriggerCapture)();\n\n// capture the next N frames on whichever window and API is currently considered active\ntypedef void(RENDERDOC_CC *pRENDERDOC_TriggerMultiFrameCapture)(uint32_t numFrames);\n\n// When choosing either a device pointer or a window handle to capture, you can pass NULL.\n// Passing NULL specifies a 'wildcard' match against anything. This allows you to specify\n// any API rendering to a specific window, or a specific API instance rendering to any window,\n// or in the simplest case of one window and one API, you can just pass NULL for both.\n//\n// In either case, if there are two or more possible matching (device,window) pairs it\n// is undefined which one will be captured.\n//\n// Note: for headless rendering you can pass NULL for the window handle and either specify\n// a device pointer or leave it NULL as above.\n\n// Immediately starts capturing API calls on the specified device pointer and window handle.\n//\n// If there is no matching thing to capture (e.g. no supported API has been initialised),\n// this will do nothing.\n//\n// The results are undefined (including crashes) if two captures are started overlapping,\n// even on separate devices and/oror windows.\ntypedef void(RENDERDOC_CC *pRENDERDOC_StartFrameCapture)(RENDERDOC_DevicePointer device,\n                                                         RENDERDOC_WindowHandle wndHandle);\n\n// Returns whether or not a frame capture is currently ongoing anywhere.\n//\n// This will return 1 if a capture is ongoing, and 0 if there is no capture running\ntypedef uint32_t(RENDERDOC_CC *pRENDERDOC_IsFrameCapturing)();\n\n// Ends capturing immediately.\n//\n// This will return 1 if the capture succeeded, and 0 if there was an error capturing.\ntypedef uint32_t(RENDERDOC_CC *pRENDERDOC_EndFrameCapture)(RENDERDOC_DevicePointer device,\n                                                           RENDERDOC_WindowHandle wndHandle);\n\n// Ends capturing immediately and discard any data stored without saving to disk.\n//\n// This will return 1 if the capture was discarded, and 0 if there was an error or no capture\n// was in progress\ntypedef uint32_t(RENDERDOC_CC *pRENDERDOC_DiscardFrameCapture)(RENDERDOC_DevicePointer device,\n                                                               RENDERDOC_WindowHandle wndHandle);\n\n//////////////////////////////////////////////////////////////////////////////////////////////////\n// RenderDoc API versions\n//\n\n// RenderDoc uses semantic versioning (http://semver.org/).\n//\n// MAJOR version is incremented when incompatible API changes happen.\n// MINOR version is incremented when functionality is added in a backwards-compatible manner.\n// PATCH version is incremented when backwards-compatible bug fixes happen.\n//\n// Note that this means the API returned can be higher than the one you might have requested.\n// e.g. if you are running against a newer RenderDoc that supports 1.0.1, it will be returned\n// instead of 1.0.0. You can check this with the GetAPIVersion entry point\ntypedef enum RENDERDOC_Version {\n  eRENDERDOC_API_Version_1_0_0 = 10000,    // RENDERDOC_API_1_0_0 = 1 00 00\n  eRENDERDOC_API_Version_1_0_1 = 10001,    // RENDERDOC_API_1_0_1 = 1 00 01\n  eRENDERDOC_API_Version_1_0_2 = 10002,    // RENDERDOC_API_1_0_2 = 1 00 02\n  eRENDERDOC_API_Version_1_1_0 = 10100,    // RENDERDOC_API_1_1_0 = 1 01 00\n  eRENDERDOC_API_Version_1_1_1 = 10101,    // RENDERDOC_API_1_1_1 = 1 01 01\n  eRENDERDOC_API_Version_1_1_2 = 10102,    // RENDERDOC_API_1_1_2 = 1 01 02\n  eRENDERDOC_API_Version_1_2_0 = 10200,    // RENDERDOC_API_1_2_0 = 1 02 00\n  eRENDERDOC_API_Version_1_3_0 = 10300,    // RENDERDOC_API_1_3_0 = 1 03 00\n  eRENDERDOC_API_Version_1_4_0 = 10400,    // RENDERDOC_API_1_4_0 = 1 04 00\n  eRENDERDOC_API_Version_1_4_1 = 10401,    // RENDERDOC_API_1_4_1 = 1 04 01\n} RENDERDOC_Version;\n\n// API version changelog:\n//\n// 1.0.0 - initial release\n// 1.0.1 - Bugfix: IsFrameCapturing() was returning false for captures that were triggered\n//         by keypress or TriggerCapture, instead of Start/EndFrameCapture.\n// 1.0.2 - Refactor: Renamed eRENDERDOC_Option_DebugDeviceMode to eRENDERDOC_Option_APIValidation\n// 1.1.0 - Add feature: TriggerMultiFrameCapture(). Backwards compatible with 1.0.x since the new\n//         function pointer is added to the end of the struct, the original layout is identical\n// 1.1.1 - Refactor: Renamed remote access to target control (to better disambiguate from remote\n//         replay/remote server concept in replay UI)\n// 1.1.2 - Refactor: Renamed \"log file\" in function names to just capture, to clarify that these\n//         are captures and not debug logging files. This is the first API version in the v1.0\n//         branch.\n// 1.2.0 - Added feature: SetCaptureFileComments() to add comments to a capture file that will be\n//         displayed in the UI program on load.\n// 1.3.0 - Added feature: New capture option eRENDERDOC_Option_AllowUnsupportedVendorExtensions\n//         which allows users to opt-in to allowing unsupported vendor extensions to function.\n//         Should be used at the user's own risk.\n//         Refactor: Renamed eRENDERDOC_Option_VerifyMapWrites to\n//         eRENDERDOC_Option_VerifyBufferAccess, which now also controls initialisation to\n//         0xdddddddd of uninitialised buffer contents.\n// 1.4.0 - Added feature: DiscardFrameCapture() to discard a frame capture in progress and stop\n//         capturing without saving anything to disk.\n// 1.4.1 - Refactor: Renamed Shutdown to RemoveHooks to better clarify what is happening\n\ntypedef struct RENDERDOC_API_1_4_1\n{\n  pRENDERDOC_GetAPIVersion GetAPIVersion;\n\n  pRENDERDOC_SetCaptureOptionU32 SetCaptureOptionU32;\n  pRENDERDOC_SetCaptureOptionF32 SetCaptureOptionF32;\n\n  pRENDERDOC_GetCaptureOptionU32 GetCaptureOptionU32;\n  pRENDERDOC_GetCaptureOptionF32 GetCaptureOptionF32;\n\n  pRENDERDOC_SetFocusToggleKeys SetFocusToggleKeys;\n  pRENDERDOC_SetCaptureKeys SetCaptureKeys;\n\n  pRENDERDOC_GetOverlayBits GetOverlayBits;\n  pRENDERDOC_MaskOverlayBits MaskOverlayBits;\n\n  // Shutdown was renamed to RemoveHooks in 1.4.1.\n  // These unions allow old code to continue compiling without changes\n  union\n  {\n    pRENDERDOC_Shutdown Shutdown;\n    pRENDERDOC_RemoveHooks RemoveHooks;\n  };\n  pRENDERDOC_UnloadCrashHandler UnloadCrashHandler;\n\n  // Get/SetLogFilePathTemplate was renamed to Get/SetCaptureFilePathTemplate in 1.1.2.\n  // These unions allow old code to continue compiling without changes\n  union\n  {\n    // deprecated name\n    pRENDERDOC_SetLogFilePathTemplate SetLogFilePathTemplate;\n    // current name\n    pRENDERDOC_SetCaptureFilePathTemplate SetCaptureFilePathTemplate;\n  };\n  union\n  {\n    // deprecated name\n    pRENDERDOC_GetLogFilePathTemplate GetLogFilePathTemplate;\n    // current name\n    pRENDERDOC_GetCaptureFilePathTemplate GetCaptureFilePathTemplate;\n  };\n\n  pRENDERDOC_GetNumCaptures GetNumCaptures;\n  pRENDERDOC_GetCapture GetCapture;\n\n  pRENDERDOC_TriggerCapture TriggerCapture;\n\n  // IsRemoteAccessConnected was renamed to IsTargetControlConnected in 1.1.1.\n  // This union allows old code to continue compiling without changes\n  union\n  {\n    // deprecated name\n    pRENDERDOC_IsRemoteAccessConnected IsRemoteAccessConnected;\n    // current name\n    pRENDERDOC_IsTargetControlConnected IsTargetControlConnected;\n  };\n  pRENDERDOC_LaunchReplayUI LaunchReplayUI;\n\n  pRENDERDOC_SetActiveWindow SetActiveWindow;\n\n  pRENDERDOC_StartFrameCapture StartFrameCapture;\n  pRENDERDOC_IsFrameCapturing IsFrameCapturing;\n  pRENDERDOC_EndFrameCapture EndFrameCapture;\n\n  // new function in 1.1.0\n  pRENDERDOC_TriggerMultiFrameCapture TriggerMultiFrameCapture;\n\n  // new function in 1.2.0\n  pRENDERDOC_SetCaptureFileComments SetCaptureFileComments;\n\n  // new function in 1.4.0\n  pRENDERDOC_DiscardFrameCapture DiscardFrameCapture;\n} RENDERDOC_API_1_4_1;\n\ntypedef RENDERDOC_API_1_4_1 RENDERDOC_API_1_0_0;\ntypedef RENDERDOC_API_1_4_1 RENDERDOC_API_1_0_1;\ntypedef RENDERDOC_API_1_4_1 RENDERDOC_API_1_0_2;\ntypedef RENDERDOC_API_1_4_1 RENDERDOC_API_1_1_0;\ntypedef RENDERDOC_API_1_4_1 RENDERDOC_API_1_1_1;\ntypedef RENDERDOC_API_1_4_1 RENDERDOC_API_1_1_2;\ntypedef RENDERDOC_API_1_4_1 RENDERDOC_API_1_2_0;\ntypedef RENDERDOC_API_1_4_1 RENDERDOC_API_1_3_0;\ntypedef RENDERDOC_API_1_4_1 RENDERDOC_API_1_4_0;\n\n//////////////////////////////////////////////////////////////////////////////////////////////////\n// RenderDoc API entry point\n//\n// This entry point can be obtained via GetProcAddress/dlsym if RenderDoc is available.\n//\n// The name is the same as the typedef - \"RENDERDOC_GetAPI\"\n//\n// This function is not thread safe, and should not be called on multiple threads at once.\n// Ideally, call this once as early as possible in your application's startup, before doing\n// any API work, since some configuration functionality etc has to be done also before\n// initialising any APIs.\n//\n// Parameters:\n//   version is a single value from the RENDERDOC_Version above.\n//\n//   outAPIPointers will be filled out with a pointer to the corresponding struct of function\n//   pointers.\n//\n// Returns:\n//   1 - if the outAPIPointers has been filled with a pointer to the API struct requested\n//   0 - if the requested version is not supported or the arguments are invalid.\n//\ntypedef int(RENDERDOC_CC *pRENDERDOC_GetAPI)(RENDERDOC_Version version, void **outAPIPointers);\n\n#ifdef __cplusplus\n}    // extern \"C\"\n#endif\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/manually_copy_to_include/item.def",
    "content": "ITEM_DEF(int, APP_WIDTH, 882)\r\nITEM_DEF(int, APP_HEIGHT, 725)\r\nITEM_DEF(string, NAME, \"vinjn\")\r\nITEM_DEF(float, velocity, 3.0f)\r\n\r\nITEM_DEF_MINMAX(float, delay, 3.0f, 0.0f, 10.0f)"
  },
  {
    "path": "3rdparty/Cinder-VNM/src/AssetManager.cpp",
    "content": "#include \"../include/AssetManager.h\"\r\n#include \"cinder/app/App.h\"\r\n#include \"cinder/ImageIo.h\"\r\n#include \"cinder/Function.h\"\r\n#include \"cinder/Utilities.h\"\r\n#include \"cinder/ObjLoader.h\"\r\n#include \"cinder/Log.h\"\r\n#include \"cinder/Function.h\"\r\n#include \"cinder/GeomIo.h\"\r\n#include \"cinder/gl/Shader.h\"\r\n#include \"cinder/gl/Context.h\"\r\n#include \"cinder/gl/Sync.h\"\r\n#include \"cinder/ip/Checkerboard.h\"\r\n#include \"cinder/ConcurrentCircularBuffer.h\"\r\n\r\n#include <map>\r\n\r\nusing namespace std;\r\nusing namespace ci;\r\nusing namespace app;\r\n\r\nstatic bool sShouldQuit = false;\r\ntemplate <typename T>\r\nT& getAssetResource(const string& relativeName, function<T(const string&, const string&)> loadFunc, const string& relativeNameB = \"\")\r\n{\r\n    typedef map<string, T> MapType;\r\n    static MapType sMap;\r\n    static T nullResource;\r\n    auto it = sMap.find(relativeName + relativeNameB);\r\n    if (it != sMap.end())\r\n    {\r\n        return it->second;\r\n    }\r\n\r\n    static std::once_flag connectCloseSignal;\r\n    auto fn = [] {\r\n        App::get()->getSignalCleanup().connect([] {\r\n            sShouldQuit = true;\r\n            sMap.clear();\r\n        });\r\n    };\r\n    std::call_once(connectCloseSignal, fn);\r\n\r\n    fs::path aPath, bPath;\r\n    if (!relativeName.empty())\r\n    {\r\n        aPath = getAssetPath(relativeName);\r\n    }\r\n    if (aPath.empty()) aPath = relativeName;\r\n    if (!relativeNameB.empty())\r\n    {\r\n        bPath = getAssetPath(relativeNameB);\r\n    }\r\n    if (bPath.empty()) bPath = relativeNameB;\r\n\r\n    try\r\n    {\r\n        CI_LOG_I(\"Loading: \" << relativeName << \" \" << relativeNameB);\r\n        auto resource = loadFunc(aPath.string(), bPath.string());\r\n        return sMap[relativeName + relativeNameB] = resource;\r\n    }\r\n    catch (Exception& e)\r\n    {\r\n        CI_LOG_E(cinder::System::demangleTypeName(typeid(e).name()) << \", reason: \\n\" << e.what());\r\n        sMap[relativeName + relativeNameB] = nullResource;\r\n    }\r\n    return nullResource;\r\n}\r\n\r\nnamespace am\r\n{\r\n    void addAssetDirectory(const fs::path& dirPath)\r\n    {\r\n        if (fs::exists(dirPath))\r\n            app::addAssetDirectory(dirPath);\r\n    }\r\n\r\n    BufferRef& buffer(const string& relativeName)\r\n    {\r\n        auto loader = [](const string & absoluteName, const string&) -> BufferRef\r\n        {\r\n            auto source = loadFile(absoluteName);\r\n            return source->getBuffer();\r\n        };\r\n        return getAssetResource<BufferRef>(relativeName, loader);\r\n    }\r\n\r\n    SurfaceRef& surface(const string& relativeName, bool forceAlpha)\r\n    {\r\n        auto loader = [forceAlpha](const string & absoluteName, const string&) -> SurfaceRef\r\n        {\r\n            auto source = loadImage(absoluteName);\r\n            bool hasAlpha = source->hasAlpha() || forceAlpha;\r\n            return Surface::create(source, SurfaceConstraintsDefault(), hasAlpha);\r\n        };\r\n        return getAssetResource<SurfaceRef>(relativeName, loader);\r\n    }\r\n\r\n    Surface16uRef& surface16u(const string& relativeName, bool forceAlpha)\r\n    {\r\n        auto loader = [forceAlpha](const string& absoluteName, const string&) -> Surface16uRef\r\n        {\r\n            auto source = loadImage(absoluteName);\r\n            bool hasAlpha = source->hasAlpha() || forceAlpha;\r\n            return Surface16u::create(source, SurfaceConstraintsDefault(), hasAlpha);\r\n        };\r\n        return getAssetResource<Surface16uRef>(relativeName, loader);\r\n    }\r\n\r\n    Surface32fRef& surface32f(const string& relativeName, bool forceAlpha)\r\n    {\r\n        auto loader = [forceAlpha](const string& absoluteName, const string&) -> Surface32fRef\r\n        {\r\n            auto source = loadImage(absoluteName);\r\n            bool hasAlpha = source->hasAlpha() || forceAlpha;\r\n            return Surface32f::create(source, SurfaceConstraintsDefault(), hasAlpha);\r\n        };\r\n        return getAssetResource<Surface32fRef>(relativeName, loader);\r\n    }\r\n\r\n    ChannelRef& channel(const std::string& relativeName)\r\n    {\r\n        auto loader = [](const string & absoluteName, const string&) -> ChannelRef\r\n        {\r\n            auto source = loadImage(absoluteName);\r\n            return Channel::create(source);\r\n        };\r\n        return getAssetResource<ChannelRef>(relativeName, loader);\r\n    }\r\n\r\n    Channel16uRef& channel16u(const std::string& relativeName)\r\n    {\r\n        auto loader = [](const string & absoluteName, const string&) -> Channel16uRef\r\n        {\r\n            auto source = loadImage(absoluteName);\r\n            return Channel16u::create(source);\r\n        };\r\n        return getAssetResource<Channel16uRef>(relativeName, loader);\r\n    }\r\n\r\n    template <typename T>\r\n    shared_ptr<T>& texture(const string& relativeName, const typename T::Format& format, bool isAsync)\r\n    {\r\n        int kCircularTextureCount = 20;\r\n        struct Task\r\n        {\r\n            string texFilename;\r\n        };\r\n\r\n        static ConcurrentCircularBuffer<Task> tasks(kCircularTextureCount);\r\n        static unique_ptr<thread> textureLoader;\r\n\r\n        auto _format = format;\r\n        _format.setLabel(relativeName);\r\n        auto loader = [=](const string & absoluteName, const string&) -> shared_ptr < T >\r\n        {\r\n            if (absoluteName == \"checkerboard\")\r\n            {\r\n                auto source = ip::checkerboard(2048, 2048);\r\n                return T::create(source, _format);\r\n            }\r\n            if (!fs::exists(absoluteName))\r\n            {\r\n                CI_LOG_E(\"Missing file: \" << absoluteName);\r\n                auto source = ip::checkerboard(512, 512);\r\n                return T::create(source, _format);\r\n            }\r\n\r\n            auto ext = fs::path(absoluteName).extension().string();\r\n            std::transform(ext.begin(), ext.end(), ext.begin(), static_cast<int(*)(int)>(tolower));\r\n#if !defined( CINDER_GL_ES ) || defined( CINDER_GL_ANGLE )\r\n            if (ext == \".dds\")\r\n            {\r\n                auto source = DataSourcePath::create(absoluteName);\r\n                return T::createFromDds(source, _format);\r\n            }\r\n#endif\r\n            if (ext == \".ktx\")\r\n            {\r\n                auto source = DataSourcePath::create(absoluteName);\r\n                return T::createFromKtx(source, _format);\r\n            }\r\n            auto source = loadImage(absoluteName);\r\n            return T::create(source, _format);\r\n        };\r\n\r\n        // TODO: use call_once\r\n        if (isAsync)\r\n        {\r\n            if (!textureLoader)\r\n            {\r\n                gl::ContextRef backgroundCtx = gl::Context::create(gl::context());\r\n\r\n                auto fn = [=](gl::ContextRef context) {\r\n                    context->makeCurrent();\r\n                    while (!sShouldQuit)\r\n                    {\r\n                        Task task;\r\n                        if (tasks.tryPopBack(&task))\r\n                        {\r\n                            auto newTex = loader(task.texFilename, \"\");\r\n\r\n                            // we need to wait on a fence before alerting the primary thread that the Texture is ready\r\n                            auto fence = gl::Sync::create();\r\n                            fence->clientWaitSync();\r\n\r\n                            texture<T>(task.texFilename, format, true) = newTex;\r\n                        }\r\n                    }\r\n                };\r\n                textureLoader = unique_ptr<thread>(new thread(bind(fn, backgroundCtx)));\r\n\r\n                App::get()->getSignalCleanup().connect([] {\r\n                    textureLoader->join();\r\n                });\r\n            }\r\n\r\n            auto fakeLoader = [=](const string & absoluteName, const string&) -> shared_ptr < T > {\r\n                static auto placeholder = ip::checkerboard(64, 64);\r\n                static auto tex = T::create(placeholder, _format);\r\n                tasks.pushFront({ absoluteName });\r\n\r\n                return tex;\r\n            };\r\n\r\n            return getAssetResource<shared_ptr<T>>(relativeName, fakeLoader);\r\n        }\r\n\r\n        return getAssetResource<shared_ptr<T>>(relativeName, loader);\r\n    }\r\n\r\n#if ! defined( CINDER_GL_ES )\r\n    //gl::Texture1dRef& texture1d(const std::string& relativeName, const gl::Texture1d::Format& format, bool isAsync)\r\n    //{\r\n    //    return texture<gl::Texture1d>(relativeName, format, isAsync);\r\n    //}\r\n#endif\r\n\r\n    gl::Texture2dRef& texture2d(const std::string& relativeName, const gl::Texture2d::Format& format, bool isAsync)\r\n    {\r\n        return texture<gl::Texture2d>(relativeName, format, isAsync);\r\n    }\r\n\r\n#if TEXTURE_3D_ENABLED\r\n    gl::Texture3dRef& texture3d(const std::string& relativeName, const gl::Texture3d::Format& format, bool isAsync)\r\n    {\r\n        return texture<gl::Texture3d>(relativeName, format, isAsync);\r\n    }\r\n#endif\r\n\r\n    gl::TextureCubeMapRef& textureCubeMap(const std::string& relativeName, const gl::TextureCubeMap::Format& format, bool isAsync)\r\n    {\r\n        return texture<gl::TextureCubeMap>(relativeName, format, isAsync);\r\n    }\r\n\r\n    TriMeshRef& triMesh(const string& objFileName, const std::string& mtlFileName)\r\n    {\r\n        auto loader = [](const string & absObjFileName, const string& absMtlFileName) -> TriMeshRef\r\n        {\r\n#define ENTRY(name)  if (absObjFileName == #name) return TriMesh::create(geom::name());\r\n            ENTRY(Rect);\r\n            ENTRY(RoundedRect);\r\n            ENTRY(Cube);\r\n            ENTRY(Icosahedron);\r\n            ENTRY(Icosphere);\r\n            ENTRY(Teapot);\r\n            ENTRY(Circle);\r\n            ENTRY(Ring);\r\n            ENTRY(Sphere);\r\n            ENTRY(Capsule);\r\n            ENTRY(Torus);\r\n            ENTRY(TorusKnot);\r\n            ENTRY(Cylinder);\r\n            ENTRY(Plane);\r\n            ENTRY(WireCapsule);\r\n            ENTRY(WireCircle);\r\n            ENTRY(WireRoundedRect);\r\n            ENTRY(WireCube);\r\n            ENTRY(WireCylinder);\r\n            ENTRY(WireCone);\r\n            ENTRY(WireIcosahedron);\r\n            ENTRY(WirePlane);\r\n            ENTRY(WireSphere);\r\n            ENTRY(WireTorus);\r\n#undef ENTRY\r\n            auto source = DataSourcePath::create(absObjFileName);\r\n            auto ext = fs::path(absObjFileName).extension().string();\r\n            TriMeshRef mesh;\r\n\r\n            std::transform(ext.begin(), ext.end(), ext.begin(), static_cast<int(*)(int)>(tolower));\r\n            if (ext == \".obj\")\r\n            {\r\n                if (absMtlFileName.empty())\r\n                {\r\n                    ObjLoader loader(source);\r\n                    mesh = TriMesh::create(loader);\r\n                }\r\n                else\r\n                {\r\n                    auto mtlSource = DataSourcePath::create(absMtlFileName);\r\n                    ObjLoader loader(source, mtlSource);\r\n                    mesh = TriMesh::create(loader);\r\n                }\r\n            }\r\n            else if (ext == \".msh\")\r\n            {\r\n                mesh = TriMesh::create();\r\n                mesh->read(source);\r\n            }\r\n            else\r\n            {\r\n                CI_LOG_E(\"Unsupported mesh format: \" << absObjFileName);\r\n                return nullptr;\r\n            }\r\n\r\n            if (!mesh->hasNormals()) {\r\n                mesh->recalculateNormals();\r\n            }\r\n\r\n            if (!mesh->hasTangents()) {\r\n                mesh->recalculateTangents();\r\n            }\r\n\r\n            return mesh;\r\n        };\r\n        return getAssetResource<TriMeshRef>(objFileName, loader, mtlFileName);\r\n    }\r\n\r\n    gl::VboMeshRef& vboMesh(const string& objFileName, const string& mtlFileName)\r\n    {\r\n        auto tri = triMesh(objFileName, mtlFileName);\r\n        auto loader = [&tri](const string & absoluteName, const string&) -> gl::VboMeshRef\r\n        {\r\n            return gl::VboMesh::create(*tri);\r\n        };\r\n\r\n        return getAssetResource<gl::VboMeshRef>(objFileName, loader, mtlFileName);\r\n    }\r\n\r\n    gl::GlslProgRef& glslProg(const string& vsFileName, const string& fsFileName, gl::GlslProg::Format format)\r\n    {\r\n        auto label = fs::path(vsFileName).filename().string() + \"/\" + fs::path(fsFileName).filename().string();\r\n        auto loader = [=, &format](const string & vsAbsoluteName, const string & fsAbsoluteName) -> gl::GlslProgRef\r\n        {\r\n            if (vsAbsoluteName == fsAbsoluteName || fsAbsoluteName.empty())\r\n            {\r\n                // Assume it's a stock shader\r\n                auto def = gl::ShaderDef();\r\n                bool isStockShader = false;\r\n                if (vsAbsoluteName.find(\"passthrough\") != string::npos) {\r\n                    isStockShader = true;\r\n                }\r\n                if (vsAbsoluteName.find(\"texture\") != string::npos) {\r\n                    isStockShader = true; def = def.texture();\r\n                }\r\n                if (vsAbsoluteName.find(\"color\") != string::npos) {\r\n                    isStockShader = true;  def = def.color();\r\n                }\r\n                if (vsAbsoluteName.find(\"lambert\") != string::npos) {\r\n                    isStockShader = true; def = def.lambert();\r\n                }\r\n                if (vsAbsoluteName.find(\"uniform\") != string::npos) {\r\n                    isStockShader = true; def = def.uniformBasedPosAndTexCoord();\r\n                }\r\n\r\n                if (isStockShader)\r\n                    return gl::getStockShader(def);\r\n            }\r\n\r\n#if defined( CINDER_GL_ES )\r\n            format.version(300); // es 3.0\r\n#else\r\n            format.version(150); // gl 3.2\r\n#endif\r\n            if (!vsAbsoluteName.empty())\r\n                format.vertex(DataSourcePath::create(vsAbsoluteName));\r\n            if (!fsAbsoluteName.empty())\r\n                format.fragment(DataSourcePath::create(fsAbsoluteName));\r\n            format.setLabel(label);\r\n\r\n            return gl::GlslProg::create(format);\r\n        };\r\n\r\n        return getAssetResource<gl::GlslProgRef>(vsFileName, loader, fsFileName);\r\n    }\r\n\r\n    string& str(const string& relativeName)\r\n    {\r\n        auto loader = [](const string & absoluteName, const string&) -> string\r\n        {\r\n            return loadString(DataSourcePath::create(absoluteName));\r\n        };\r\n        return getAssetResource<string>(relativeName, loader);\r\n    }\r\n\r\n    static vector<string> loadPaths(const string& absoluteFolderName, const string&, bool isLongMode)\r\n    {\r\n        vector<string> files;\r\n        fs::directory_iterator kEnd;\r\n        for (fs::directory_iterator it(absoluteFolderName); it != kEnd; ++it)\r\n        {\r\n            if (fs::is_regular_file(*it) && it->path().extension() != \".db\"\r\n                && it->path().extension() != \".DS_Store\")\r\n            {\r\n#ifndef NDEBUG\r\n                //console() << it->path() << endl;\r\n#endif\r\n                files.push_back(isLongMode ?\r\n                    it->path().string() :\r\n                    it->path().filename().string());\r\n            }\r\n        }\r\n        return files;\r\n    }\r\n\r\n    vector<string>& longPaths(const string& relativeFolderName)\r\n    {\r\n        return getAssetResource<vector<string>>(relativeFolderName, bind(loadPaths, placeholders::_1, placeholders::_2, true));\r\n    }\r\n\r\n    vector<string>& shortPaths(const string& relativeFolderName)\r\n    {\r\n        return getAssetResource<vector<string>>(relativeFolderName, bind(loadPaths, placeholders::_1, placeholders::_2, false));\r\n    }\r\n\r\n    audio::VoiceRef& voice(const string& relativeName)\r\n    {\r\n#if defined(CINDER_MSW)\r\n        auto loader = [](const string & absoluteName, const string&) -> audio::VoiceRef\r\n        {\r\n            auto source = audio::load(DataSourcePath::create(absoluteName));\r\n            return audio::Voice::create(source);\r\n        };\r\n        return getAssetResource<audio::VoiceRef>(relativeName, loader);\r\n#else\r\n        throw audio::AudioExc(\"ci::audio is unsupported\");\r\n#endif\r\n    }\r\n\r\n}\r\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/src/MiniConfig.cpp",
    "content": "#include \"../include/MiniConfig.h\"\r\n#include <cinder/Xml.h>\r\n#include <cinder/gl/wrapper.h>\r\n#include <cinder/Utilities.h>\r\n#include <cinder/app/App.h>\r\n#include <cinder/params/Params.h>\r\n\r\n#ifndef CINDER_COCOA_TOUCH\r\n#include <cinder/ImageIo.h>\r\n#endif\r\n\r\nusing namespace ci;\r\nusing namespace ci::app;\r\nusing namespace std;\r\n\r\n#define GROUP_DEF(grp)\r\n#define ITEM_DEF(type, var, default) type var = default;\r\n#define ITEM_DEF_MINMAX(type, var, default, Min, Max) ITEM_DEF(type, var, default);\r\n#include ITEM_DEF_FILE\r\n#undef ITEM_DEF_MINMAX\r\n#undef ITEM_DEF\r\n#undef GROUP_DEF\r\n\r\nvoid readConfig()\r\n{\r\n    fs::path configPath = app::getAppPath() / CONFIG_XML;\r\n    XmlTree tree;\r\n    try\r\n    {\r\n        tree = XmlTree(loadFile(configPath));\r\n    }\r\n    catch (exception& e)\r\n    {\r\n        console() << e.what() << endl;\r\n        console() << \"[Warning] Fails to read from \" << configPath.string() << endl;\r\n        writeConfig();\r\n        return;\r\n    }\r\n    XmlTree group;\r\n\r\n#define GROUP_DEF(grp) try {group = tree.getChild(#grp);} catch (exception& e) {}\r\n#define ITEM_DEF(type, var, default)                        \\\r\n    try                                                      \\\r\n    {                                                       \\\r\n        if (group.getTag().empty())                         \\\r\n            var = tree.getChild(#var).getValue<type>();     \\\r\n        else                                                \\\r\n            var = group.getChild(#var).getValue<type>();    \\\r\n    }                                                       \\\r\n    catch (exception& e)                                    \\\r\n    {                                                       \\\r\n        console() << e.what() << endl;                      \\\r\n    }\r\n\r\n#define ITEM_DEF_MINMAX(type, var, default, Min, Max) ITEM_DEF(type, var, default);\r\n#include \"item.def\"\r\n#undef ITEM_DEF_MINMAX\r\n#undef ITEM_DEF\r\n#undef GROUP_DEF\r\n    console() << \"Reads from \" << configPath.string() << endl;\r\n}\r\n\r\nvoid writeConfig()\r\n{\r\n#ifdef CINDER_COCOA_TOUCH\r\n    // TODO: how to enable writing in iOS?\r\n    return;\r\n#endif\r\n\r\n    fs::path configPath = app::getAppPath() / CONFIG_XML;\r\n    try\r\n    {\r\n        XmlTree tree = XmlTree::createDoc();\r\n        XmlTree group;\r\n\r\n#define GROUP_DEF(grp)                                          \\\r\n        do                                                      \\\r\n        {                                                       \\\r\n            if (!group.getTag().empty()) tree.push_back(group); \\\r\n            group = XmlTree(#grp, \"\");                          \\\r\n        } while (0);\r\n\r\n#define ITEM_DEF(type, var, default)                            \\\r\n        do                                                      \\\r\n        {                                                       \\\r\n            XmlTree item(#var, toString(var));                  \\\r\n            if (group.getTag().empty()) tree.push_back(item);   \\\r\n            else group.push_back(item);                         \\\r\n        } while (0);\r\n#define ITEM_DEF_MINMAX(type, var, default, Min, Max) ITEM_DEF(type, var, default);\r\n#include ITEM_DEF_FILE\r\n#undef ITEM_DEF_MINMAX\r\n#undef ITEM_DEF\r\n#undef GROUP_DEF\r\n        if (!group.getTag().empty()) tree.push_back(group);\r\n\r\n#ifdef CHINESE_GBK_ENCODING_ENABLED\r\n        // OStreamRef os = writeFile(configPath)->getStream();\r\n        ofstream of(configPath.string().c_str());\r\n        const string kGbkHeader = \"<?xml version=\\\"1.0\\\" encoding=\\\"gbk\\\"?>\";\r\n        of << kGbkHeader << endl << tree;\r\n#else\r\n        tree.write( writeFile(configPath));\r\n#endif\r\n        console() << \"Writes to \" << configPath.string() <<endl;\r\n    }\r\n    catch( ... ) {\r\n        console() << \"[Warning] Fails to write to \" << configPath.string() <<endl;\r\n    }\r\n}\r\n\r\nvoid revertToDefaultValues()\r\n{\r\n#define GROUP_DEF(grp)\r\n#define ITEM_DEF(type, var, default) var = default;\r\n#define ITEM_DEF_MINMAX(type, var, default, Min, Max) ITEM_DEF(type, var, default);\r\n#include ITEM_DEF_FILE\r\n#undef ITEM_DEF_MINMAX\r\n#undef ITEM_DEF\r\n#undef GROUP_DEF\r\n    console() << \"MiniConfig reverted to default values\" << endl;\r\n}\r\n\r\nnamespace\r\n{\r\n    const int kPODItemHeight = 16;\r\n    template <typename T>\r\n    int getItemHeight(const T&)\r\n    {\r\n        return kPODItemHeight;\r\n    }\r\n\r\n    template <>\r\n    int getItemHeight(const quat&)\r\n    {\r\n        return 80;\r\n    }\r\n\r\n    template <>\r\n    int getItemHeight(const vec3&)\r\n    {\r\n        return 120;\r\n    }\r\n\r\n    template <>\r\n    int getItemHeight(const Color&)\r\n    {\r\n        return 80;\r\n    }\r\n\r\n    template <>\r\n    int getItemHeight(const ColorA&)\r\n    {\r\n        return 80;\r\n    }\r\n\r\n    int getConfigUIHeight()\r\n    {\r\n        int height = kPODItemHeight * 4; // top + bottom\r\n\r\n    #define GROUP_DEF(grp)                  height += kPODItemHeight;\r\n    #define ITEM_DEF(type, var, default)    height += getItemHeight(var);\r\n    #define ITEM_DEF_MINMAX(type, var, default, Min, Max) ITEM_DEF(type, var, default);\r\n    #include ITEM_DEF_FILE\r\n    #undef ITEM_DEF_MINMAX\r\n    #undef ITEM_DEF\r\n    #undef GROUP_DEF\r\n\r\n        return height;\r\n    }\r\n}\r\n\r\nvoid takeScreenShot()\r\n{\r\n    auto windowSurf = copyWindowSurface();\r\n#ifdef CINDER_COCOA_TOUCH\r\n    cocoa::writeToSavedPhotosAlbum(windowSurf);\r\n#else\r\n    fs::path writePath = getAppPath() / (\"screenshot_\" + toString(getElapsedFrames()) + \".png\");\r\n    writeImage(writePath, windowSurf);\r\n#endif\r\n}\r\n\r\nshared_ptr<params::InterfaceGl> createConfigUI(const ivec2& size)\r\n{\r\n#if defined(CINDER_MSW_DESKTOP) || defined(CINDER_LINUX) || defined(CINDER_MAC)\r\n    ivec2 newsize = {size.x, max(size.y, getConfigUIHeight()) };\r\n    \r\n    auto params = params::InterfaceGl::create(\"MiniConfig.xml\", newsize);\r\n    params->addButton(\"SAVE\", writeConfig);\r\n    params->addButton(\"PROFILER\", [] {\r\n        launchWebBrowser(Url(getAssetPath(\"vis/index.html\").string(), true));\r\n        });\r\n    params->addButton(\"SCREENSHOT\", takeScreenShot);\r\n    params->addButton(\"QUIT\", []{App::get()->quit(); });\r\n    params->setOptions(\"\", \"valueswidth=fit\");\r\n    params->addSeparator();\r\n    string groupName = \"Config\";\r\n#define GROUP_DEF(grp)                  groupName = #grp;\r\n#define ITEM_DEF(type, var, default)    params->addParam(#var, &var, #var[0] == '_').group(groupName);\r\n#define ITEM_DEF_MINMAX(type, var, default, Min, Max)       \\\r\ndo                                                          \\\r\n{                                                           \\\r\ntype step = (Max - Min) / (type)500;                        \\\r\nparams->addParam(#var, &var).min(Min).max(Max).step(step).group(groupName);  \\\r\n} while(0);\r\n#include ITEM_DEF_FILE\r\n#undef ITEM_DEF_MINMAX\r\n#undef ITEM_DEF\r\n#undef GROUP_DEF\r\n    params->addSeparator();\r\n    \r\n    getWindow()->getSignalPostDraw().connect([params] {\r\n#if defined( CINDER_MSW_DESKTOP )\r\n        gl::pushDebugGroup(\"MiniConfig::UI\");\r\n#endif\r\n        params->draw();\r\n#if defined( CINDER_MSW_DESKTOP )\r\n        gl::popDebugGroup();\r\n#endif\r\n    });\r\n    \r\n    return params;\r\n#else\r\n    return nullptr;\r\n#endif\r\n}\r\n\r\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/templates/DepthSensor VNM/assets/shader.frag",
    "content": "uniform sampler2D uTex0;\r\nuniform sampler2D uTex1;\r\nuniform sampler2D uTex2;\r\nuniform sampler2D uTex3;\r\n\r\nin lowp vec4     Color;\r\nin highp vec3     Normal;\r\nin highp vec2     TexCoord;\r\n\r\nout highp vec4    oColor;\r\n\r\nvoid main( void )\r\n{\r\n    oColor = texture( uTex0, TexCoord.st ) * Color;\r\n}\r\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/templates/DepthSensor VNM/assets/shader.vert",
    "content": "uniform mat4    ciModelViewProjection;\r\nuniform mat3    ciNormalMatrix;\r\n\r\nin vec4     ciPosition;\r\nin vec2     ciTexCoord0;\r\nin vec3     ciNormal;\r\nin vec4     ciColor;\r\n\r\nout highp vec2  TexCoord;\r\nout lowp vec4   Color;\r\nout highp vec3  Normal;\r\n\r\nvoid main( void )\r\n{\r\n    gl_Position = ciModelViewProjection * ciPosition;\r\n    Color       = ciColor;\r\n    TexCoord    = ciTexCoord0;\r\n    Normal      = ciNormalMatrix * ciNormal;\r\n}\r\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/templates/DepthSensor VNM/include/item.def",
    "content": "ITEM_DEF(int, APP_WIDTH, 1024)\r\nITEM_DEF(int, APP_HEIGHT, 768)\r\nITEM_DEF(int, SENSOR_TYPE, 0)"
  },
  {
    "path": "3rdparty/Cinder-VNM/templates/DepthSensor VNM/src/_TBOX_PREFIX_App.cpp",
    "content": "#include \"cinder/app/App.h\"\n#include \"cinder/app/RendererGl.h\"\n#include \"cinder/gl/gl.h\"\n#include \"cinder/CameraUi.h\"\n#include \"cinder/Log.h\"\n\n#include \"AssetManager.h\"\n#include \"MiniConfigImgui.h\"\n#include \"DepthSensor.h\"\n\nusing namespace ci;\nusing namespace ci::app;\nusing namespace std;\n\nstruct _TBOX_PREFIX_App : public App\n{\n    void setup() override\n    {\n        const auto& args = getCommandLineArgs();\n        log::makeLogger<log::LoggerFileRotating>(fs::path(), \"app.%Y.%m.%d.log\");\n\n        ds::DeviceType type = (ds::DeviceType)SENSOR_TYPE;\n        ds::Option option;\n        option.enableColor = true;\n        mDevice = ds::Device::create(type, option);\n        if (!mDevice->isValid())\n        {\n            quit();\n            return;\n        }\n\n        mDevice->signalDepthDirty.connect([&]{\n            mDepthChannel = mDevice->depthChannel.clone();\n        });\n\n        mCamUi = CameraUi( &mCam, getWindow(), -1 );\n\n        createConfigImgui();\n        gl::enableDepth();\n\n        getWindow()->getSignalResize().connect([&] {\n            APP_WIDTH = getWindowWidth();\n            APP_HEIGHT = getWindowHeight();\n            mCam.setAspectRatio( getWindowAspectRatio() );\n        });\n\n        getSignalCleanup().connect([&] { writeConfig(); });\n\n        getWindow()->getSignalKeyUp().connect([&](KeyEvent& event) {\n            if (event.getCode() == KeyEvent::KEY_ESCAPE) quit();\n        });\n        \n        //mGlslProg = am::glslProg(VS_NAME, FS_NAME);\n        //mGlslProg->uniform(\"uTex0\", 0);\n\n        getWindow()->getSignalDraw().connect([&] {\n            gl::setMatrices( mCam );\n            gl::clear();\n        });\n    }\n    \n    CameraPersp         mCam;\n    CameraUi            mCamUi;\n    Channel16u          mDepthChannel;\n    gl::GlslProgRef     mGlslProg;\n    ds::DeviceRef       mDevice;\n};\n\nCINDER_APP( _TBOX_PREFIX_App, RendererGl, [](App::Settings* settings) {\n    readConfig();\n    settings->setWindowSize(APP_WIDTH, APP_HEIGHT);\n    settings->setMultiTouchEnabled(false);\n} )\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/templates/DepthSensor VNM/template.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<cinder>\n<template name=\"VNM: DepthSensor\" parent=\"org.libcinder.apptemplates.basicopengl\">\n    <requires>org.jing.vnm</requires>\n\t<requires>org.vnm.depthsensor</requires>\n\t<header replaceContents=\"true\" isResourceHeader=\"true\">include/item.def</header>\n\t<source replaceContents=\"true\" replaceName=\"true\">src/_TBOX_PREFIX_App.cpp</source>\n</template>\n</cinder>"
  },
  {
    "path": "3rdparty/Cinder-VNM/templates/Melo Scene/include/item.def",
    "content": "ITEM_DEF(int, APP_WIDTH, 1024)\r\nITEM_DEF(int, APP_HEIGHT, 768)\r\nITEM_DEF(string, MESH_NAME, \"Teapot\")\r\nITEM_DEF(string, TEX0_NAME, \"checkerboard\")\r\nITEM_DEF(string, TEX1_NAME, \"checkerboard\")\r\nITEM_DEF(string, TEX2_NAME, \"checkerboard\")\r\nITEM_DEF(string, TEX3_NAME, \"checkerboard\")\r\nITEM_DEF(string, VS_NAME, \"texture\")\r\nITEM_DEF(string, FS_NAME, \"texture\")\r\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/templates/Melo Scene/src/_TBOX_PREFIX_App.cpp",
    "content": "#include \"cinder/app/App.h\"\n#include \"cinder/app/RendererGl.h\"\n#include \"cinder/gl/gl.h\"\n#include \"cinder/CameraUi.h\"\n#include \"cinder/Log.h\"\n\n#include \"AssetManager.h\"\n#include \"MiniConfigImgui.h\"\n\n#include \"melo.h\"\n\nusing namespace ci;\nusing namespace ci::app;\nusing namespace std;\n\nstruct _TBOX_PREFIX_App : public App\n{\n    void setup() override\n    {\n        log::makeLogger<log::LoggerFileRotating>(fs::path(), \"app.%Y.%m.%d.log\");\n\n        mCam.setNearClip(1);\n        mCam.setFarClip(10000);\n        mCamUi = CameraUi(&mCam, getWindow(), -1);\n\n        createConfigImgui();\n        gl::enableDepth();\n\n        getWindow()->getSignalResize().connect([&] {\n            APP_WIDTH = getWindowWidth();\n            APP_HEIGHT = getWindowHeight();\n            mCam.setAspectRatio(getWindowAspectRatio());\n        });\n\n        getSignalCleanup().connect([&] { writeConfig(); });\n\n        getWindow()->getSignalKeyUp().connect([&](KeyEvent &event) {\n            if (event.getCode() == KeyEvent::KEY_ESCAPE)\n                quit();\n        });\n\n        {\n            mRoot = melo::createRootNode();\n            auto grid = melo::createGridNode();\n            mRoot->addChild(grid);\n\n            auto gltf = melo::createMeshNode(MESH_NAME);\n            mRoot->addChild(gltf);\n        }\n\n        getSignalUpdate().connect([&] {\n            mRoot->treeUpdate();\n\n            for (auto& child : mRoot->getChildren())\n            {\n                //mModel->flipV = FLIP_V;\n                child->cameraPosition = mCam.getEyePoint();\n            }\n        });\n\n        getWindow()->getSignalDraw().connect([&] {\n            gl::setMatrices(mCam);\n            gl::clear();\n\n            mRoot->treeDraw();\n        });\n    }\n\n    CameraPersp mCam;\n    CameraUi mCamUi;\n    gl::GlslProgRef mGlslProg;\n    melo::NodeRef mRoot;\n};\n\nCINDER_APP(_TBOX_PREFIX_App, RendererGl, [](App::Settings *settings) {\n    readConfig();\n    settings->setWindowSize(APP_WIDTH, APP_HEIGHT);\n    settings->setMultiTouchEnabled(false);\n})\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/templates/Melo Scene/template.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<cinder>\n<template name=\"VNM: Melo Scene\" parent=\"org.libcinder.apptemplates.basicopengl\">\n\t<requires>org.jing.vnm</requires>\n\t<requires>jing.melo</requires>\n\t<header replaceContents=\"true\" isResourceHeader=\"true\">include/item.def</header>\n\t<source replaceContents=\"true\" replaceName=\"true\">src/_TBOX_PREFIX_App.cpp</source>\n</template>\n</cinder>"
  },
  {
    "path": "3rdparty/Cinder-VNM/templates/Minimalist VNM/assets/shader.frag",
    "content": "uniform sampler2D uTex0;\r\nuniform sampler2D uTex1;\r\nuniform sampler2D uTex2;\r\nuniform sampler2D uTex3;\r\n\r\nin lowp vec4     Color;\r\nin highp vec3     Normal;\r\nin highp vec2     TexCoord;\r\n\r\nout highp vec4    oColor;\r\n\r\nvoid main( void )\r\n{\r\n    oColor = texture( uTex0, TexCoord.st ) * Color;\r\n}\r\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/templates/Minimalist VNM/assets/shader.vert",
    "content": "uniform mat4    ciModelViewProjection;\r\nuniform mat3    ciNormalMatrix;\r\n\r\nin vec4     ciPosition;\r\nin vec2     ciTexCoord0;\r\nin vec3     ciNormal;\r\nin vec4     ciColor;\r\n\r\nout highp vec2  TexCoord;\r\nout lowp vec4   Color;\r\nout highp vec3  Normal;\r\n\r\nvoid main( void )\r\n{\r\n    gl_Position = ciModelViewProjection * ciPosition;\r\n    Color       = ciColor;\r\n    TexCoord    = ciTexCoord0;\r\n    Normal      = ciNormalMatrix * ciNormal;\r\n}\r\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/templates/Minimalist VNM/include/item.def",
    "content": "ITEM_DEF(int, APP_WIDTH, 1024)\r\nITEM_DEF(int, APP_HEIGHT, 768)\r\nITEM_DEF(string, MESH_NAME, \"Teapot\")\r\nITEM_DEF(string, TEX0_NAME, \"checkerboard\")\r\nITEM_DEF(string, TEX1_NAME, \"checkerboard\")\r\nITEM_DEF(string, TEX2_NAME, \"checkerboard\")\r\nITEM_DEF(string, TEX3_NAME, \"checkerboard\")\r\nITEM_DEF(string, VS_NAME, \"texture\")\r\nITEM_DEF(string, FS_NAME, \"texture\")\r\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/templates/Minimalist VNM/src/_TBOX_PREFIX_App.cpp",
    "content": "#include \"cinder/app/App.h\"\n#include \"cinder/app/RendererGl.h\"\n#include \"cinder/gl/gl.h\"\n#include \"cinder/CameraUi.h\"\n#include \"cinder/Log.h\"\n\n#include \"AssetManager.h\"\n#include \"MiniConfigImgui.h\"\n\nusing namespace ci;\nusing namespace ci::app;\nusing namespace std;\n\nstruct _TBOX_PREFIX_App : public App\n{\n    void setup() override\n    {\n        log::makeLogger<log::LoggerFileRotating>(fs::path(), \"app.%Y.%m.%d.log\");\n        \n        auto aabb = am::triMesh(MESH_NAME)->calcBoundingBox();\n        mCam.lookAt(aabb.getMax() * 2.0f, aabb.getCenter());\n        mCamUi = CameraUi( &mCam, getWindow(), -1 );\n\n        createConfigImgui();\n        gl::enableDepth();\n\n        getWindow()->getSignalResize().connect([&] {\n            APP_WIDTH = getWindowWidth();\n            APP_HEIGHT = getWindowHeight();\n            mCam.setAspectRatio( getWindowAspectRatio() );\n        });\n\n        getSignalCleanup().connect([&] { writeConfig(); });\n\n        getWindow()->getSignalKeyUp().connect([&](KeyEvent& event) {\n            if (event.getCode() == KeyEvent::KEY_ESCAPE) quit();\n        });\n\n        getSignalUpdate().connect([&] {\n        });\n\n        mGlslProg = am::glslProg(VS_NAME, FS_NAME);\n        mGlslProg->uniform(\"uTex0\", 0);\n        mGlslProg->uniform(\"uTex1\", 1);\n        mGlslProg->uniform(\"uTex2\", 2);\n        mGlslProg->uniform(\"uTex3\", 3);\n\n        getWindow()->getSignalDraw().connect([&] {\n            gl::setMatrices( mCam );\n            gl::clear();\n        \n            gl::ScopedTextureBind tex0(am::texture2d(TEX0_NAME), 0);\n            gl::ScopedTextureBind tex1(am::texture2d(TEX1_NAME), 1);\n            gl::ScopedTextureBind tex2(am::texture2d(TEX2_NAME), 2);\n            gl::ScopedTextureBind tex3(am::texture2d(TEX3_NAME), 3);\n            gl::ScopedGlslProg glsl(mGlslProg);\n\n            gl::draw(am::vboMesh(MESH_NAME));\n        });\n    }\n    \n    CameraPersp         mCam;\n    CameraUi            mCamUi;\n    gl::GlslProgRef     mGlslProg;\n};\n\nCINDER_APP( _TBOX_PREFIX_App, RendererGl, [](App::Settings* settings) {\n    readConfig();\n    settings->setWindowSize(APP_WIDTH, APP_HEIGHT);\n    settings->setMultiTouchEnabled(false);\n} )\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/templates/Minimalist VNM/template.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<cinder>\n<template name=\"VNM: Minimalist\" parent=\"org.libcinder.apptemplates.basicopengl\">\n\t<requires>org.jing.vnm</requires>\n\t<header replaceContents=\"true\" isResourceHeader=\"true\">include/item.def</header>\n\t<source replaceContents=\"true\" replaceName=\"true\">src/_TBOX_PREFIX_App.cpp</source>\n</template>\n</cinder>"
  },
  {
    "path": "3rdparty/Cinder-VNM/templates/NonGame/include/item.def",
    "content": "ITEM_DEF(int, APP_WIDTH, 1024)\r\nITEM_DEF(int, APP_HEIGHT, 768)"
  },
  {
    "path": "3rdparty/Cinder-VNM/templates/NonGame/src/_TBOX_PREFIX_App.cpp",
    "content": "#include \"cinder/app/App.h\"\n#include \"cinder/app/RendererGl.h\"\n#include \"cinder/gl/gl.h\"\n#include \"cinder/Log.h\"\n\n#include \"AssetManager.h\"\n#include \"MiniConfigImgui.h\"\n\nusing namespace ci;\nusing namespace ci::app;\nusing namespace std;\n\nstruct _TBOX_PREFIX_App : public App\n{\n    void setup() override\n    {\n        log::makeLogger<log::LoggerFileRotating>(fs::path(), \"app.%Y.%m.%d.log\");\n        createConfigImgui();\n\n        getWindow()->getSignalKeyUp().connect([&](KeyEvent& event) {\n            if (event.getCode() == KeyEvent::KEY_ESCAPE) quit();\n        });\n\n        getWindow()->getSignalResize().connect([&]{\n            APP_WIDTH = getWindowWidth();\n            APP_HEIGHT = getWindowHeight();\n        });\n\n        getSignalUpdate().connect([&] {\n        });\n\n        getSignalCleanup().connect([&] { writeConfig(); });\n        \n        getWindow()->getSignalDraw().connect([&] {\n            gl::clear();\n        });\n    }\n};\n\nCINDER_APP( _TBOX_PREFIX_App, RendererGl, [](App::Settings* settings) {\n    readConfig();\n    settings->setWindowSize(APP_WIDTH, APP_HEIGHT);\n    settings->setMultiTouchEnabled(false);\n} )\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/templates/NonGame/template.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<cinder>\n<template name=\"VNM: NonGame\" parent=\"org.libcinder.apptemplates.basicopengl\">\n\t<requires>org.jing.vnm</requires>\n\t<header replaceContents=\"true\" isResourceHeader=\"true\">include/item.def</header>\n\t<source replaceContents=\"true\" replaceName=\"true\">src/_TBOX_PREFIX_App.cpp</source>\n</template>\n</cinder>"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/CinderGuizmo.cpp",
    "content": "#include \"CinderGuizmo.h\"\r\n#include \"cinder/app/KeyEvent.h\"\r\n#include \"imgui/imgui.h\"\r\n#ifndef IMGUI_DEFINE_MATH_OPERATORS\r\n#define IMGUI_DEFINE_MATH_OPERATORS\r\n#endif\r\n#include \"imgui/imgui_internal.h\"\r\n#include \"glm/gtc/type_ptr.hpp\"\r\n#include \"ImGuizmo/ImGuizmo.h\"\r\n\r\nusing namespace ci;\r\nusing namespace app;\r\n\r\nvoid ImGui::EnableGizmo(bool enable)\r\n{\r\n    ImGuizmo::Enable(enable);\r\n}\r\n\r\nbool ImGui::EditGizmo(const glm::mat4& cameraView, const glm::mat4& cameraProjection, glm::mat4* matrix)\r\n{\r\n    static ImGuizmo::OPERATION mCurrentGizmoOperation(ImGuizmo::TRANSLATE);\r\n    static ImGuizmo::MODE mCurrentGizmoMode(ImGuizmo::LOCAL);\r\n    static bool useSnap = false;\r\n    static float snap[3] = { 1.f, 1.f, 1.f };\r\n    static float bounds[] = { -0.5f, -0.5f, -0.5f, 0.5f, 0.5f, 0.5f };\r\n    static float boundsSnap[] = { 0.1f, 0.1f, 0.1f };\r\n    static bool boundSizing = false;\r\n    static bool boundSizingSnap = false;\r\n\r\n    ImGuizmo::BeginFrame();\r\n\r\n    if (ImGui::IsKeyPressed(KeyEvent::KEY_t))\r\n        mCurrentGizmoOperation = ImGuizmo::TRANSLATE;\r\n    if (ImGui::IsKeyPressed(KeyEvent::KEY_r))\r\n        mCurrentGizmoOperation = ImGuizmo::ROTATE;\r\n    if (ImGui::IsKeyPressed(KeyEvent::KEY_s))\r\n        mCurrentGizmoOperation = ImGuizmo::SCALE;\r\n    if (ImGui::RadioButton(\"Translate\", mCurrentGizmoOperation == ImGuizmo::TRANSLATE))\r\n        mCurrentGizmoOperation = ImGuizmo::TRANSLATE;\r\n    ImGui::SameLine();\r\n    if (ImGui::RadioButton(\"Rotate\", mCurrentGizmoOperation == ImGuizmo::ROTATE))\r\n        mCurrentGizmoOperation = ImGuizmo::ROTATE;\r\n    ImGui::SameLine();\r\n    if (ImGui::RadioButton(\"Scale\", mCurrentGizmoOperation == ImGuizmo::SCALE))\r\n        mCurrentGizmoOperation = ImGuizmo::SCALE;\r\n    float matrixTranslation[3], matrixRotation[3], matrixScale[3];\r\n    ImGuizmo::DecomposeMatrixToComponents(glm::value_ptr(*matrix), matrixTranslation, matrixRotation, matrixScale);\r\n    bool trsDirty = false;\r\n    trsDirty |= ImGui::InputFloat3(\"Tr\", matrixTranslation, 3);\r\n    trsDirty |= ImGui::InputFloat3(\"Rt\", matrixRotation, 3);\r\n    trsDirty |= ImGui::InputFloat3(\"Sc\", matrixScale, 3);\r\n    ImGuizmo::RecomposeMatrixFromComponents(matrixTranslation, matrixRotation, matrixScale, glm::value_ptr((*matrix)));\r\n\r\n    if (mCurrentGizmoOperation != ImGuizmo::SCALE)\r\n    {\r\n        if (ImGui::RadioButton(\"Local\", mCurrentGizmoMode == ImGuizmo::LOCAL))\r\n            mCurrentGizmoMode = ImGuizmo::LOCAL;\r\n        ImGui::SameLine();\r\n        if (ImGui::RadioButton(\"World\", mCurrentGizmoMode == ImGuizmo::WORLD))\r\n            mCurrentGizmoMode = ImGuizmo::WORLD;\r\n    }\r\n    if (ImGui::IsKeyPressed(KeyEvent::KEY_z))\r\n        useSnap = !useSnap;\r\n    ImGui::Checkbox(\"\", &useSnap);\r\n    ImGui::SameLine();\r\n\r\n    switch (mCurrentGizmoOperation)\r\n    {\r\n    case ImGuizmo::TRANSLATE:\r\n        ImGui::InputFloat3(\"Snap\", &snap[0]);\r\n        break;\r\n    case ImGuizmo::ROTATE:\r\n        ImGui::InputFloat(\"Angle Snap\", &snap[0]);\r\n        break;\r\n    case ImGuizmo::SCALE:\r\n        ImGui::InputFloat(\"Scale Snap\", &snap[0]);\r\n        break;\r\n    }\r\n    #if 0\r\n    ImGui::Checkbox(\"Bound Sizing\", &boundSizing);\r\n    if (boundSizing)\r\n    {\r\n        ImGui::PushID(3);\r\n        ImGui::Checkbox(\"\", &boundSizingSnap);\r\n        ImGui::SameLine();\r\n        ImGui::InputFloat3(\"Snap\", boundsSnap);\r\n        ImGui::PopID();\r\n    }\r\n    #endif\r\n\r\n    ImGuiIO& io = ImGui::GetIO();\r\n    ImGuizmo::SetRect(0, 0, io.DisplaySize.x, io.DisplaySize.y);\r\n    ImGuizmo::Manipulate(glm::value_ptr(cameraView), glm::value_ptr(cameraProjection), mCurrentGizmoOperation, mCurrentGizmoMode, glm::value_ptr(*matrix),\r\n    NULL, useSnap ? &snap[0] : NULL, boundSizing ? bounds : NULL, boundSizingSnap ? boundsSnap : NULL);\r\n\r\n    return trsDirty || ImGuizmo::IsUsing();\r\n}\r\n\r\nbool ImGui::ViewManipulate(glm::mat4& cameraView, float length, const glm::ivec2& position, const glm::ivec2& size, uint32_t backgroundColor)\r\n{\r\n    ImGuiIO& io = ImGui::GetIO();\r\n    auto position_ = ImVec2(position.x, position.y);\r\n    auto size_ = ImVec2(size.x, size.y);\r\n    bool isInside = ImRect(position_, position_ + size_).Contains(io.MousePos);\r\n\r\n    ImGuizmo::ViewManipulate(glm::value_ptr(cameraView), length, position_, size_, backgroundColor);\r\n\r\n    return isInside;\r\n}\r\n\r\nvoid ImGui::DecomposeMatrixToComponents(const glm::mat4& transform, glm::vec3& matrixTranslation, glm::vec3& matrixRotation, glm::vec3& matrixScale)\r\n{\r\n    ImGuizmo::DecomposeMatrixToComponents(glm::value_ptr(transform), glm::value_ptr(matrixTranslation), glm::value_ptr(matrixRotation), glm::value_ptr(matrixScale));\r\n}\r\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/CinderImGui.cpp",
    "content": "/*\n Cinder-ImGui\n This code is intended for use with Cinder\n and Omar Cornut ImGui C++ libraries.\n \n http://libcinder.org\n https://github.com/ocornut\n \n Copyright (c) 2013-2015, Simon Geilfus - All rights reserved.\n \n Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n the following conditions are met:\n \n * Redistributions of source code must retain the above copyright notice, this list of conditions and\n the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n the following disclaimer in the documentation and/or other materials provided with the distribution.\n \n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n POSSIBILITY OF SUCH DAMAGE.\n */\n\n// Linux fixes thanks to the help of @petros, see this thread:\n// https://forum.libcinder.org/#Topic/23286000002634083\n\n#include \"CinderImGui.h\"\n#define IMGUI_DEFINE_MATH_OPERATORS\n#define IMGUI_DEFINE_PLACEMENT_NEW\n#include \"imgui_internal.h\"\n\n#include \"cinder/app/App.h\"\n#include \"cinder/gl/scoped.h\"\n#include \"cinder/gl/draw.h\"\n#include \"cinder/gl/Context.h\"\n#include \"cinder/gl/Vao.h\"\n#include \"cinder/gl/Vbo.h\"\n#include \"cinder/gl/Texture.h\"\n#include \"cinder/gl/GlslProg.h\"\n#include \"cinder/Clipboard.h\"\n#include \"cinder/CinderAssert.h\"\n#include \"cinder/Log.h\"\n\nusing namespace std;\nusing namespace ci;\nusing namespace ci::app;\n\n\nnamespace ImGui {\n\n// static variables\nstatic bool sInitialized = false;\n\n\nImGui::Options::Options()\n: mWindow( ci::app::getWindow() ),\nmAutoRender( true ), mMergeFonts( true )\n{\n}\n\nImGui::Options& ImGui::Options::window( const ci::app::WindowRef &window )\n{\n\tmWindow = window;\n\treturn *this;\n}\nImGui::Options& ImGui::Options::autoRender( bool autoRender )\n{\n\tmAutoRender = autoRender;\n\treturn *this;\n}\n\nImGui::Options& ImGui::Options::font( const ci::fs::path &fontPath, float size )\n{\n\tmFonts = { { fontPath, size } };\n\treturn *this;\n}\nImGui::Options& ImGui::Options::fonts( const std::vector<std::pair<ci::fs::path,float>> &fonts, bool merge )\n{\n\tmFonts = fonts;\n\tmMergeFonts = merge;\n\treturn *this;\n}\nImGui::Options& ImGui::Options::fontGlyphRanges( const std::string &name, const vector<ImWchar> &glyphRanges )\n{\n\tmFontsGlyphRanges[name] = glyphRanges;\n\treturn *this;\n}\nImGui::Options& ImGui::Options::fontGlobalScale(float scale)\n{\n    ImGui::GetIO().FontGlobalScale = scale;\n    return *this;\n}\nImGui::Options& ImGui::Options::alpha( float a )\n{\n\tmStyle.Alpha = a;\n\treturn *this;\n}\nImGui::Options& ImGui::Options::windowPadding( const glm::vec2 &padding )\n{\n\tmStyle.WindowPadding = padding;\n\treturn *this;\n}\nImGui::Options& ImGui::Options::windowMinSize( const glm::vec2 &minSize )\n{\n\tmStyle.WindowMinSize = minSize;\n\treturn *this;\n}\nImGui::Options& ImGui::Options::windowRounding( float rounding )\n{\n\tmStyle.WindowRounding = rounding;\n\treturn *this;\n}\nImGui::Options& ImGui::Options::windowTitleAlign( const glm::vec2 &align )\n{\n\tmStyle.WindowTitleAlign = align;\n\treturn *this;\n}\nImGui::Options& ImGui::Options::childRounding( float rounding )\n{\n\tmStyle.ChildRounding = rounding;\n\treturn *this;\n}\n\nImGui::Options& ImGui::Options::framePadding( const glm::vec2 &padding )\n{\n\tmStyle.FramePadding = padding;\n\treturn *this;\n}\nImGui::Options& ImGui::Options::frameRounding( float rounding )\n{\n\tmStyle.FrameRounding = rounding;\n\treturn *this;\n}\nImGui::Options& ImGui::Options::itemSpacing( const glm::vec2 &spacing )\n{\n\tmStyle.ItemSpacing = spacing;\n\treturn *this;\n}\nImGui::Options& ImGui::Options::itemInnerSpacing( const glm::vec2 &spacing )\n{\n\tmStyle.ItemInnerSpacing = spacing;\n\treturn *this;\n}\nImGui::Options& ImGui::Options::touchExtraPadding( const glm::vec2 &padding )\n{\n\tmStyle.TouchExtraPadding = padding;\n\treturn *this;\n}\nImGui::Options& ImGui::Options::indentSpacing( float spacing )\n{\n\tmStyle.IndentSpacing = spacing;\n\treturn *this;\n}\nImGui::Options& ImGui::Options::columnsMinSpacing( float minSpacing )\n{\n\tmStyle.ColumnsMinSpacing = minSpacing;\n\treturn *this;\n}\nImGui::Options& ImGui::Options::scrollBarSize( float size )\n{\n\tmStyle.ScrollbarSize = size;\n\treturn *this;\n}\nImGui::Options& ImGui::Options::scrollbarRounding( float rounding )\n{\n\tmStyle.ScrollbarRounding = rounding;\n\treturn *this;\n}\nImGui::Options& ImGui::Options::grabMinSize( float minSize )\n{\n\tmStyle.GrabMinSize = minSize;\n\treturn *this;\n}\nImGui::Options& ImGui::Options::grabRounding( float rounding )\n{\n\tmStyle.GrabRounding = rounding;\n\treturn *this;\n}\nImGui::Options& ImGui::Options::buttonTextAlign( const ci::vec2 &textAlign )\n{\n\tmStyle.ButtonTextAlign = textAlign;\n\treturn *this;\n}\nImGui::Options& ImGui::Options::displayWindowPadding( const glm::vec2 &padding )\n{\n\tmStyle.DisplayWindowPadding = padding;\n\treturn *this;\n}\nImGui::Options& ImGui::Options::displaySafeAreaPadding( const glm::vec2 &padding )\n{\n\tmStyle.DisplaySafeAreaPadding = padding;\n\treturn *this;\n}\nImGui::Options& ImGui::Options::antiAliasedLines( bool antiAliasing )\n{\n\tmStyle.AntiAliasedLines = antiAliasing;\n\treturn *this;\n}\nImGui::Options& ImGui::Options::antiAliasedFill( bool antiAliasing )\n{\n\tmStyle.AntiAliasedFill = antiAliasing;\n\treturn *this;\n}\nImGui::Options& ImGui::Options::curveTessellationTol( float tessTolerance )\n{\n\tmStyle.CurveTessellationTol = tessTolerance;\n\treturn *this;\n}\nImGui::Options& ImGui::Options::iniPath( const ci::fs::path &path )\n{\n\tmIniPath = path;\n\treturn *this;\n}\n\nconst ImWchar* ImGui::Options::getFontGlyphRanges( const std::string &name ) const\n{\n\tif( mFontsGlyphRanges.count( name ) ) {\n\t\treturn &mFontsGlyphRanges.find(name)->second[0];\n\t}\n\telse return NULL;\n}\n\nImGui::Options& ImGui::Options::defaultTheme()\n{\n\tmStyle = ImGuiStyle();\n\t\n\treturn *this;\n}\n\nImGui::Options& ImGui::Options::darkTheme()\n{\n\tmStyle.WindowMinSize            = ImVec2( 160, 20 );\n\tmStyle.FramePadding             = ImVec2( 4, 2 );\n\tmStyle.ItemSpacing              = ImVec2( 6, 2 );\n\tmStyle.ItemInnerSpacing         = ImVec2( 6, 4 );\n\tmStyle.Alpha\t\t\t= 0.95f;\n\tmStyle.WindowRounding           = 4.0f;\n\tmStyle.FrameRounding            = 2.0f;\n\tmStyle.IndentSpacing            = 6.0f;\n\tmStyle.ItemInnerSpacing\t\t= ImVec2( 2, 4 );\n\tmStyle.ColumnsMinSpacing        = 50.0f;\n\tmStyle.GrabMinSize\t\t= 14.0f;\n\tmStyle.GrabRounding\t\t= 16.0f;\n\tmStyle.ScrollbarSize\t\t= 12.0f;\n\tmStyle.ScrollbarRounding\t= 16.0f;\n\t\n\tImGuiStyle& style = mStyle;\n\tstyle.Colors[ImGuiCol_Text]                  = ImVec4(0.86f, 0.93f, 0.89f, 0.78f);\n\tstyle.Colors[ImGuiCol_TextDisabled]          = ImVec4(0.86f, 0.93f, 0.89f, 0.28f);\n\tstyle.Colors[ImGuiCol_WindowBg]              = ImVec4(0.13f, 0.14f, 0.17f, 1.00f);\n\tstyle.Colors[ImGuiCol_Border]                = ImVec4(0.31f, 0.31f, 1.00f, 0.00f);\n\tstyle.Colors[ImGuiCol_BorderShadow]          = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);\n\tstyle.Colors[ImGuiCol_FrameBg]               = ImVec4(0.20f, 0.22f, 0.27f, 1.00f);\n\tstyle.Colors[ImGuiCol_FrameBgHovered]        = ImVec4(0.92f, 0.18f, 0.29f, 0.78f);\n\tstyle.Colors[ImGuiCol_FrameBgActive]         = ImVec4(0.92f, 0.18f, 0.29f, 1.00f);\n\tstyle.Colors[ImGuiCol_TitleBg]               = ImVec4(0.20f, 0.22f, 0.27f, 1.00f);\n\tstyle.Colors[ImGuiCol_TitleBgCollapsed]      = ImVec4(0.20f, 0.22f, 0.27f, 0.75f);\n\tstyle.Colors[ImGuiCol_TitleBgActive]         = ImVec4(0.92f, 0.18f, 0.29f, 1.00f);\n\tstyle.Colors[ImGuiCol_MenuBarBg]             = ImVec4(0.20f, 0.22f, 0.27f, 0.47f);\n\tstyle.Colors[ImGuiCol_ScrollbarBg]           = ImVec4(0.20f, 0.22f, 0.27f, 1.00f);\n\tstyle.Colors[ImGuiCol_ScrollbarGrab]         = ImVec4(0.09f, 0.15f, 0.16f, 1.00f);\n\tstyle.Colors[ImGuiCol_ScrollbarGrabHovered]  = ImVec4(0.92f, 0.18f, 0.29f, 0.78f);\n\tstyle.Colors[ImGuiCol_ScrollbarGrabActive]   = ImVec4(0.92f, 0.18f, 0.29f, 1.00f);\n\tstyle.Colors[ImGuiCol_CheckMark]             = ImVec4(0.71f, 0.22f, 0.27f, 1.00f);\n\tstyle.Colors[ImGuiCol_SliderGrab]            = ImVec4(0.47f, 0.77f, 0.83f, 0.14f);\n\tstyle.Colors[ImGuiCol_SliderGrabActive]      = ImVec4(0.92f, 0.18f, 0.29f, 1.00f);\n\tstyle.Colors[ImGuiCol_Button]                = ImVec4(0.47f, 0.77f, 0.83f, 0.14f);\n\tstyle.Colors[ImGuiCol_ButtonHovered]         = ImVec4(0.92f, 0.18f, 0.29f, 0.86f);\n\tstyle.Colors[ImGuiCol_ButtonActive]          = ImVec4(0.92f, 0.18f, 0.29f, 1.00f);\n\tstyle.Colors[ImGuiCol_Header]                = ImVec4(0.92f, 0.18f, 0.29f, 0.76f);\n\tstyle.Colors[ImGuiCol_HeaderHovered]         = ImVec4(0.92f, 0.18f, 0.29f, 0.86f);\n\tstyle.Colors[ImGuiCol_HeaderActive]          = ImVec4(0.92f, 0.18f, 0.29f, 1.00f);\n\tstyle.Colors[ImGuiCol_Separator]                = ImVec4(0.14f, 0.16f, 0.19f, 1.00f);\n\tstyle.Colors[ImGuiCol_SeparatorHovered]         = ImVec4(0.92f, 0.18f, 0.29f, 0.78f);\n\tstyle.Colors[ImGuiCol_SeparatorActive]          = ImVec4(0.92f, 0.18f, 0.29f, 1.00f);\n\tstyle.Colors[ImGuiCol_ResizeGrip]            = ImVec4(0.47f, 0.77f, 0.83f, 0.04f);\n\tstyle.Colors[ImGuiCol_ResizeGripHovered]     = ImVec4(0.92f, 0.18f, 0.29f, 0.78f);\n\tstyle.Colors[ImGuiCol_ResizeGripActive]      = ImVec4(0.92f, 0.18f, 0.29f, 1.00f);\n\tstyle.Colors[ImGuiCol_PlotLines]             = ImVec4(0.86f, 0.93f, 0.89f, 0.63f);\n\tstyle.Colors[ImGuiCol_PlotLinesHovered]      = ImVec4(0.92f, 0.18f, 0.29f, 1.00f);\n\tstyle.Colors[ImGuiCol_PlotHistogram]         = ImVec4(0.86f, 0.93f, 0.89f, 0.63f);\n\tstyle.Colors[ImGuiCol_PlotHistogramHovered]  = ImVec4(0.92f, 0.18f, 0.29f, 1.00f);\n\tstyle.Colors[ImGuiCol_TextSelectedBg]        = ImVec4(0.92f, 0.18f, 0.29f, 0.43f);\n\tstyle.Colors[ImGuiCol_PopupBg]\t\t\t\t = ImVec4(0.20f, 0.22f, 0.27f, 0.9f);\n\tstyle.Colors[ImGuiCol_ModalWindowDimBg]  = ImVec4(0.20f, 0.22f, 0.27f, 0.73f);\n\t\n\treturn *this;\n}\n\n\nImGui::Options& ImGui::Options::color( ImGuiCol option, const ci::ColorA &color )\n{\n\tmStyle.Colors[ option ] = color;\n\treturn *this;\n}\n\n//! cinder renderer\nclass Renderer {\npublic:\n\tRenderer();\n\t\n\t//! renders imgui drawlist\n\tvoid render( ImDrawData* draw_data );\n\t//! sets the font\n\tImFont* addFont( const ci::fs::path &font, float size, const ImWchar* glyph_ranges = NULL, bool merge = true );\n\t\n\t//! initializes and returns the font texture\n\tci::gl::Texture2dRef getFontTextureRef();\n\t//! initializes and returns the vao\n\tci::gl::VaoRef getVao();\n\t//! initializes and returns the vbo\n\tci::gl::VboRef getVbo();\n\t//! initializes and returns the shader\n\tci::gl::GlslProgRef getGlslProg();\n\t\n\t//! initializes the font texture\n\tvoid initFontTexture();\n\t//! initializes the vbo mesh\n\tvoid initBuffers( size_t size = 1000 );\n\t//! initializes the shader\n\tvoid initGlslProg();\n\t\n\tImFont* getFont( const std::string &name );\n\tvoid clearFonts();\n\t\nprotected:\n\tci::gl::Texture2dRef\tmFontTexture;\n\tci::gl::VaoRef\t\tmVao;\n\tci::gl::VboRef\t\tmVbo;\n\tci::gl::VboRef\t\tmIbo;\n\tci::gl::GlslProgRef\t\tmShader;\n\t\n\tmap<string,ImFont*>\t\tmFonts;\n\tvector<vector<ImWchar>>\tmFontsGlyphRanges;\n};\n\n\n\nRenderer::Renderer()\n{\n\tinitGlslProg();\n\tinitBuffers();\n}\n\n#define USE_MAP_BUFFER\n\n//! renders imgui drawlist\nvoid Renderer::render( ImDrawData* draw_data )\n{\n\tconst float width\t= ImGui::GetIO().DisplaySize.x;\n\tconst float height\t= ImGui::GetIO().DisplaySize.y;\n\tconst auto &vao\t\t= getVao();\n\tconst auto &vbo\t\t= getVbo();\n\tconst auto &shader\t= getGlslProg();\n\tauto ctx\t\t\t= gl::context();\n\t\n\tconst mat4 mat =\n\t{\n\t\t{ 2.0f/width,\t0.0f,\t\t0.0f,\t0.0f },\n\t\t{ 0.0f,\t\t2.0f/-height,\t0.0f,\t0.0f },\n\t\t{ 0.0f,\t\t0.0f,\t\t\t-1.0f,\t0.0f },\n\t\t{ -1.0f,\t1.0f,\t\t\t0.0f,\t1.0f },\n\t};\n\t\n\tgl::ScopedVao scopedVao( vao.get() );\n\tgl::ScopedBuffer scopedVbo( GL_ARRAY_BUFFER, vbo->getId() );\n\tgl::ScopedBuffer scopedIbo( GL_ELEMENT_ARRAY_BUFFER, mIbo->getId() );\n\tgl::ScopedGlslProg scopedShader( shader );\n\tgl::ScopedDepth scopedDepth( false );\n\tgl::ScopedBlendAlpha scopedBlend;\n\tgl::ScopedFaceCulling scopedFaceCulling( false );\n\tshader->uniform( \"uModelViewProjection\", mat );\n\n\tGLuint currentTextureId = 0;\n\tctx->pushTextureBinding( GL_TEXTURE_2D, CINDER_IMGUI_TEXTURE_UNIT );\n\tctx->pushBoolState( GL_SCISSOR_TEST, GL_TRUE );\n\tctx->pushScissor();\n\tfor (int n = 0; n < draw_data->CmdListsCount; n++) {\n\t\tconst ImDrawList* cmd_list = draw_data->CmdLists[n];\n        const ImDrawIdx* idx_buffer_offset = 0;\n\t\n#if defined( USE_MAP_BUFFER ) \n\t\t// grow vertex buffer if needed\n\t\tint needed_vtx_size = cmd_list->VtxBuffer.size() * sizeof(ImDrawVert);\n\t\tif ( vbo->getSize() < needed_vtx_size) {\n\t\t\tGLsizeiptr size = needed_vtx_size + 2000 * sizeof(ImDrawVert);\n#ifndef CINDER_LINUX_EGL_RPI2\n\t\t\tmVbo->bufferData( size, nullptr, GL_STREAM_DRAW );\n#else\n\t\t\tmVbo->bufferData( size, nullptr, GL_DYNAMIC_DRAW );\n#endif\n\t\t}\n\n\t\t// update vertex data\n\t\t{\n\t\t\tImDrawVert *vtx_data = static_cast<ImDrawVert*>( vbo->mapReplace() );\n\t\t\tif (!vtx_data)\n\t\t\t\tcontinue;\n\t\t\tmemcpy( vtx_data, &cmd_list->VtxBuffer[0], cmd_list->VtxBuffer.size() * sizeof(ImDrawVert) );\n\t\t\tvbo->unmap();\n\t\t}\n\t\t\n\t\t// grow index buffer if needed\n\t\tint needed_idx_size = cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx);\n\t\tif( mIbo->getSize() < needed_idx_size ) {\n\t\t\tGLsizeiptr size = needed_idx_size + 2000 * sizeof(ImDrawIdx);\n#if ! defined( CINDER_LINUX_EGL_RPI2 )\n\t\t\tmIbo->bufferData( size, nullptr, GL_STREAM_DRAW );\n#else\n\t\t\tmIbo->bufferData( size, nullptr, GL_DYNAMIC_DRAW );\n#endif\n\t\t}\n\t\t\n\t\t// update index data\n\t\t{\n\t\t\tImDrawIdx *idx_data = static_cast<ImDrawIdx*>( mIbo->mapReplace() );\n\t\t\tif( ! idx_data )\n\t\t\t\tcontinue;\n\t\t\tmemcpy( idx_data, &cmd_list->IdxBuffer[0], cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx) );\n\t\t\tmIbo->unmap();\n\t\t}\n#else\n#if ! defined( CINDER_LINUX_EGL_RPI2 )\n\t\tmVbo->bufferData( (GLsizeiptr)cmd_list->VtxBuffer.Size * sizeof(ImDrawVert), (const GLvoid*)cmd_list->VtxBuffer.Data, GL_STREAM_DRAW );\n\t\tmIbo->bufferData( (GLsizeiptr)cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx), (const GLvoid*)cmd_list->IdxBuffer.Data, GL_STREAM_DRAW );\n#else\n\t\tmVbo->bufferData( (GLsizeiptr)cmd_list->VtxBuffer.Size * sizeof(ImDrawVert), (const GLvoid*)cmd_list->VtxBuffer.Data, GL_DYNAMIC_DRAW );\n\t\tmIbo->bufferData( (GLsizeiptr)cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx), (const GLvoid*)cmd_list->IdxBuffer.Data, GL_DYNAMIC_DRAW );\n#endif\n#endif\n\t\t\n\t\t// issue draw commands\n        for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)\n        {\n            const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];\n\t\t\tif (pcmd->UserCallback) {\n\t\t\t\tpcmd->UserCallback(cmd_list, pcmd);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tbool pushTexture = currentTextureId != (GLuint)(intptr_t) pcmd->TextureId;\n\t\t\t\tif( pushTexture ) {\n\t\t\t\t\tcurrentTextureId = (GLuint)(intptr_t) pcmd->TextureId;\n\t\t\t\t\tctx->bindTexture( GL_TEXTURE_2D, currentTextureId, CINDER_IMGUI_TEXTURE_UNIT );\n\t\t\t\t}\n\t\t\t\tctx->setScissor( { ivec2( (int)pcmd->ClipRect.x, (int)(height - pcmd->ClipRect.w) ), ivec2( (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y) ) } );\n\t\t\t\tgl::drawElements( GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset );\n\t\t\t}\n\t\t\tidx_buffer_offset += pcmd->ElemCount;\n\t\t}\n\t}\n\n\tctx->popScissor();\n\tctx->popBoolState( GL_SCISSOR_TEST );\n\tctx->popTextureBinding( GL_TEXTURE_2D, CINDER_IMGUI_TEXTURE_UNIT );\n}\n\n//! initializes and returns the font texture\ngl::TextureRef Renderer::getFontTextureRef()\n{\n\tif( !mFontTexture ){\n\t\tinitFontTexture();\n\t}\n\treturn mFontTexture;\n}\n//! initializes and returns the vbo mesh\ngl::VaoRef Renderer::getVao()\n{\n\tif( !mVao ){\n\t\tinitBuffers();\n\t}\n\treturn mVao;\n}\n\n//! initializes and returns the vbo\ngl::VboRef Renderer::getVbo()\n{\n\tif( !mVbo ){\n\t\tinitBuffers();\n\t}\n\treturn mVbo;\n}\n\n//! initializes the vbo mesh\nvoid Renderer::initBuffers( size_t size )\n{\n\t#if ! defined( CINDER_LINUX_EGL_RPI2 )\n\tmVbo    = gl::Vbo::create( GL_ARRAY_BUFFER, size, nullptr, GL_STREAM_DRAW );\n\tmIbo    = gl::Vbo::create( GL_ELEMENT_ARRAY_BUFFER, 10, nullptr, GL_STREAM_DRAW );\n\t#else\n\tmVbo    = gl::Vbo::create( GL_ARRAY_BUFFER, size, nullptr, GL_DYNAMIC_DRAW );\n\tmIbo    = gl::Vbo::create( GL_ELEMENT_ARRAY_BUFFER, 10, nullptr, GL_DYNAMIC_DRAW );\n\t#endif\n\tmVao    = gl::Vao::create();\n\t\n\tgl::ScopedVao mVaoScope( mVao );\n\tgl::ScopedBuffer mVboScope( mVbo );\n\t\n\tgl::enableVertexAttribArray( 0 );\n\tgl::enableVertexAttribArray( 1 );\n\tgl::enableVertexAttribArray( 2 );\n\t\n\tgl::vertexAttribPointer( 0, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (const GLvoid*)offsetof(ImDrawVert, pos) );\n\tgl::vertexAttribPointer( 1, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (const GLvoid*)offsetof(ImDrawVert, uv) );\n\tgl::vertexAttribPointer( 2, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (const GLvoid*)offsetof(ImDrawVert, col) );\n\t\n}\n//! initalizes the font texture\nvoid Renderer::initFontTexture()\n{\n\tunsigned char* pixels;\n\tint width, height;\n\tImGui::GetIO().Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);\n\tmFontTexture = gl::Texture::create( pixels, GL_RGBA, width, height, gl::Texture::Format().magFilter(GL_LINEAR).minFilter(GL_LINEAR) );\n\tImGui::GetIO().Fonts->ClearTexData();\n\tImGui::GetIO().Fonts->TexID = (void *)(intptr_t) mFontTexture->getId();\n}\n\n/*ImFont* addFont( ci::DataSourceRef font, float size, int fontId )\n {\n ImFont* newFont = getRenderer()->addFont( font, size, fontId );\n return newFont;\n }\n */\n\nImFont* Renderer::addFont( const ci::fs::path &font, float size, const ImWchar* glyph_ranges, bool merge )\n{\n\tImFontAtlas* fontAtlas  = ImGui::GetIO().Fonts;\n\t\n\tauto fontSource = loadFile( font );\n\tFont ciFont( fontSource, size );\n\n\tImWchar* glyphRanges = NULL;\n\t// if we have glyph ranges copy them\n\tif( glyph_ranges && glyph_ranges[0] && glyph_ranges[1] ){\n\t\tmFontsGlyphRanges.push_back( vector<ImWchar>() );\n\t\tauto &ranges = mFontsGlyphRanges.back();\n\t\tfor( const ImWchar* range = glyph_ranges; range[0] && range[1]; range += 2 ) {\n\t\t\tranges.push_back( range[0] );\n\t\t\tranges.push_back( range[1] );\n\t\t}\n\t\tranges.push_back( 0 );\n\t\tglyphRanges = ranges.data();\n\t}\n\t// otherwise get them from the font\n\telse if( ciFont.getNumGlyphs() ) {\n\t\tint numGlyphs = ciFont.getNumGlyphs();\n\t\t// copy glyphs so we can sort them\n\t\tvector<ImWchar> glyphs;\n\t\tfor( size_t i = 0; i < numGlyphs; ++i ) { \n\t\t\tglyphs.push_back( ciFont.getGlyphIndex( i ) );\n\t\t}\n\t\tsort( glyphs.begin(), glyphs.end() );\n\t\n\t\t// find glyph ranges\n\t\tmFontsGlyphRanges.push_back( vector<ImWchar>() );\n\t\tauto &ranges = mFontsGlyphRanges.back();\n\t\tFont::Glyph start = glyphs[0] == 0 ? '0' : glyphs[0];\n\t\tfor( size_t i = 1; i < numGlyphs; ++i ) {\n\t\t\tif( glyphs[i] != glyphs[i-1] + 1 ) {\n\t\t\t\tranges.push_back( start );\n\t\t\t\tranges.push_back( glyphs[i-1] );\n\t\t\t\tstart = glyphs[i];\n\t\t\t}\n\t\t}\n\t\tif( ranges.empty() || ranges.back() != glyphs[numGlyphs-1] ) {\n\t\t\tranges.push_back( start );\n\t\t\tranges.push_back( glyphs[numGlyphs-1] );\n\t\t}\n\t\tranges.push_back( '\\0' );\n\t\tglyphRanges = ranges.data();\n\t}\n\t\n\tBufferRef buffer\t= fontSource->getBuffer();\n\tvoid* bufferCopy\t= (void*) malloc( buffer->getSize() );\n\tmemcpy( bufferCopy, buffer->getData(), buffer->getSize() );\n\t\n\tImFontConfig config;\n\tif( merge && ! mFonts.empty() ) {\n\t\tconfig.MergeMode = true;\n\t\tconfig.PixelSnapH = true;\n\t\t//config.OversampleV = 4;\n\t}\n\t/*else if( merge ) {\n\t\tfontAtlas->AddFontDefault();\n\t\tconfig.MergeMode = true;\n\t\tconfig.PixelSnapH = true;\n\t}*/\n\n\tImFont* newFont = fontAtlas->AddFontFromMemoryTTF( bufferCopy, buffer->getSize(), size, &config, glyphRanges );\n\t//ImFont* newFont = fontAtlas->AddFontFromFileTTF( font.string().c_str(), size, &config, glyphRanges );\n\t\n\tmFonts.insert( make_pair( font.stem().string(), newFont ) );\n\treturn newFont;\n}\nvoid Renderer::clearFonts()\n{\n\tmFonts.clear();\n}\n\n//! initalizes and returns the shader\ngl::GlslProgRef Renderer::getGlslProg()\n{\n\tif( !mShader ){\n\t\tinitGlslProg();\n\t}\n\treturn mShader;\n}\n\n//! initalizes the shader\nvoid Renderer::initGlslProg()\n{\n\ttry {\n\t\tmShader = gl::GlslProg::create( gl::GlslProg::Format()\n\t\t\t\t\t       .vertex(\n\t\t\t\t\t#if defined(CINDER_GL_ES_2)\n\t\t\t\t\t\t       R\"(\n\t\t\t\t\t\t       precision highp float;\n\t\t\t\t\t\t       uniform mat4 uModelViewProjection;\n\t\t\t\t\t\t       \n\t\t\t\t\t\t       attribute vec2      iPosition;\n\t\t\t\t\t\t       attribute vec2      iUv;\n\t\t\t\t\t\t       attribute vec4      iColor;\n\t\t\t\t\t\t       \n\t\t\t\t\t\t       varying vec2     vUv;\n\t\t\t\t\t\t       varying vec4     vColor;\n\t\t\t\t\t\t       \n\t\t\t\t\t\t       void main() {\n\t\t\t\t\t\t\t       vColor       = iColor;\n\t\t\t\t\t\t\t       vUv          = iUv;\n\t\t\t\t\t\t\t       gl_Position  = uModelViewProjection * vec4( iPosition, 0.0, 1.0 );\n\t\t\t\t\t\t       } )\"\n\t\t\t\t\t#elif defined(CINDER_GL_ES_3)\n\t\t\t\t\t       R\"(\n\t\t\t\t\t\t#version 300 es\n\t\t\t\t\t       precision highp float;\n\t\t\t\t\t       uniform mat4 uModelViewProjection;\n\t\t\t\t\t       \n\t\t\t\t\t       in vec2      iPosition;\n\t\t\t\t\t       in vec2      iUv;\n\t\t\t\t\t       in vec4      iColor;\n\t\t\t\t\t       \n\t\t\t\t\t       out vec2     vUv;\n\t\t\t\t\t       out vec4     vColor;\n\t\t\t\t\t       \n\t\t\t\t\t       void main() {\n\t\t\t\t\t\t       vColor       = iColor;\n\t\t\t\t\t\t       vUv          = iUv;\n\t\t\t\t\t\t       gl_Position  = uModelViewProjection * vec4( iPosition, 0.0, 1.0 );\n\t\t\t\t\t       } )\"\n\t\t\t\t\t#else\n\t\t\t\t\t\tR\"(\n\t\t\t\t\t\t#version 150\n\t\t\t\t\t\tuniform mat4 uModelViewProjection;\n\t\t\t\t\t\tin vec2      iPosition;\n\t\t\t\t\t\tin vec2      iUv;\n\t\t\t\t\t\tin vec4      iColor;\n\t\t\t\t\t\tout vec2     vUv;\n\t\t\t\t\t\tout vec4     vColor;\n\t\t\t\t\t\tvoid main() {\n\t\t\t\t\t\t\tvColor       = iColor;\n\t\t\t\t\t\t\tvUv          = iUv;\n\t\t\t\t\t\t\tgl_Position  = uModelViewProjection * vec4( iPosition, 0.0, 1.0 );\n\t\t\t\t\t\t} )\"\n\t\t\t\t\t\t\n\t\t\t\t\t#endif\n\t\t)\n\t\t.fragment(\n\t#if defined(CINDER_GL_ES_2)\n\t\t\t  R\"(\n\t\t\t  precision highp float;\n\t\t\t  \n\t\t\t  varying highp vec2\tvUv;\n\t\t\t  varying highp vec4\tvColor;\n\t\t\t  uniform sampler2D\tuTex;\n\t\t\t  \n\t\t\t  void main() {\n\t\t\t\t  vec4 color = texture2D( uTex, vUv ) * vColor;\n\t\t\t\t  gl_FragColor = color;\n\t\t\t  }  )\"\n\t#elif defined(CINDER_GL_ES_3)\n\t\tR\"(\n\t\t#version 300 es\n\t\tprecision highp float;\n\t\t\n\t\tin highp vec2\t\tvUv;\n\t\tin highp vec4\t\tvColor;\n\t\tout highp vec4\t\toColor;\n\t\tuniform sampler2D\tuTex;\n\t\t\n\t\tvoid main() {\n\t\t\tvec4 color = texture( uTex, vUv ) * vColor;\n\t\t\toColor = color;\n\t\t}  )\"\n\t#else\n\t\tR\"(\n\t\t#version 150\n\t\t\n\t\tin vec2\t\t\tvUv;\n\t\tin vec4\t\t\tvColor;\n\t\tout vec4\t\toColor;\n\t\tuniform sampler2D\tuTex;\n\t\t\n\t\tvoid main() {\n\t\t\tvec4 color = texture( uTex, vUv ) * vColor;\n\t\t\toColor = color;\n\t\t}  )\"\n\t\t\n\t#endif\n\t\t)\n\t\t.attribLocation( \"iPosition\", 0 )\n\t\t.attribLocation( \"iUv\", 1 )\n\t\t.attribLocation( \"iColor\", 2 )\n\t\t);\n\n\t\tmShader->uniform( \"uTex\", CINDER_IMGUI_TEXTURE_UNIT );\n\n\t}\n\tcatch( gl::GlslProgCompileExc exc ){\n\t\tCI_LOG_E( \"Problem Compiling ImGui::Renderer shader \" << exc.what() );\n\t}\n}\nImFont* Renderer::getFont( const std::string &name )\n{\n\tif( !mFonts.count( name ) ){\n\t\treturn nullptr;\n\t}\n\telse {\n\t\treturn mFonts[name];\n\t}\n}\n\n\ntypedef std::shared_ptr<Renderer> RendererRef;\nRendererRef getRenderer()\n{\n\tstatic RendererRef renderer = RendererRef( new Renderer() );\n\treturn renderer;\n}\n\n\n// Cinder Helpers\nvoid Image( const ci::gl::Texture2dRef &texture, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col )\n{\n\tImage( (void*)(intptr_t) texture->getId(), size, uv0, uv1, tint_col, border_col );\n}\nbool ImageButton( const ci::gl::Texture2dRef &texture, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, int frame_padding, const ImVec4& bg_col, const ImVec4& tint_col)\n{\n\treturn ImageButton( (void*)(intptr_t) texture->getId(), size, uv0, uv1, frame_padding, bg_col, tint_col );\n}\n\nvoid PushFont( const std::string& name )\n{\n\tauto renderer   = getRenderer();\n\tImFont* font    = renderer->getFont( name );\n\tCI_ASSERT( font != nullptr );\n\tPushFont( font );\n}\n\nbool Combo(const char* label, int* currIndex, const std::vector<std::string>& values, ImGuiComboFlags flags)\n{\n\tif (values.empty()) return false;\n\n\tbool changed = false;\n\tint itemsCount = (int)values.size();\n\tconst char* previewItem = NULL;\n\tif (*currIndex >= 0 && *currIndex < itemsCount) {\n\t\tpreviewItem = values.at(*currIndex).c_str();\n\t}\n\n\tif (ImGui::BeginCombo(label, previewItem, flags)) {\n\t\tfor (int i = 0; i < itemsCount; ++i) {\n\t\t\tImGui::PushID((void*)(intptr_t)i);\n\t\t\tbool selected = (*currIndex == i);\n\t\t\tif (ImGui::Selectable(values.at(i).c_str(), selected)) {\n\t\t\t\t*currIndex = i;\n\t\t\t\tchanged = true;\n\t\t\t}\n\t\t\tif (selected) ImGui::SetItemDefaultFocus();\n\t\t\tImGui::PopID();\n\t\t}\n\t\tImGui::EndCombo();\n\t}\n\treturn changed;\n}\n\n// Std Helpers\nbool ListBox( const char* label, int* current_item, const std::vector<std::string>& items, int height_in_items )\n{\n\t// copy names to a vector\n\tvector<const char*> names;\n\tfor( auto item : items ) {\n\t\tchar *cname = new char[ item.size() + 1 ];\n\t\tstd::strcpy( cname, item.c_str() );\n\t\tnames.push_back( cname );\n\t}\n\t\n\tbool result = ListBox( label, current_item, names.data(), names.size(), height_in_items );\n\t// cleanup\n\tfor( auto &name : names ) delete [] name;\n\treturn result;\n}\nbool InputText( const char* label, std::string* buf, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data )\n{\n\t// conversion\n\tchar *buffer = new char[buf->size()+128];\n\tstd::strcpy( buffer, buf->c_str() );\n\tbool result = InputText( label, buffer, buf->size()+128, flags, callback, user_data );\n\tif( result ){\n\t\t*buf = string( buffer );\n\t}\n\t// cleanup\n\tdelete [] buffer;\n\treturn result;\n}\nbool InputTextMultiline( const char* label, std::string* buf, const ImVec2& size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data )\n{\n\t// conversion\n\tconstexpr size_t extraSpace = 16384;\n\tchar *buffer = new char[buf->size()+extraSpace];\n\tstd::strcpy( buffer, buf->c_str() );\n\tbool result = InputTextMultiline( label, buffer, buf->size()+extraSpace, size, flags, callback, user_data );\n\tif( result ){\n\t\t*buf = string( buffer );\n\t}\n\t// cleanup\n\tdelete [] buffer;\n\treturn result;\n}\n\nnamespace {\n\t\n\t//! sets the right mouseDown IO values in imgui\n\tvoid mouseDown( ci::app::MouseEvent& event )\n\t{\n\t\tImGuiIO& io = ImGui::GetIO();\n\t\tio.MousePos = toPixels( event.getPos() );\n\t\tif( event.isLeftDown() ){\n\t\t\tio.MouseDown[0] = true;\n\t\t\tio.MouseDown[1] = false;\n\t\t}\n\t\telse if( event.isRightDown() ){\n\t\t\tio.MouseDown[0] = false;\n\t\t\tio.MouseDown[1] = true;\n\t\t}\n\t\t\n\t\tevent.setHandled( io.WantCaptureMouse );\n\t}\n\t//! sets the right mouseMove IO values in imgui\n\tvoid mouseMove( ci::app::MouseEvent& event )\n\t{\n\t\tImGuiIO& io = ImGui::GetIO();\n\t\tio.MousePos = toPixels( event.getPos() );\n\t\t\n\t\tevent.setHandled( io.WantCaptureMouse );\n\t}\n\t//! sets the right mouseDrag IO values in imgui\n\tvoid mouseDrag( ci::app::MouseEvent& event )\n\t{\n\t\tImGuiIO& io = ImGui::GetIO();\n\t\tio.MousePos = toPixels( event.getPos() );\n\t\t\n\t\tevent.setHandled( io.WantCaptureMouse );\n\t}\n\t//! sets the right mouseDrag IO values in imgui\n\tvoid mouseUp( ci::app::MouseEvent& event )\n\t{\n\t\tImGuiIO& io     = ImGui::GetIO();\n\t\tio.MouseDown[0] = false;\n\t\tio.MouseDown[1] = false;\n\t\t\n\t\tevent.setHandled( io.WantCaptureMouse );\n\t}\n\t//! sets the right mouseWheel IO values in imgui\n\tvoid mouseWheel( ci::app::MouseEvent& event )\n\t{\n\t\tImGuiIO& io     = ImGui::GetIO();\n\t\tio.MouseWheel   += event.getWheelIncrement();\n\t\t\n\t\tevent.setHandled( io.WantCaptureMouse );\n\t}\n\t\n\t\n\tvector<int> sAccelKeys;\n\t\n\t//! sets the right keyDown IO values in imgui\n\tvoid keyDown( ci::app::KeyEvent& event )\n\t{\n\t\tImGuiIO& io = ImGui::GetIO();\n\n\t\t#if defined CINDER_LINUX\n\t\t\tauto character = event.getChar();\n\t\t#else\n\t\t\tuint32_t character = event.getCharUtf32();\n\t\t#endif\n\n\t\tio.KeysDown[event.getCode()] = true;\n\t\t\n\t\tif ( !event.isAccelDown() && character > 0 && character <= 255 ) {\n\t\t\tio.AddInputCharacter( ( char ) character );\n\t\t}\n\t\telse if( event.getCode() != KeyEvent::KEY_LMETA\n\t\t\t&& event.getCode() != KeyEvent::KEY_RMETA\n\t\t\t&& event.isAccelDown()\n\t\t\t&& find( sAccelKeys.begin(), sAccelKeys.end(), event.getCode() ) == sAccelKeys.end() ){\n\t\t\tsAccelKeys.push_back( event.getCode() );\n\t\t}\n\t\t\n\t\tio.KeyCtrl = io.KeysDown[KeyEvent::KEY_LCTRL] || io.KeysDown[KeyEvent::KEY_RCTRL];\n\t\tio.KeyShift = io.KeysDown[KeyEvent::KEY_LSHIFT] || io.KeysDown[KeyEvent::KEY_RSHIFT];\n\t\tio.KeyAlt = io.KeysDown[KeyEvent::KEY_LALT] || io.KeysDown[KeyEvent::KEY_RALT];\n\t\tio.KeySuper = io.KeysDown[KeyEvent::KEY_LMETA] || io.KeysDown[KeyEvent::KEY_RMETA] || io.KeysDown[KeyEvent::KEY_LSUPER] || io.KeysDown[KeyEvent::KEY_RSUPER];\n\t\t\n\t\tevent.setHandled( io.WantCaptureKeyboard );\n\t}\n\t//! sets the right keyUp IO values in imgui\n\tvoid keyUp( ci::app::KeyEvent& event )\n\t{\n\t\tImGuiIO& io = ImGui::GetIO();\n\t\t\n\t\tio.KeysDown[event.getCode()] = false;\n\t\t\n\t\tfor( auto key : sAccelKeys ){\n\t\t\tio.KeysDown[key] = false;\n\t\t}\n\t\tsAccelKeys.clear();\n\t\t\n\t\tio.KeyCtrl = io.KeysDown[KeyEvent::KEY_LCTRL] || io.KeysDown[KeyEvent::KEY_RCTRL];\n\t\tio.KeyShift = io.KeysDown[KeyEvent::KEY_LSHIFT] || io.KeysDown[KeyEvent::KEY_RSHIFT];\n\t\tio.KeyAlt = io.KeysDown[KeyEvent::KEY_LALT] || io.KeysDown[KeyEvent::KEY_RALT];\n\t\tio.KeySuper = io.KeysDown[KeyEvent::KEY_LMETA] || io.KeysDown[KeyEvent::KEY_RMETA] || io.KeysDown[KeyEvent::KEY_LSUPER] || io.KeysDown[KeyEvent::KEY_RSUPER];\n\t\t\n\t\tevent.setHandled( io.WantCaptureKeyboard );\n\t}\n\t\n\tstatic bool sNewFrame = false;\n\tvoid newFrameGuard();\n\tvoid render()\n\t{\n\t\tstatic auto timer = ci::Timer(true);\n\t\tImGuiIO& io = ImGui::GetIO();\n\t\tio.DeltaTime = timer.getSeconds();\n\n\t\tif( io.DeltaTime < 0.0f ) {\n\t\t\tCI_LOG_W(\"WARNING: overriding imgui deltatime because it is \" << io.DeltaTime);\n\t\t\tio.DeltaTime = 1.0f/60.0f;\n\t\t}\n\n\t\ttimer.start();\n\t\tImGui::Render();\n\t\tauto renderer = getRenderer();\n\t\trenderer->render( ImGui::GetDrawData() );\n\t\tsNewFrame = false;\n\t\tApp::get()->dispatchAsync( []() {\n\t\t\tnewFrameGuard();\n\t\t} );\n\t}\n\t\n\tvoid newFrameGuard()\n\t{\n\t\tif( ! sNewFrame ){\n\t\t\tImGui::NewFrame();\n\t\t\tsNewFrame = true;\n\t\t}\n\t}\n\n\tvoid resize()\n\t{\n\t\tImGuiIO& io\t= ImGui::GetIO();\n\t\tio.DisplaySize\t= toPixels( getWindowSize() );\n\t\tnewFrameGuard();\n\t}\n\t\n\tvoid resetKeys()\n\t{\n\t\tfor( int i = 0; i < IM_ARRAYSIZE( ImGui::GetIO().KeysDown ); i++ ) {\n\t\t\tImGui::GetIO().KeysDown[i] = false;\n\t\t}\n\t\tfor( int i = 0; i < IM_ARRAYSIZE( ImGui::GetIO().KeysDown); i++ ) {\n\t\t\tImGui::GetKeyData(i)->DownDuration = 0.0f;\n\t\t}\n\t\tfor( int i = 0; i < IM_ARRAYSIZE( ImGui::GetIO().KeysDown); i++ ) {\n\t\t\tImGui::GetKeyData(i)->DownDurationPrev = 0.0f;\n\t\t}\n\t\tImGui::GetIO().KeyCtrl\t= false;\n\t\tImGui::GetIO().KeyShift = false;\n\t\tImGui::GetIO().KeyAlt\t= false;\n\t}\n\t\n} // Anonymous namespace\n\n// wrong... and would not work in a multi-windows scenario\nstatic signals::ConnectionList sWindowConnections;\n\n// also wrong... but fixes a crash on cleanup\nstatic signals::ConnectionList sAppConnections;\n\nvoid initialize( const Options &options )\n{\n\t// create one context for now. will update with multiple context / shared fontatlas soon!\n\tImGuiContext* context = ImGui::CreateContext();\n\n\t// get the window and switch to its context before initializing the renderer\n\tauto window\t\t\t\t\t= options.getWindow();\n\tauto currentContext\t\t\t= gl::context();\n\twindow->getRenderer()->makeCurrentContext();\n\tauto renderer\t\t\t\t= getRenderer();\n\t\n\t// set style\n\tconst ImGuiStyle& style\t\t\t\t= options.getStyle();\n\tImGuiStyle& imGuiStyle\t\t\t\t= ImGui::GetStyle();\n\timGuiStyle.Alpha\t\t\t\t\t= style.Alpha;\n\timGuiStyle.WindowPadding\t\t\t= style.WindowPadding;\n\timGuiStyle.WindowMinSize\t\t\t= style.WindowMinSize;\n\timGuiStyle.WindowRounding\t\t\t= style.WindowRounding;\n\timGuiStyle.WindowTitleAlign\t\t\t= style.WindowTitleAlign;\n\timGuiStyle.ChildRounding\t\t\t= style.ChildRounding;\n\timGuiStyle.FramePadding\t\t\t\t= style.FramePadding;\n\timGuiStyle.FrameRounding\t\t\t= style.FrameRounding;\n\timGuiStyle.ItemSpacing\t\t\t\t= style.ItemSpacing;\n\timGuiStyle.ItemInnerSpacing\t\t\t= style.ItemInnerSpacing;\n\timGuiStyle.TouchExtraPadding\t\t= style.TouchExtraPadding;\n\timGuiStyle.IndentSpacing\t\t\t= style.IndentSpacing;\n\timGuiStyle.ColumnsMinSpacing\t\t= style.ColumnsMinSpacing;\n\timGuiStyle.ScrollbarSize\t\t\t= style.ScrollbarSize;\n\timGuiStyle.ScrollbarRounding\t\t= style.ScrollbarRounding;\n\timGuiStyle.GrabMinSize\t\t\t\t= style.GrabMinSize;\n\timGuiStyle.GrabRounding\t\t\t\t= style.GrabRounding;\n\timGuiStyle.ButtonTextAlign\t\t\t= style.ButtonTextAlign;\n\timGuiStyle.DisplayWindowPadding\t\t= style.DisplayWindowPadding;\n\timGuiStyle.DisplaySafeAreaPadding\t= style.DisplaySafeAreaPadding;\n\timGuiStyle.AntiAliasedLines\t\t\t= style.AntiAliasedLines;\n\timGuiStyle.AntiAliasedFill\t\t\t= style.AntiAliasedFill;\n\t\n\t// set colors\n\tfor( int i = 0; i < ImGuiCol_COUNT; i++ )\n\t\timGuiStyle.Colors[i] = style.Colors[i];\n\t\n\t// set io and keymap\n\tImGuiIO& io                         = ImGui::GetIO();\n\tio.DisplaySize                      = ImVec2( window->getSize().x, window->getSize().y );\n\tio.DeltaTime                        = 1.0f / 60.0f;\n\tio.KeyMap[ImGuiKey_Tab]             = KeyEvent::KEY_TAB;\n\tio.KeyMap[ImGuiKey_LeftArrow]       = KeyEvent::KEY_LEFT;\n\tio.KeyMap[ImGuiKey_RightArrow]      = KeyEvent::KEY_RIGHT;\n\tio.KeyMap[ImGuiKey_UpArrow]         = KeyEvent::KEY_UP;\n\tio.KeyMap[ImGuiKey_DownArrow]       = KeyEvent::KEY_DOWN;\n\tio.KeyMap[ImGuiKey_Home]            = KeyEvent::KEY_HOME;\n\tio.KeyMap[ImGuiKey_End]             = KeyEvent::KEY_END;\n\tio.KeyMap[ImGuiKey_Delete]          = KeyEvent::KEY_DELETE;\n\tio.KeyMap[ImGuiKey_Backspace]       = KeyEvent::KEY_BACKSPACE;\n\tio.KeyMap[ImGuiKey_Enter]           = KeyEvent::KEY_RETURN;\n\tio.KeyMap[ImGuiKey_Escape]          = KeyEvent::KEY_ESCAPE;\n\tio.KeyMap[ImGuiKey_A]               = KeyEvent::KEY_a;\n\tio.KeyMap[ImGuiKey_C]               = KeyEvent::KEY_c;\n\tio.KeyMap[ImGuiKey_V]               = KeyEvent::KEY_v;\n\tio.KeyMap[ImGuiKey_X]               = KeyEvent::KEY_x;\n\tio.KeyMap[ImGuiKey_Y]               = KeyEvent::KEY_y;\n\tio.KeyMap[ImGuiKey_Z]               = KeyEvent::KEY_z;\n\tio.KeyMap[ImGuiKey_Insert]\t\t\t= KeyEvent::KEY_INSERT;\n\tio.KeyMap[ImGuiKey_Space]\t\t\t= KeyEvent::KEY_SPACE;\n\t\n\t// setup config file path\n\tstatic string path = ( getAssetPath( \"\" ) / \"imgui.ini\" ).string();\n\tif( ! options.getIniPath().empty() )\n\t\tpath = options.getIniPath().string().c_str();\n\tio.IniFilename = path.c_str();\n\t\n\t// setup fonts\n\tImFontAtlas* fontAtlas  = ImGui::GetIO().Fonts;\n\tfontAtlas->Clear();\n\trenderer->clearFonts();\n\tfor( auto font : options.getFonts() ){\n\t\tstring name = font.first.stem().string();\n\t\trenderer->addFont( font.first, font.second, options.getFontGlyphRanges( name ), options.getFontMergeMode() );\n\t}\n\trenderer->initFontTexture();\n\t\n#ifndef CINDER_LINUX\n\t// clipboard callbacks\n\tio.SetClipboardTextFn = []( void* user_data, const char* text ) {\n\t\t// clipboard text is already zero-terminated\n\t\tClipboard::setString( text );\n\t};\n\tio.GetClipboardTextFn = []( void* user_data ) {\n\t\tstring str = Clipboard::getString();\n\t\tstatic vector<char> strCopy;\n\t\tstrCopy = vector<char>(str.begin(), str.end());\n\t\tstrCopy.push_back('\\0');\n\t\treturn (const char *) &strCopy[0];\n\t};\n#endif\n\t\n\t// connect window's signals\n\tdisconnectWindow( window );\n\tconnectWindow( window );\n\t\n\tif( options.isAutoRenderEnabled() && window ) {\n\t\tsWindowConnections += ( window->getSignalDraw().connect( newFrameGuard ) );\n\t\tsWindowConnections += ( window->getSignalPostDraw().connect( render ) );\n\t}\n\t\n\t// connect app's signals\n    sAppConnections += app::App::get()->getSignalDidBecomeActive().connect( resetKeys );\n    sAppConnections += app::App::get()->getSignalWillResignActive().connect( resetKeys );\n    sAppConnections += app::App::get()->getSignalCleanup().connect( [context](){\n        sAppConnections.clear();\n\n\t\tImGui::DestroyContext( context );\n#if defined( IMGUI_DOCK )\n\t\tShutdownDock();\n#endif\n\t} );\n\n\tsInitialized = true;\n\t\n\t// switch back to the original gl context\n\tcurrentContext->makeCurrent();\n}\n\n\nvoid connectWindow( ci::app::WindowRef window )\n{\n\tsWindowConnections += window->getSignalMouseDown().connect( mouseDown );\n\tsWindowConnections += window->getSignalMouseUp().connect( mouseUp );\n\tsWindowConnections += window->getSignalMouseDrag().connect( mouseDrag );\n\tsWindowConnections += window->getSignalMouseMove().connect( mouseMove );\n\tsWindowConnections += window->getSignalMouseWheel().connect( mouseWheel );\n\tsWindowConnections += window->getSignalKeyDown().connect( keyDown );\n\tsWindowConnections += window->getSignalKeyUp().connect( keyUp );\n\tsWindowConnections += window->getSignalResize().connect( resize );\n}\nvoid disconnectWindow( ci::app::WindowRef window )\n{\n\tsWindowConnections.clear();\n}\n\nScopedWindow::ScopedWindow( const std::string &name, ImGuiWindowFlags flags)\n{\n\tImGui::Begin( name.c_str(), nullptr, flags );\n}\nScopedWindow::~ScopedWindow()\n{\n\tImGui::End();\n}\nScopedChild::ScopedChild( const std::string &name, glm::vec2 size, bool border, ImGuiWindowFlags extraFlags )\n{\n\tImGui::BeginChild( name.c_str(), size, border, extraFlags );\n}\nScopedChild::~ScopedChild()\n{\n\tImGui::EndChild();\n}\nScopedGroup::ScopedGroup()\n{\n\tImGui::BeginGroup();\n}\nScopedGroup::~ScopedGroup()\n{\n\tImGui::EndGroup();\n}\nScopedFont::ScopedFont( ImFont* font )\n{\n\tImGui::PushFont( font );\n}\nScopedFont::ScopedFont( const std::string &name )\n{\n\tImGui::PushFont( name );\n}\nScopedFont::~ScopedFont()\n{\n\tImGui::PopFont();\n}\nScopedStyleColor::ScopedStyleColor( ImGuiCol idx, const ImVec4& col )\n{\n\tImGui::PushStyleColor( idx, col );\n}\nScopedStyleColor::~ScopedStyleColor()\n{\n\tImGui::PopStyleColor();\n}\nScopedStyleVar::ScopedStyleVar( ImGuiStyleVar idx, float val )\n{\n\tImGui::PushStyleVar( idx, val );\n}\nScopedStyleVar::ScopedStyleVar( ImGuiStyleVar idx, const ImVec2 &val )\n{\n\tImGui::PushStyleVar( idx, val );\n}\nScopedStyleVar::~ScopedStyleVar()\n{\n\tImGui::PopStyleVar();\n}\n\nScopedItemWidth::ScopedItemWidth( float itemWidth )\n{\n\tImGui::PushItemWidth( itemWidth );\n}\nScopedItemWidth::~ScopedItemWidth()\n{\n\tImGui::PopItemWidth();\n}\n\nScopedTextWrapPos::ScopedTextWrapPos( float wrapPosX )\n{\n\tImGui::PushTextWrapPos( wrapPosX );\n}\nScopedTextWrapPos::~ScopedTextWrapPos()\n{\n\tImGui::PopTextWrapPos();\n}\n\nScopedId::ScopedId( const std::string &name )\n{\n\tImGui::PushID( name.c_str() );\n}\nScopedId::ScopedId( const void *ptrId )\n{\n\tImGui::PushID( ptrId );\n}\nScopedId::ScopedId( const int intId )\n{\n\tImGui::PushID( intId );\n}\nScopedId::~ScopedId()\n{\n\tImGui::PopID();\n}\n\nScopedMainMenuBar::ScopedMainMenuBar()\n{\n\tmOpened = ImGui::BeginMainMenuBar();\n}\nScopedMainMenuBar::~ScopedMainMenuBar()\n{\n\tif( mOpened ) ImGui::EndMainMenuBar();\n}\n\nScopedMenuBar::ScopedMenuBar()\n{\n\tmOpened = ImGui::BeginMenuBar();\n}\nScopedMenuBar::~ScopedMenuBar()\n{\n\tif( mOpened ) ImGui::EndMenuBar();\n}\n//\n//bool FilePicker( const char* label, fs::path* path, bool open, const fs::path &initialPath, std::vector<std::string> extensions )\n//{\n//\n//    ImGuiWindow* window = GetCurrentWindow();\n//    if (window->SkipItems)\n//        return false;\n//\n//    ImGuiContext& g = *GImGui;\n//    const ImGuiStyle& style = g.Style;\n//    const ImGuiID id = window->GetID(label);\n//    const float w = CalcItemWidth();\n//\n//    const ImVec2 label_size = CalcTextSize(label, NULL, true);\n//    const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f));\n//    const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));\n//\n//    ItemSize(total_bb, style.FramePadding.y);\n//\tif (!ItemAdd(total_bb, &id))\n//    {\n//        return false;\n//    }\n//\t\n//    bool hovered, held;\n//    ButtonBehavior(frame_bb, id, &hovered, &held);\n//    const ImU32 col = GetColorU32((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : path->empty() ? ImGuiCol_Column : ImGuiCol_Button);\t\n//    RenderFrame( frame_bb.Min, frame_bb.Max, col, true, style.FrameRounding );\n//\t\n//\tfs::path filename = path->has_filename() ? path->filename() : path->has_stem() ? path->stem() : *path;\n//\tfs::path dir = path->has_parent_path() && path->parent_path().has_stem() ? path->parent_path().stem() : fs::path();\n//    RenderTextClipped( frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding, ( dir / filename ).string().c_str(), NULL, NULL, ImVec2(0.5f,0.5f) );\n//\t\n//\tbool changed = false;\n//\tPushID( label );\n//\tif( BeginPopupContextItem( \"##FilePickerContextPopup\", 0 ) ) {\n//\t\tif( MenuItem( string( \"Load \" + string( label ) ).c_str(), \"\", nullptr ) ) {\n//\t\t\tauto newPath = open ? getOpenFilePath( initialPath, extensions ) : getSaveFilePath( initialPath, extensions );\n//\t\t\tif( ! newPath.empty() ) {\n//\t\t\t\t*path = newPath;\n//\t\t\t\tchanged = true;\n//\t\t\t}\n//\t\t}\n//\t\tif( MenuItem( \"Clear\", \"\", nullptr ) ) {\n//\t\t\tpath->clear();\n//\t\t\tchanged = true;\n//\t\t}\n//\t\tEndPopup();\n//\t}\n//\tPopID();\n//\n//\tif( hovered && ! path->empty() ) {\n//\t\tBeginTooltip();\n//\t\tTextUnformatted( path->string().c_str() );\n//\t\tEndTooltip();\n//\t}\n//\t\n//\n//    if (label_size.x > 0.0f)\n//        RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);\n//\n//\treturn changed;\n//\n//}\n//\n//bool IconButton( const char* icon, const ImVec2& size_arg, bool frame )\n//{\n//    ImGuiWindow* window = GetCurrentWindow();\n//    if (window->SkipItems)\n//        return false;\n//\n//    ImGuiContext& g = *GImGui;\n//    const ImGuiStyle& style = g.Style;\n//    const ImGuiID id = window->GetID(icon);\n//    const ImVec2 label_size = CalcTextSize(icon, NULL, true);\n//\t\n//\tImGuiButtonFlags flags = 0;\n//    ImVec2 pos = window->DC.CursorPos;\n//    if ((flags & ImGuiButtonFlags_AlignTextBaseLine) && style.FramePadding.y < window->DC.CurrentLineTextBaseOffset) // Try to vertically align buttons that are smaller/have no padding so that text baseline matches (bit hacky, since it shouldn't be a flag)\n//        pos.y += window->DC.CurrentLineTextBaseOffset - style.FramePadding.y;\n//    ImVec2 size = CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0f, label_size.y + style.FramePadding.y * 2.0f);\n//\n//    const ImRect bb(pos, pos + size);\n//    ItemSize(bb, style.FramePadding.y);\n//    if (!ItemAdd(bb, &id))\n//        return false;\n//\n//    if (window->DC.ItemFlags & ImGuiItemFlags_ButtonRepeat) flags |= ImGuiButtonFlags_Repeat;\n//\n//    bool hovered, held;\n//    bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);\n//\n//    // Render\n//\tconst ImU32 col = GetColorU32((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Text);\n//\tScopedStyleColor color( ImGuiCol_Text, ImVec4( (float)((col >> 0) & 0xFF) / 255.0f, (float)((col >> 8) & 0xFF) / 255.0f, (float)((col >> 16) & 0xFF) / 255.0f, (float)((col >> 24) & 0xFF) / 255.0f ) );\n//    RenderTextClipped(bb.Min + style.FramePadding, bb.Max - style.FramePadding, icon, NULL, &label_size, style.ButtonTextAlign, &bb);\n//\n//\treturn pressed;\n//}\n//\n//bool IconToggle( const char* iconEnabled, const char* iconDisabled, bool *enabled, const ImVec2& size, bool frame )\n//{\n//    ImGuiWindow* window = GetCurrentWindow();\n//    if (window->SkipItems)\n//        return false;\n//\n//\tbool changed = IconButton( *enabled ? iconEnabled : iconDisabled, size, frame );\n//\tif( changed ) {\n//\t\t*enabled = ! *enabled;\n//\t}\n//\treturn changed;\n//}\n\n#if defined( IMGUI_DOCK )\n\nstruct DockContext\n{\n\tenum Slot_\n\t{\n\t\tSlot_Left,\n\t\tSlot_Right,\n\t\tSlot_Top,\n\t\tSlot_Bottom,\n\t\tSlot_Tab,\n\n\t\tSlot_Float,\n\t\tSlot_None\n\t};\n\n\n\tenum EndAction_\n\t{\n\t\tEndAction_None,\n\t\tEndAction_Panel,\n\t\tEndAction_End,\n\t\tEndAction_EndChild\n\t};\n\n\n\tenum Status_\n\t{\n\t\tStatus_Docked,\n\t\tStatus_Float,\n\t\tStatus_Dragged\n\t};\n\n\n\tstruct Dock\n\t{\n\t\tDock()\n\t\t\t: id(0)\n\t\t\t, next_tab(nullptr)\n\t\t\t, prev_tab(nullptr)\n\t\t\t, parent(nullptr)\n\t\t\t, pos(0, 0)\n\t\t\t, size(-1, -1)\n\t\t\t, active(true)\n\t\t\t, status(Status_Float)\n\t\t\t, label(nullptr)\n\t\t\t, opened(false)\n\t\t{\n\t\t\tlocation[0] = 0;\n\t\t\tchildren[0] = children[1] = nullptr;\n\t\t}\n\n\n\t\t~Dock() { MemFree(label); }\n\n\n\t\tImVec2 getMinSize() const\n\t\t{\n\t\t\tif (!children[0]) return ImVec2(16, 16 + GetTextLineHeightWithSpacing());\n\n\t\t\tImVec2 s0 = children[0]->getMinSize();\n\t\t\tImVec2 s1 = children[1]->getMinSize();\n\t\t\treturn isHorizontal() ? ImVec2(s0.x + s1.x, ImMax(s0.y, s1.y))\n\t\t\t\t\t\t\t\t  : ImVec2(ImMax(s0.x, s1.x), s0.y + s1.y);\n\t\t}\n\n\n\t\tbool isHorizontal() const { return children[0]->pos.x < children[1]->pos.x; }\n\n\n\t\tvoid setParent(Dock* dock)\n\t\t{\n\t\t\tparent = dock;\n\t\t\tfor (Dock* tmp = prev_tab; tmp; tmp = tmp->prev_tab) tmp->parent = dock;\n\t\t\tfor (Dock* tmp = next_tab; tmp; tmp = tmp->next_tab) tmp->parent = dock;\n\t\t}\n\n\n\t\tDock& getSibling()\n\t\t{\n\t\t\tIM_ASSERT(parent);\n\t\t\tif (parent->children[0] == &getFirstTab()) return *parent->children[1];\n\t\t\treturn *parent->children[0];\n\t\t}\n\n\n\t\tDock& getFirstTab()\n\t\t{\n\t\t\tDock* tmp = this;\n\t\t\twhile (tmp->prev_tab) tmp = tmp->prev_tab;\n\t\t\treturn *tmp;\n\t\t}\n\n\n\t\tvoid setActive()\n\t\t{\n\t\t\tactive = true;\n\t\t\tfor (Dock* tmp = prev_tab; tmp; tmp = tmp->prev_tab) tmp->active = false;\n\t\t\tfor (Dock* tmp = next_tab; tmp; tmp = tmp->next_tab) tmp->active = false;\n\t\t}\n\n\n\t\tbool isContainer() const { return children[0] != nullptr; }\n\n\n\t\tvoid setChildrenPosSize(const ImVec2& _pos, const ImVec2& _size)\n\t\t{\n\t\t\tImVec2 s = children[0]->size;\n\t\t\tif (isHorizontal())\n\t\t\t{\n\t\t\t\ts.y = _size.y;\n\t\t\t\ts.x = (float)int(\n\t\t\t\t\t_size.x * children[0]->size.x / (children[0]->size.x + children[1]->size.x));\n\t\t\t\tif (s.x < children[0]->getMinSize().x)\n\t\t\t\t{\n\t\t\t\t\ts.x = children[0]->getMinSize().x;\n\t\t\t\t}\n\t\t\t\telse if (_size.x - s.x < children[1]->getMinSize().x)\n\t\t\t\t{\n\t\t\t\t\ts.x = _size.x - children[1]->getMinSize().x;\n\t\t\t\t}\n\t\t\t\tchildren[0]->setPosSize(_pos, s);\n\n\t\t\t\ts.x = _size.x - children[0]->size.x;\n\t\t\t\tImVec2 p = _pos;\n\t\t\t\tp.x += children[0]->size.x;\n\t\t\t\tchildren[1]->setPosSize(p, s);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\ts.x = _size.x;\n\t\t\t\ts.y = (float)int(\n\t\t\t\t\t_size.y * children[0]->size.y / (children[0]->size.y + children[1]->size.y));\n\t\t\t\tif (s.y < children[0]->getMinSize().y)\n\t\t\t\t{\n\t\t\t\t\ts.y = children[0]->getMinSize().y;\n\t\t\t\t}\n\t\t\t\telse if (_size.y - s.y < children[1]->getMinSize().y)\n\t\t\t\t{\n\t\t\t\t\ts.y = _size.y - children[1]->getMinSize().y;\n\t\t\t\t}\n\t\t\t\tchildren[0]->setPosSize(_pos, s);\n\n\t\t\t\ts.y = _size.y - children[0]->size.y;\n\t\t\t\tImVec2 p = _pos;\n\t\t\t\tp.y += children[0]->size.y;\n\t\t\t\tchildren[1]->setPosSize(p, s);\n\t\t\t}\n\t\t}\n\n\n\t\tvoid setPosSize(const ImVec2& _pos, const ImVec2& _size)\n\t\t{\n\t\t\tsize = _size;\n\t\t\tpos = _pos;\n\t\t\tfor (Dock* tmp = prev_tab; tmp; tmp = tmp->prev_tab)\n\t\t\t{\n\t\t\t\ttmp->size = _size;\n\t\t\t\ttmp->pos = _pos;\n\t\t\t}\n\t\t\tfor (Dock* tmp = next_tab; tmp; tmp = tmp->next_tab)\n\t\t\t{\n\t\t\t\ttmp->size = _size;\n\t\t\t\ttmp->pos = _pos;\n\t\t\t}\n\n\t\t\tif (!isContainer()) return;\n\t\t\tsetChildrenPosSize(_pos, _size);\n\t\t}\n\n\n\t\tchar* label;\n\t\tImU32 id;\n\t\tDock* next_tab;\n\t\tDock* prev_tab;\n\t\tDock* children[2];\n\t\tDock* parent;\n\t\tbool active;\n\t\tImVec2 pos;\n\t\tImVec2 size;\n\t\tStatus_ status;\n\t\tint last_frame;\n\t\tint invalid_frames;\n\t\tchar location[16];\n\t\tbool opened;\n\t\tbool first;\n\t};\n\n\n\tImVector<Dock*> m_docks;\n\tImVec2 m_drag_offset;\n\tDock* m_current = nullptr;\n\tint m_last_frame = 0;\n\tEndAction_ m_end_action;\n\n\n\t~DockContext() {}\n\n\n\tDock& getDock(const char* label, bool opened)\n\t{\n\t\tImU32 id = ImHash(label, 0);\n\t\tfor (int i = 0; i < m_docks.size(); ++i)\n\t\t{\n\t\t\tif (m_docks[i]->id == id) return *m_docks[i];\n\t\t}\n\n\t\tDock* new_dock = (Dock*)MemAlloc(sizeof(Dock));\n\t\tIM_PLACEMENT_NEW(new_dock) Dock();\n\t\tm_docks.push_back(new_dock);\n\t\tnew_dock->label = ImStrdup(label);\n\t\tIM_ASSERT(new_dock->label);\n\t\tnew_dock->id = id;\n\t\tnew_dock->setActive();\n\t\tnew_dock->status = Status_Float;\n\t\tnew_dock->pos = ImVec2(0, 0);\n\t\tnew_dock->size = GetIO().DisplaySize;\n\t\tnew_dock->opened = opened;\n\t\tnew_dock->first = true;\n\t\tnew_dock->last_frame = 0;\n\t\tnew_dock->invalid_frames = 0;\n\t\tnew_dock->location[0] = 0;\n\t\treturn *new_dock;\n\t}\n\n\n\tvoid putInBackground()\n\t{\n\t\tImGuiWindow* win = GetCurrentWindow();\n\t\tImGuiContext& g = *GImGui;\n\t\tif (g.Windows[0] == win) return;\n\n\t\tfor (int i = 0; i < g.Windows.Size; i++)\n\t\t{\n\t\t\tif (g.Windows[i] == win)\n\t\t\t{\n\t\t\t\tfor (int j = i - 1; j >= 0; --j)\n\t\t\t\t{\n\t\t\t\t\tg.Windows[j + 1] = g.Windows[j];\n\t\t\t\t}\n\t\t\t\tg.Windows[0] = win;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\n\tvoid splits()\n\t{\n\t\tif (GetFrameCount() == m_last_frame) return;\n\t\tm_last_frame = GetFrameCount();\n\n\t\tputInBackground();\n\n\t\tImU32 color = GetColorU32(ImGuiCol_Button);\n\t\tImU32 color_hovered = GetColorU32(ImGuiCol_ButtonHovered);\n\t\tImDrawList* draw_list = GetWindowDrawList();\n\t\tImGuiIO& io = GetIO();\n\t\tfor (int i = 0; i < m_docks.size(); ++i)\n\t\t{\n\t\t\tDock& dock = *m_docks[i];\n\t\t\tif (!dock.isContainer()) continue;\n\n\t\t\tPushID(i);\n\t\t\tif (!IsMouseDown(0)) dock.status = Status_Docked;\n\n\t\t\tImVec2 size = dock.children[0]->size;\n\t\t\tImVec2 dsize(0, 0);\n\t\t\tSetCursorScreenPos(dock.children[1]->pos);\n\t\t\tImVec2 min_size0 = dock.children[0]->getMinSize();\n\t\t\tImVec2 min_size1 = dock.children[1]->getMinSize();\n\t\t\tif (dock.isHorizontal())\n\t\t\t{\n\t\t\t\tInvisibleButton(\"split\", ImVec2(3, dock.size.y));\n\t\t\t\tif (dock.status == Status_Dragged) dsize.x = io.MouseDelta.x;\n\t\t\t\tdsize.x = -ImMin(-dsize.x, dock.children[0]->size.x - min_size0.x);\n\t\t\t\tdsize.x = ImMin(dsize.x, dock.children[1]->size.x - min_size1.x);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tInvisibleButton(\"split\", ImVec2(dock.size.x, 3));\n\t\t\t\tif (dock.status == Status_Dragged) dsize.y = io.MouseDelta.y;\n\t\t\t\tdsize.y = -ImMin(-dsize.y, dock.children[0]->size.y - min_size0.y);\n\t\t\t\tdsize.y = ImMin(dsize.y, dock.children[1]->size.y - min_size1.y);\n\t\t\t}\n\t\t\tImVec2 new_size0 = dock.children[0]->size + dsize;\n\t\t\tImVec2 new_size1 = dock.children[1]->size - dsize;\n\t\t\tImVec2 new_pos1 = dock.children[1]->pos + dsize;\n\t\t\tdock.children[0]->setPosSize(dock.children[0]->pos, new_size0);\n\t\t\tdock.children[1]->setPosSize(new_pos1, new_size1);\n\n\t\t\tif (IsItemHovered() && IsMouseClicked(0))\n\t\t\t{\n\t\t\t\tdock.status = Status_Dragged;\n\t\t\t}\n\n\t\t\tdraw_list->AddRectFilled(\n\t\t\t\tGetItemRectMin(), GetItemRectMax(), IsItemHovered() ? color_hovered : color);\n\t\t\tPopID();\n\t\t}\n\t}\n\n\n\tvoid checkNonexistent()\n\t{\n\t\tint frame_limit = ImMax(0, ImGui::GetFrameCount() - 2);\n\t\tfor (Dock* dock : m_docks)\n\t\t{\n\t\t\tif (dock->isContainer()) continue;\n\t\t\tif (dock->status == Status_Float) continue;\n\t\t\tif (dock->last_frame < frame_limit)\n\t\t\t{\n\t\t\t\t++dock->invalid_frames;\n\t\t\t\tif (dock->invalid_frames > 2)\n\t\t\t\t{\n\t\t\t\t\tdoUndock(*dock);\n\t\t\t\t\tdock->status = Status_Float;\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tdock->invalid_frames = 0;\n\t\t}\n\t}\n\n\n\tvoid beginPanel()\n\t{\n\t\tImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize |\n\t\t\t\t\t\t\t\t ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse |\n\t\t\t\t\t\t\t\t ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoScrollbar |\n\t\t\t\t\t\t\t\t ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_ShowBorders | \n\t\t\t\t\t\t\t\t ImGuiWindowFlags_NoBringToFrontOnFocus;\n\t\tDock* root = getRootDock();\n\t\tif (root)\n\t\t{\n\t\t\tSetNextWindowPos(root->pos);\n\t\t\tSetNextWindowSize(root->size);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tSetNextWindowPos(ImVec2(0, 0));\n\t\t\tSetNextWindowSize(GetIO().DisplaySize);\n\t\t}\n\n\t\t//ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0);\n\t\tBegin(\"###DockPanel\", nullptr, flags);\n\t\tsplits();\n\n\t\tcheckNonexistent();\n\t}\n\n\n\tvoid endPanel()\n\t{\n\t\tEnd();\n\t\t//ImGui::PopStyleVar();\n\t}\n\n\n\tDock* getDockAt(const ImVec2& pos) const\n\t{\n\t\tfor (int i = 0; i < m_docks.size(); ++i)\n\t\t{\n\t\t\tDock& dock = *m_docks[i];\n\t\t\tif (dock.isContainer()) continue;\n\t\t\tif (dock.status != Status_Docked) continue;\n\t\t\tif (IsMouseHoveringRect(dock.pos, dock.pos + dock.size, false))\n\t\t\t{\n\t\t\t\treturn &dock;\n\t\t\t}\n\t\t}\n\n\t\treturn nullptr;\n\t}\n\n\n\tstatic ImRect getDockedRect(const ImRect& rect, Slot_ dock_slot)\n\t{\n\t\tImVec2 half_size = rect.GetSize() * 0.5f;\n\t\tswitch (dock_slot)\n\t\t{\n\t\t\tdefault: return rect;\n\t\t\tcase Slot_Top: return ImRect(rect.Min, rect.Min + ImVec2(rect.Max.x, half_size.y));\n\t\t\tcase Slot_Right: return ImRect(rect.Min + ImVec2(half_size.x, 0), rect.Max);\n\t\t\tcase Slot_Bottom: return ImRect(rect.Min + ImVec2(0, half_size.y), rect.Max);\n\t\t\tcase Slot_Left: return ImRect(rect.Min, rect.Min + ImVec2(half_size.x, rect.Max.y));\n\t\t}\n\t}\n\n\n\tstatic ImRect getSlotRect(ImRect parent_rect, Slot_ dock_slot)\n\t{\n\t\tImVec2 size = parent_rect.Max - parent_rect.Min;\n\t\tImVec2 center = parent_rect.Min + size * 0.5f;\n\t\tswitch (dock_slot)\n\t\t{\n\t\t\tdefault: return ImRect(center - ImVec2(20, 20), center + ImVec2(20, 20));\n\t\t\tcase Slot_Top: return ImRect(center + ImVec2(-20, -50), center + ImVec2(20, -30));\n\t\t\tcase Slot_Right: return ImRect(center + ImVec2(30, -20), center + ImVec2(50, 20));\n\t\t\tcase Slot_Bottom: return ImRect(center + ImVec2(-20, +30), center + ImVec2(20, 50));\n\t\t\tcase Slot_Left: return ImRect(center + ImVec2(-50, -20), center + ImVec2(-30, 20));\n\t\t}\n\t}\n\n\n\tstatic ImRect getSlotRectOnBorder(ImRect parent_rect, Slot_ dock_slot)\n\t{\n\t\tImVec2 size = parent_rect.Max - parent_rect.Min;\n\t\tImVec2 center = parent_rect.Min + size * 0.5f;\n\t\tswitch (dock_slot)\n\t\t{\n\t\t\tcase Slot_Top:\n\t\t\t\treturn ImRect(ImVec2(center.x - 20, parent_rect.Min.y + 10),\n\t\t\t\t\tImVec2(center.x + 20, parent_rect.Min.y + 30));\n\t\t\tcase Slot_Left:\n\t\t\t\treturn ImRect(ImVec2(parent_rect.Min.x + 10, center.y - 20),\n\t\t\t\t\tImVec2(parent_rect.Min.x + 30, center.y + 20));\n\t\t\tcase Slot_Bottom:\n\t\t\t\treturn ImRect(ImVec2(center.x - 20, parent_rect.Max.y - 30),\n\t\t\t\t\tImVec2(center.x + 20, parent_rect.Max.y - 10));\n\t\t\tcase Slot_Right:\n\t\t\t\treturn ImRect(ImVec2(parent_rect.Max.x - 30, center.y - 20),\n\t\t\t\t\tImVec2(parent_rect.Max.x - 10, center.y + 20));\n\t\t\tdefault: IM_ASSERT(false);\n\t\t}\n\t\tIM_ASSERT(false);\n\t\treturn ImRect();\n\t}\n\n\n\tDock* getRootDock()\n\t{\n\t\tfor (int i = 0; i < m_docks.size(); ++i)\n\t\t{\n\t\t\tif (!m_docks[i]->parent &&\n\t\t\t\t(m_docks[i]->status == Status_Docked || m_docks[i]->children[0]))\n\t\t\t{\n\t\t\t\treturn m_docks[i];\n\t\t\t}\n\t\t}\n\t\treturn nullptr;\n\t}\n\n\n\tbool dockSlots(Dock& dock, Dock* dest_dock, const ImRect& rect, bool on_border)\n\t{\n\t\tImDrawList* canvas = GetWindowDrawList();\n\t\tImU32 color = GetColorU32(ImGuiCol_Button);\n\t\tImU32 color_hovered = GetColorU32(ImGuiCol_ButtonHovered);\n\t\tImVec2 mouse_pos = GetIO().MousePos;\n\t\tfor (int i = 0; i < (on_border ? 4 : 5); ++i)\n\t\t{\n\t\t\tImRect r =\n\t\t\t\ton_border ? getSlotRectOnBorder(rect, (Slot_)i) : getSlotRect(rect, (Slot_)i);\n\t\t\tbool hovered = r.Contains(mouse_pos);\n\t\t\tcanvas->AddRectFilled(r.Min, r.Max, hovered ? color_hovered : color);\n\t\t\tif (!hovered) continue;\n\n\t\t\tif (!IsMouseDown(0))\n\t\t\t{\n\t\t\t\tdoDock(dock, dest_dock ? dest_dock : getRootDock(), (Slot_)i);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tImRect docked_rect = getDockedRect(rect, (Slot_)i);\n\t\t\tcanvas->AddRectFilled(docked_rect.Min, docked_rect.Max, GetColorU32(ImGuiCol_Button));\n\t\t}\n\t\treturn false;\n\t}\n\n\n\tvoid handleDrag(Dock& dock)\n\t{\n\t\tDock* dest_dock = getDockAt(GetIO().MousePos);\n\n\t\tBegin(\"##Overlay\",\n\t\t\tNULL,\n\t\t\tImVec2(0, 0),\n\t\t\t0.f,\n\t\t\tImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove |\n\t\t\t\tImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings |\n\t\t\t\tImGuiWindowFlags_AlwaysAutoResize);\n\t\tImDrawList* canvas = GetWindowDrawList();\n\n\t\tcanvas->PushClipRectFullScreen();\n\n\t\tImU32 docked_color = GetColorU32(ImGuiCol_FrameBg);\n\t\tdocked_color = (docked_color & 0x00ffFFFF) | 0x80000000;\n\t\tdock.pos = GetIO().MousePos - m_drag_offset;\n\t\tif (dest_dock)\n\t\t{\n\t\t\tif (dockSlots(dock,\n\t\t\t\t\tdest_dock,\n\t\t\t\t\tImRect(dest_dock->pos, dest_dock->pos + dest_dock->size),\n\t\t\t\t\tfalse))\n\t\t\t{\n\t\t\t\tcanvas->PopClipRect();\n\t\t\t\tEnd();\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tif (dockSlots(dock, nullptr, ImRect(ImVec2(0, 0), GetIO().DisplaySize), true))\n\t\t{\n\t\t\tcanvas->PopClipRect();\n\t\t\tEnd();\n\t\t\treturn;\n\t\t}\n\t\tcanvas->AddRectFilled(dock.pos, dock.pos + dock.size, docked_color);\n\t\tcanvas->PopClipRect();\n\n\t\tif (!IsMouseDown(0))\n\t\t{\n\t\t\tdock.status = Status_Float;\n\t\t\tdock.location[0] = 0;\n\t\t\tdock.setActive();\n\t\t}\n\n\t\tEnd();\n\t}\n\n\n\tvoid fillLocation(Dock& dock)\n\t{\n\t\tif (dock.status == Status_Float) return;\n\t\tchar* c = dock.location;\n\t\tDock* tmp = &dock;\n\t\twhile (tmp->parent)\n\t\t{\n\t\t\t*c = getLocationCode(tmp);\n\t\t\ttmp = tmp->parent;\n\t\t\t++c;\n\t\t}\n\t\t*c = 0;\n\t}\n\n\n\tvoid doUndock(Dock& dock)\n\t{\n\t\tif (dock.prev_tab)\n\t\t\tdock.prev_tab->setActive();\n\t\telse if (dock.next_tab)\n\t\t\tdock.next_tab->setActive();\n\t\telse\n\t\t\tdock.active = false;\n\t\tDock* container = dock.parent;\n\n\t\tif (container)\n\t\t{\n\t\t\tDock& sibling = dock.getSibling();\n\t\t\tif (container->children[0] == &dock)\n\t\t\t{\n\t\t\t\tcontainer->children[0] = dock.next_tab;\n\t\t\t}\n\t\t\telse if (container->children[1] == &dock)\n\t\t\t{\n\t\t\t\tcontainer->children[1] = dock.next_tab;\n\t\t\t}\n\n\t\t\tbool remove_container = !container->children[0] || !container->children[1];\n\t\t\tif (remove_container)\n\t\t\t{\n\t\t\t\tif (container->parent)\n\t\t\t\t{\n\t\t\t\t\tDock*& child = container->parent->children[0] == container\n\t\t\t\t\t\t\t\t\t   ? container->parent->children[0]\n\t\t\t\t\t\t\t\t\t   : container->parent->children[1];\n\t\t\t\t\tchild = &sibling;\n\t\t\t\t\tchild->setPosSize(container->pos, container->size);\n\t\t\t\t\tchild->setParent(container->parent);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif (container->children[0])\n\t\t\t\t\t{\n\t\t\t\t\t\tcontainer->children[0]->setParent(nullptr);\n\t\t\t\t\t\tcontainer->children[0]->setPosSize(container->pos, container->size);\n\t\t\t\t\t}\n\t\t\t\t\tif (container->children[1])\n\t\t\t\t\t{\n\t\t\t\t\t\tcontainer->children[1]->setParent(nullptr);\n\t\t\t\t\t\tcontainer->children[1]->setPosSize(container->pos, container->size);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor (int i = 0; i < m_docks.size(); ++i)\n\t\t\t\t{\n\t\t\t\t\tif (m_docks[i] == container)\n\t\t\t\t\t{\n\t\t\t\t\t\tm_docks.erase(m_docks.begin() + i);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontainer->~Dock();\n\t\t\t\tMemFree(container);\n\t\t\t}\n\t\t}\n\t\tif (dock.prev_tab) dock.prev_tab->next_tab = dock.next_tab;\n\t\tif (dock.next_tab) dock.next_tab->prev_tab = dock.prev_tab;\n\t\tdock.parent = nullptr;\n\t\tdock.prev_tab = dock.next_tab = nullptr;\n\t}\n\n\n\tvoid drawTabbarListButton(Dock& dock)\n\t{\n\t\tif (!dock.next_tab) return;\n\n\t\tImDrawList* draw_list = GetWindowDrawList();\n\t\tif (InvisibleButton(\"list\", ImVec2(16, 16)))\n\t\t{\n\t\t\tOpenPopup(\"tab_list_popup\");\n\t\t}\n\t\tif (BeginPopup(\"tab_list_popup\"))\n\t\t{\n\t\t\tDock* tmp = &dock;\n\t\t\twhile (tmp)\n\t\t\t{\n\t\t\t\tbool dummy = false;\n\t\t\t\tif (Selectable(tmp->label, &dummy))\n\t\t\t\t{\n\t\t\t\t\ttmp->setActive();\n\t\t\t\t}\n\t\t\t\ttmp = tmp->next_tab;\n\t\t\t}\n\t\t\tEndPopup();\n\t\t}\n\n\t\tbool hovered = IsItemHovered();\n\t\tImVec2 min = GetItemRectMin();\n\t\tImVec2 max = GetItemRectMax();\n\t\tImVec2 center = (min + max) * 0.5f;\n\t\tImU32 text_color = GetColorU32(ImGuiCol_Text);\n\t\tImU32 color_active = GetColorU32(ImGuiCol_FrameBgActive);\n\t\tdraw_list->AddRectFilled(ImVec2(center.x - 4, min.y + 3),\n\t\t\tImVec2(center.x + 4, min.y + 5),\n\t\t\thovered ? color_active : text_color);\n\t\tdraw_list->AddTriangleFilled(ImVec2(center.x - 4, min.y + 7),\n\t\t\tImVec2(center.x + 4, min.y + 7),\n\t\t\tImVec2(center.x, min.y + 12),\n\t\t\thovered ? color_active : text_color);\n\t}\n\n\n\tbool tabbar(Dock& dock, bool close_button)\n\t{\n\t\tfloat tabbar_height = 2 * GetTextLineHeightWithSpacing();\n\t\tImVec2 size(dock.size.x, tabbar_height);\n\t\tbool tab_closed = false;\n\n\t\tSetCursorScreenPos(dock.pos);\n\t\tchar tmp[20];\n\t\tImFormatString(tmp, IM_ARRAYSIZE(tmp), \"tabs%d\", (int)dock.id);\n\t\tif (BeginChild(tmp, size, true))\n\t\t{\n\t\t\tDock* dock_tab = &dock;\n\n\t\t\tImDrawList* draw_list = GetWindowDrawList();\n\t\t\tImU32 color = GetColorU32(ImGuiCol_WindowBg);//ImGuiCol_FrameBg);\n\t\t\tImU32 color_active = GetColorU32(ImGuiCol_WindowBg);//ImGuiCol_FrameBgActive);\n\t\t\tImU32 color_hovered = GetColorU32(ImGuiCol_FrameBgActive);//ImGuiCol_FrameBgHovered);\n\t\t\tImU32 text_color = GetColorU32(ImGuiCol_Text);\n\t\t\tfloat line_height = GetTextLineHeightWithSpacing();\n\t\t\tfloat tab_base;\n\n\t\t\tdrawTabbarListButton(dock);\n\n\t\t\twhile (dock_tab)\n\t\t\t{\n\t\t\t\tSameLine(0, 15);\n\n\t\t\t\tconst char* text_end = FindRenderedTextEnd(dock_tab->label);\n\t\t\t\tImVec2 size(CalcTextSize(dock_tab->label, text_end).x, line_height);\n\t\t\t\tif (InvisibleButton(dock_tab->label, size))\n\t\t\t\t{\n\t\t\t\t\tdock_tab->setActive();\n\t\t\t\t}\n\n\t\t\t\tif (IsItemActive() && IsMouseDragging())\n\t\t\t\t{\n\t\t\t\t\tm_drag_offset = GetMousePos() - dock_tab->pos;\n\t\t\t\t\tdoUndock(*dock_tab);\n\t\t\t\t\tdock_tab->status = Status_Dragged;\n\t\t\t\t}\n\n\t\t\t\tbool hovered = IsItemHovered();\n\t\t\t\tImVec2 pos = GetItemRectMin();\n\t\t\t\tif (dock_tab->active && close_button)\n\t\t\t\t{\n\t\t\t\t\tsize.x += 16 + GetStyle().ItemSpacing.x;\n\t\t\t\t\tSameLine();\n\t\t\t\t\ttab_closed = InvisibleButton(\"close\", ImVec2(16, 16));\n\t\t\t\t\tImVec2 center = (GetItemRectMin() + GetItemRectMax()) * 0.5f;\n\t\t\t\t\tdraw_list->AddLine(\n\t\t\t\t\t\tcenter + ImVec2(-3.5f, -3.5f), center + ImVec2(3.5f, 3.5f), text_color);\n\t\t\t\t\tdraw_list->AddLine(\n\t\t\t\t\t\tcenter + ImVec2(3.5f, -3.5f), center + ImVec2(-3.5f, 3.5f), text_color);\n\t\t\t\t}\n\t\t\t\ttab_base = pos.y;\n\t\t\t\tImGuiStyle &style = GetStyle();\n\n\t\t\t\tdraw_list->PathClear();\n\t\t\t\tdraw_list->AddRectFilled( pos + ImVec2( -5, 0 ), pos + ImVec2( size.x + 5, size.y ), hovered ? color_hovered : (dock_tab->active ? color_active : color), style.FrameRounding, 1 | 2 );\n\t\t\t\tdraw_list->AddText( pos, text_color, dock_tab->label, text_end);\n\n\t\t\t\tdock_tab = dock_tab->next_tab;\n\t\t\t}\n\t\t\tImVec2 cp(dock.pos.x, tab_base + line_height);\n\t\t\tdraw_list->AddLine(cp, cp + ImVec2(dock.size.x, 0), color);\n\t\t}\n\t\tEndChild();\n\t\treturn tab_closed;\n\t}\n\n\n\tstatic void setDockPosSize(Dock& dest, Dock& dock, Slot_ dock_slot, Dock& container)\n\t{\n\t\tIM_ASSERT(!dock.prev_tab && !dock.next_tab && !dock.children[0] && !dock.children[1]);\n\n\t\tdest.pos = container.pos;\n\t\tdest.size = container.size;\n\t\tdock.pos = container.pos;\n\t\tdock.size = container.size;\n\n\t\tswitch (dock_slot)\n\t\t{\n\t\t\tcase Slot_Bottom:\n\t\t\t\tdest.size.y *= 0.5f;\n\t\t\t\tdock.size.y *= 0.5f;\n\t\t\t\tdock.pos.y += dest.size.y;\n\t\t\t\tbreak;\n\t\t\tcase Slot_Right:\n\t\t\t\tdest.size.x *= 0.5f;\n\t\t\t\tdock.size.x *= 0.5f;\n\t\t\t\tdock.pos.x += dest.size.x;\n\t\t\t\tbreak;\n\t\t\tcase Slot_Left:\n\t\t\t\tdest.size.x *= 0.5f;\n\t\t\t\tdock.size.x *= 0.5f;\n\t\t\t\tdest.pos.x += dock.size.x;\n\t\t\t\tbreak;\n\t\t\tcase Slot_Top:\n\t\t\t\tdest.size.y *= 0.5f;\n\t\t\t\tdock.size.y *= 0.5f;\n\t\t\t\tdest.pos.y += dock.size.y;\n\t\t\t\tbreak;\n\t\t\tdefault: IM_ASSERT(false); break;\n\t\t}\n\t\tdest.setPosSize(dest.pos, dest.size);\n\n\t\tif (container.children[1]->pos.x < container.children[0]->pos.x ||\n\t\t\tcontainer.children[1]->pos.y < container.children[0]->pos.y)\n\t\t{\n\t\t\tDock* tmp = container.children[0];\n\t\t\tcontainer.children[0] = container.children[1];\n\t\t\tcontainer.children[1] = tmp;\n\t\t}\n\t}\n\n\n\tvoid doDock(Dock& dock, Dock* dest, Slot_ dock_slot)\n\t{\n\t\tIM_ASSERT(!dock.parent);\n\t\tif (!dest)\n\t\t{\n\t\t\tdock.status = Status_Docked;\n\t\t\tdock.setPosSize(ImVec2(0, 0), GetIO().DisplaySize);\n\t\t}\n\t\telse if (dock_slot == Slot_Tab)\n\t\t{\n\t\t\tDock* tmp = dest;\n\t\t\twhile (tmp->next_tab)\n\t\t\t{\n\t\t\t\ttmp = tmp->next_tab;\n\t\t\t}\n\n\t\t\ttmp->next_tab = &dock;\n\t\t\tdock.prev_tab = tmp;\n\t\t\tdock.size = tmp->size;\n\t\t\tdock.pos = tmp->pos;\n\t\t\tdock.parent = dest->parent;\n\t\t\tdock.status = Status_Docked;\n\t\t}\n\t\telse if (dock_slot == Slot_None)\n\t\t{\n\t\t\tdock.status = Status_Float;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tDock* container = (Dock*)MemAlloc(sizeof(Dock));\n\t\t\tIM_PLACEMENT_NEW(container) Dock();\n\t\t\tm_docks.push_back(container);\n\t\t\tcontainer->children[0] = &dest->getFirstTab();\n\t\t\tcontainer->children[1] = &dock;\n\t\t\tcontainer->next_tab = nullptr;\n\t\t\tcontainer->prev_tab = nullptr;\n\t\t\tcontainer->parent = dest->parent;\n\t\t\tcontainer->size = dest->size;\n\t\t\tcontainer->pos = dest->pos;\n\t\t\tcontainer->status = Status_Docked;\n\t\t\tcontainer->label = ImStrdup(\"\");\n\n\t\t\tif (!dest->parent)\n\t\t\t{\n\t\t\t}\n\t\t\telse if (&dest->getFirstTab() == dest->parent->children[0])\n\t\t\t{\n\t\t\t\tdest->parent->children[0] = container;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tdest->parent->children[1] = container;\n\t\t\t}\n\n\t\t\tdest->setParent(container);\n\t\t\tdock.parent = container;\n\t\t\tdock.status = Status_Docked;\n\n\t\t\tsetDockPosSize(*dest, dock, dock_slot, *container);\n\t\t}\n\t\tdock.setActive();\n\t}\n\n\n\tvoid rootDock(const ImVec2& pos, const ImVec2& size)\n\t{\n\t\tDock* root = getRootDock();\n\t\tif (!root) return;\n\n\t\tImVec2 min_size = root->getMinSize();\n\t\tImVec2 requested_size = size;\n\t\troot->setPosSize(pos, ImMax(min_size, requested_size));\n\t}\n\n\n\tvoid setDockActive()\n\t{\n\t\tIM_ASSERT(m_current);\n\t\tif (m_current) m_current->setActive();\n\t}\n\n\n\tstatic Slot_ getSlotFromLocationCode(char code)\n\t{\n\t\tswitch (code)\n\t\t{\n\t\t\tcase '1': return Slot_Left;\n\t\t\tcase '2': return Slot_Top;\n\t\t\tcase '3': return Slot_Bottom;\n\t\t\tdefault: return Slot_Right;\n\t\t}\n\t}\n\n\n\tstatic char getLocationCode(Dock* dock)\n\t{\n\t\tif (!dock) return '0';\n\n\t\tif (dock->parent->isHorizontal())\n\t\t{\n\t\t\tif (dock->pos.x < dock->parent->children[0]->pos.x) return '1';\n\t\t\tif (dock->pos.x < dock->parent->children[1]->pos.x) return '1';\n\t\t\treturn '0';\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (dock->pos.y < dock->parent->children[0]->pos.y) return '2';\n\t\t\tif (dock->pos.y < dock->parent->children[1]->pos.y) return '2';\n\t\t\treturn '3';\n\t\t}\n\t}\n\n\n\tvoid tryDockToStoredLocation(Dock& dock)\n\t{\n\t\tif (dock.status == Status_Docked) return;\n\t\tif (dock.location[0] == 0) return;\n\t\t\n\t\tDock* tmp = getRootDock();\n\t\tif (!tmp) return;\n\n\t\tDock* prev = nullptr;\n\t\tchar* c = dock.location + strlen(dock.location) - 1;\n\t\twhile (c >= dock.location && tmp)\n\t\t{\n\t\t\tprev = tmp;\n\t\t\ttmp = *c == getLocationCode(tmp->children[0]) ? tmp->children[0] : tmp->children[1];\n\t\t\tif(tmp) --c;\n\t\t}\n\t\tif (tmp && tmp->children[0]) tmp = tmp->parent;\n\t\tdoDock(dock, tmp ? tmp : prev, tmp && !tmp->children[0] ? Slot_Tab : getSlotFromLocationCode(*c));\n\t}\n\n\n\tbool begin(const char* label, bool* opened, ImGuiWindowFlags extra_flags)\n\t{\n\t\tDock& dock = getDock(label, !opened || *opened);\n\t\tif (!dock.opened && (!opened || *opened)) tryDockToStoredLocation(dock);\n\t\tdock.last_frame = ImGui::GetFrameCount();\n\t\tif (strcmp(dock.label, label) != 0)\n\t\t{\n\t\t\tMemFree(dock.label);\n\t\t\tdock.label = ImStrdup(label);\n\t\t}\n\t\t\n\t\tm_end_action = EndAction_None;\n\t\tif( dock.first ) {\n\t\t\tdoDock( dock, getRootDock(), Slot_Tab );\n\t\t}\n\t\tif (dock.first && opened) *opened = dock.opened;\n\t\tdock.first = false;\n\t\tif (opened && !*opened)\n\t\t{\n\t\t\tif (dock.status != Status_Float)\n\t\t\t{\n\t\t\t\tfillLocation(dock);\n\t\t\t\tdoUndock(dock);\n\t\t\t\tdock.status = Status_Float;\n\t\t\t}\n\t\t\tdock.opened = false;\n\t\t\treturn false;\n\t\t}\n\t\tdock.opened = true;\n\n\t\tm_end_action = EndAction_Panel;\n\t\tbeginPanel();\n\n\t\tm_current = &dock;\n\t\tif (dock.status == Status_Dragged) handleDrag(dock);\n\n\t\tbool is_float = dock.status == Status_Float;\n\n\t\tif (is_float)\n\t\t{\n\t\t\tSetNextWindowPos(dock.pos);\n\t\t\tSetNextWindowSize(dock.size);\n\t\t\tbool ret = Begin(label,\n\t\t\t\topened,\n\t\t\t\tdock.size,\n\t\t\t\t-1.0f,\n\t\t\t\tImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_ShowBorders | extra_flags);\n\t\t\tm_end_action = EndAction_End;\n\t\t\tdock.pos = GetWindowPos();\n\t\t\tdock.size = GetWindowSize();\n\n\t\t\tImGuiContext& g = *GImGui;\n\n\t\t\tif (g.ActiveId == GetCurrentWindow()->MoveId && g.IO.MouseDown[0])\n\t\t\t{\n\t\t\t\tm_drag_offset = GetMousePos() - dock.pos;\n\t\t\t\tdoUndock(dock);\n\t\t\t\tdock.status = Status_Dragged;\n\t\t\t}\n\t\t\treturn ret;\n\t\t}\n\n\t\tif (!dock.active && dock.status != Status_Dragged) return false;\n\n\t\tm_end_action = EndAction_EndChild;\n\n\t\tPushStyleColor(ImGuiCol_Border, ImVec4(0, 0, 0, 0));\n\t\tPushStyleColor(ImGuiCol_BorderShadow, ImVec4(0, 0, 0, 0));\n\t\tfloat tabbar_height = GetTextLineHeightWithSpacing();\n\t\tif (tabbar(dock.getFirstTab(), opened != nullptr))\n\t\t{\n\t\t\tfillLocation(dock);\n\t\t\t*opened = false;\n\t\t}\n\t\tImVec2 pos = dock.pos;\n\t\tImVec2 size = dock.size;\n\t\tpos.y += tabbar_height + GetStyle().WindowPadding.y;\n\t\tsize.y -= tabbar_height + GetStyle().WindowPadding.y;\n\n\t\tSetCursorScreenPos(pos);\n\t\tImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize |\n\t\t\t\t\t\t\t\t ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse |\n\t\t\t\t\t\t\t\t ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoBringToFrontOnFocus |\n\t\t\t\t\t\t\t\t extra_flags;\n\t\tchar tmp[256];\n\t\tstrcpy(tmp, label);\n\t\tstrcat(tmp, \"_docked\"); // to avoid https://github.com/ocornut/imgui/issues/713\n\t\tbool ret = BeginChild(tmp, size, true, flags);\n\t\tPopStyleColor();\n\t\tPopStyleColor();\n\t\treturn ret;\n\t}\n\n\n\tvoid end()\n\t{\n\t\tif (m_end_action == EndAction_End)\n\t\t{\n\t\t\tEnd();\n\t\t}\n\t\telse if (m_end_action == EndAction_EndChild)\n\t\t{\n\t\t\tPushStyleColor(ImGuiCol_Border, ImVec4(0, 0, 0, 0));\n\t\t\tPushStyleColor(ImGuiCol_BorderShadow, ImVec4(0, 0, 0, 0));\n\t\t\tEndChild();\n\t\t\tPopStyleColor();\n\t\t\tPopStyleColor();\n\t\t}\n\t\tm_current = nullptr;\n\t\tif (m_end_action > EndAction_None) endPanel();\n\t}\n\n\n\tint getDockIndex(Dock* dock)\n\t{\n\t\tif (!dock) return -1;\n\n\t\tfor (int i = 0; i < m_docks.size(); ++i)\n\t\t{\n\t\t\tif (dock == m_docks[i]) return i;\n\t\t}\n\n\t\tIM_ASSERT(false);\n\t\treturn -1;\n\t}\n\n\t/*\n\tvoid save(Lumix::FS::OsFile& file)\n\t{\n\t\tfile << \"docks = {\\n\";\n\t\tfor (int i = 0; i < m_docks.size(); ++i)\n\t\t{\n\t\t\tDock& dock = *m_docks[i];\n\t\t\tfile << \"dock\" << (Lumix::uint64)&dock << \" = {\\n\";\n\t\t\tfile << \"index = \" << i << \",\\n\";\n\t\t\tfile << \"label = \\\"\" << dock.label << \"\\\",\\n\";\n\t\t\tfile << \"x = \" << (int)dock.pos.x << \",\\n\";\n\t\t\tfile << \"y = \" << (int)dock.pos.y << \",\\n\";\n\t\t\tfile << \"location = \\\"\" << dock.location << \"\\\",\\n\";\n\t\t\tfile << \"size_x = \" << (int)dock.size.x << \",\\n\";\n\t\t\tfile << \"size_y = \" << (int)dock.size.y << \",\\n\";\n\t\t\tfile << \"status = \" << (int)dock.status << \",\\n\";\n\t\t\tfile << \"active = \" << (int)dock.active << \",\\n\";\n\t\t\tfile << \"opened = \" << (int)dock.opened << \",\\n\";\n\t\t\tfile << \"prev = \" << (int)getDockIndex(dock.prev_tab) << \",\\n\";\n\t\t\tfile << \"next = \" << (int)getDockIndex(dock.next_tab) << \",\\n\";\n\t\t\tfile << \"child0 = \" << (int)getDockIndex(dock.children[0]) << \",\\n\";\n\t\t\tfile << \"child1 = \" << (int)getDockIndex(dock.children[1]) << \",\\n\";\n\t\t\tfile << \"parent = \" << (int)getDockIndex(dock.parent) << \"\\n\";\n\t\t\tif (i < m_docks.size() - 1)\n\t\t\t\tfile << \"},\\n\";\n\t\t\telse\n\t\t\t\tfile << \"}\\n\";\n\t\t}\n\t\tfile << \"}\\n\";\n\t}\n\t\n\n\tDock* getDockByIndex(lua_Integer idx) { return idx < 0 ? nullptr : m_docks[(int)idx]; }\n\n\n\tvoid load(lua_State* L)\n\t{\n\t\tfor (int i = 0; i < m_docks.size(); ++i)\n\t\t{\n\t\t\tm_docks[i]->~Dock();\n\t\t\tMemFree(m_docks[i]);\n\t\t}\n\t\tm_docks.clear();\n\n\t\tif (lua_getglobal(L, \"docks\") == LUA_TTABLE)\n\t\t{\n\t\t\tlua_pushnil(L);\n\t\t\twhile (lua_next(L, -2) != 0)\n\t\t\t{\n\t\t\t\tDock* new_dock = (Dock*)MemAlloc(sizeof(Dock));\n\t\t\t\tm_docks.push_back(IM_PLACEMENT_NEW(new_dock) Dock());\n\t\t\t\tlua_pop(L, 1);\n\t\t\t}\n\t\t}\n\t\tlua_pop(L, 1);\n\n\t\tif (lua_getglobal(L, \"docks\") == LUA_TTABLE)\n\t\t{\n\t\t\tlua_pushnil(L);\n\t\t\twhile (lua_next(L, -2) != 0)\n\t\t\t{\n\t\t\t\tif (lua_istable(L, -1))\n\t\t\t\t{\n\t\t\t\t\tint idx = 0;\n\t\t\t\t\tif (lua_getfield(L, -1, \"index\") == LUA_TNUMBER)\n\t\t\t\t\t\tidx = (int)lua_tointeger(L, -1);\n\t\t\t\t\tDock& dock = *m_docks[idx];\n\t\t\t\t\tdock.last_frame = 0;\n\t\t\t\t\tdock.invalid_frames = 0;\n\t\t\t\t\tlua_pop(L, 1);\n\n\t\t\t\t\tif (lua_getfield(L, -1, \"label\") == LUA_TSTRING)\n\t\t\t\t\t{\n\t\t\t\t\t\tdock.label = ImStrdup(lua_tostring(L, -1));\n\t\t\t\t\t\tdock.id = ImHash(dock.label, 0);\n\t\t\t\t\t}\n\t\t\t\t\tlua_pop(L, 1);\n\n\t\t\t\t\tif (lua_getfield(L, -1, \"x\") == LUA_TNUMBER)\n\t\t\t\t\t\tdock.pos.x = (float)lua_tonumber(L, -1);\n\t\t\t\t\tif (lua_getfield(L, -2, \"y\") == LUA_TNUMBER)\n\t\t\t\t\t\tdock.pos.y = (float)lua_tonumber(L, -1);\n\t\t\t\t\tif (lua_getfield(L, -3, \"size_x\") == LUA_TNUMBER)\n\t\t\t\t\t\tdock.size.x = (float)lua_tonumber(L, -1);\n\t\t\t\t\tif (lua_getfield(L, -4, \"size_y\") == LUA_TNUMBER)\n\t\t\t\t\t\tdock.size.y = (float)lua_tonumber(L, -1);\n\t\t\t\t\tif (lua_getfield(L, -5, \"active\") == LUA_TNUMBER)\n\t\t\t\t\t\tdock.active = lua_tointeger(L, -1) != 0;\n\t\t\t\t\tif (lua_getfield(L, -6, \"opened\") == LUA_TNUMBER)\n\t\t\t\t\t\tdock.opened = lua_tointeger(L, -1) != 0;\n\t\t\t\t\tif (lua_getfield(L, -7, \"location\") == LUA_TSTRING)\n\t\t\t\t\t\tstrcpy(dock.location, lua_tostring(L, -1));\n\t\t\t\t\tif (lua_getfield(L, -8, \"status\") == LUA_TNUMBER)\n\t\t\t\t\t{\n\t\t\t\t\t\tdock.status = (Status_)lua_tointeger(L, -1);\n\t\t\t\t\t}\n\t\t\t\t\tlua_pop(L, 8);\n\n\t\t\t\t\tif (lua_getfield(L, -1, \"prev\") == LUA_TNUMBER)\n\t\t\t\t\t{\n\t\t\t\t\t\tdock.prev_tab = getDockByIndex(lua_tointeger(L, -1));\n\t\t\t\t\t}\n\t\t\t\t\tif (lua_getfield(L, -2, \"next\") == LUA_TNUMBER)\n\t\t\t\t\t{\n\t\t\t\t\t\tdock.next_tab = getDockByIndex(lua_tointeger(L, -1));\n\t\t\t\t\t}\n\t\t\t\t\tif (lua_getfield(L, -3, \"child0\") == LUA_TNUMBER)\n\t\t\t\t\t{\n\t\t\t\t\t\tdock.children[0] = getDockByIndex(lua_tointeger(L, -1));\n\t\t\t\t\t}\n\t\t\t\t\tif (lua_getfield(L, -4, \"child1\") == LUA_TNUMBER)\n\t\t\t\t\t{\n\t\t\t\t\t\tdock.children[1] = getDockByIndex(lua_tointeger(L, -1));\n\t\t\t\t\t}\n\t\t\t\t\tif (lua_getfield(L, -5, \"parent\") == LUA_TNUMBER)\n\t\t\t\t\t{\n\t\t\t\t\t\tdock.parent = getDockByIndex(lua_tointeger(L, -1));\n\t\t\t\t\t}\n\t\t\t\t\tlua_pop(L, 5);\n\t\t\t\t}\n\t\t\t\tlua_pop(L, 1);\n\t\t\t}\n\t\t}\n\t\tlua_pop(L, 1);\n\t}*/\n};\n\n\nstatic DockContext g_dock;\n\n\nvoid ShutdownDock()\n{\n\tfor (int i = 0; i < g_dock.m_docks.size(); ++i)\n\t{\n\t\tg_dock.m_docks[i]->~Dock();\n\t\tMemFree(g_dock.m_docks[i]);\n\t}\n\tg_dock.m_docks.clear();\n}\n\n\nvoid RootDock(const ImVec2& pos, const ImVec2& size)\n{\n\tg_dock.rootDock(pos, size);\n}\n\n\nvoid SetDockActive()\n{\n\tg_dock.setDockActive();\n}\n\n\nbool BeginDock(const char* label, bool* opened, ImGuiWindowFlags extra_flags)\n{\n\treturn g_dock.begin(label, opened, extra_flags);\n}\n\n\nvoid EndDock()\n{\n\tg_dock.end();\n}\n\n#endif\n\n}\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/CinderMarkdown.cpp",
    "content": "#include <cinder/Utilities.h>\r\n#include \"imgui/ImGui.h\"                // https://github.com/ocornut/imgui\r\n#include \"imgui_markdown/imgui_markdown.h\"       // https://github.com/juliettef/imgui_markdown\r\n#include \"IconFontCppHeaders/IconsFontAwesome5.h\"    // https://github.com/juliettef/IconFontCppHeaders\r\n\r\n\r\nusing namespace ci;\r\n\r\n/////\r\n\r\nvoid LinkCallback(ImGui::MarkdownLinkCallbackData data_);\r\ninline ImGui::MarkdownImageData ImageCallback(ImGui::MarkdownLinkCallbackData data_);\r\n\r\n// You can make your own Markdown function with your prefered string container and markdown config.\r\nstatic ImGui::MarkdownConfig mdConfig{ LinkCallback, ImageCallback, ICON_FA_LINK, { { NULL, true }, { NULL, true }, { NULL, false } } };\r\n\r\nvoid LinkCallback(ImGui::MarkdownLinkCallbackData data_)\r\n{\r\n    std::string url(data_.link, data_.linkLength);\r\n    launchWebBrowser(Url(url));\r\n}\r\n\r\ninline ImGui::MarkdownImageData ImageCallback(ImGui::MarkdownLinkCallbackData data_)\r\n{\r\n    // In your application you would load an image based on data_ input. Here we just use the imgui font texture.\r\n    ImTextureID image = ImGui::GetIO().Fonts->TexID;\r\n    ImGui::MarkdownImageData imageData{ true, false, image, ImVec2(40.0f, 20.0f) };\r\n    return imageData;\r\n}\r\n\r\nvoid LoadFonts(float fontSize_ = 12.0f)\r\n{\r\n    ImGuiIO& io = ImGui::GetIO();\r\n    io.Fonts->Clear();\r\n    // Base font\r\n    io.Fonts->AddFontFromFileTTF(\"myfont.ttf\", fontSize_);\r\n    // Bold headings H2 and H3\r\n    mdConfig.headingFormats[1].font = io.Fonts->AddFontFromFileTTF(\"myfont-bold.ttf\", fontSize_);\r\n    mdConfig.headingFormats[2].font = mdConfig.headingFormats[1].font;\r\n    // bold heading H1\r\n    float fontSizeH1 = fontSize_ * 1.1f;\r\n    mdConfig.headingFormats[0].font = io.Fonts->AddFontFromFileTTF(\"myfont-bold.ttf\", fontSizeH1);\r\n}\r\n\r\nvoid Markdown(const std::string& markdown_)\r\n{\r\n    // fonts for, respectively, headings H1, H2, H3 and beyond\r\n    ImGui::Markdown(markdown_.c_str(), markdown_.length(), mdConfig);\r\n}\r\n\r\nvoid MarkdownExample()\r\n{\r\n    const std::string markdownText = u8R\"(\r\n# H1 Header: Text and Links\r\nYou can add [links like this one to enkisoftware](https://www.enkisoftware.com/) and lines will wrap well.\r\n## H2 Header: indented text.\r\n  This text has an indent (two leading spaces).\r\n    This one has two.\r\n### H3 Header: Lists\r\n  * Unordered lists\r\n    * Lists can be indented with two extra spaces.\r\n  * Lists can have [links like this one to Avoyd](https://www.avoyd.com/)\r\n)\";\r\n    Markdown(markdownText);\r\n}\r\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/CinderRemoteImgui.cpp",
    "content": "#include <winsock2.h>\r\n#include \"CinderRemoteImgui.h\"\r\n#include <cinder/app/App.h>\r\n#include <cinder/CinderImGui.h>\r\n#include \"../ui/imgui_remote/imgui_remote.h\"\r\n\r\nextern void    ImGui_ImplOpenGL3_NewFrame();\r\nextern void    ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data);\r\n\r\nstatic bool sTriggerNewFrame = false;\r\n\r\nvoid createRemoteImgui(const char* address, int port)\r\n{\r\n    ImGui::RemoteInit(address, port);\r\n    sTriggerNewFrame = true;\r\n}\r\n\r\nvoid updateRemoteImgui(bool ENABLE_REMOTE_GUI)\r\n{\r\n    if (!ENABLE_REMOTE_GUI) return;\r\n\r\n    ImGui::RemoteUpdate();\r\n    ImGui::RemoteInput input;\r\n    if (ImGui::RemoteGetInput(input))\r\n    {\r\n        ImGuiIO& io = ImGui::GetIO();\r\n        for (int i = 0; i < 256; i++)\r\n            io.KeysDown[i] = input.KeysDown[i];\r\n        io.KeyCtrl = input.KeyCtrl;\r\n        io.KeyShift = input.KeyShift;\r\n        io.MousePos = input.MousePos;\r\n        io.MouseDown[0] = (input.MouseButtons & 1);\r\n        io.MouseDown[1] = (input.MouseButtons & 2) != 0;\r\n        io.MouseWheel += input.MouseWheelDelta;\r\n        // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array.\r\n        io.KeyMap[ImGuiKey_Tab] = ImGuiKey_Tab;\r\n        io.KeyMap[ImGuiKey_LeftArrow] = ImGuiKey_LeftArrow;\r\n        io.KeyMap[ImGuiKey_RightArrow] = ImGuiKey_RightArrow;\r\n        io.KeyMap[ImGuiKey_UpArrow] = ImGuiKey_UpArrow;\r\n        io.KeyMap[ImGuiKey_DownArrow] = ImGuiKey_DownArrow;\r\n        io.KeyMap[ImGuiKey_Home] = ImGuiKey_Home;\r\n        io.KeyMap[ImGuiKey_End] = ImGuiKey_End;\r\n        io.KeyMap[ImGuiKey_Delete] = ImGuiKey_Delete;\r\n        io.KeyMap[ImGuiKey_Backspace] = ImGuiKey_Backspace;\r\n        io.KeyMap[ImGuiKey_Enter] = 13;\r\n        io.KeyMap[ImGuiKey_Escape] = 27;\r\n        io.KeyMap[ImGuiKey_A] = 'a';\r\n        io.KeyMap[ImGuiKey_C] = 'c';\r\n        io.KeyMap[ImGuiKey_V] = 'v';\r\n        io.KeyMap[ImGuiKey_X] = 'x';\r\n        io.KeyMap[ImGuiKey_Y] = 'y';\r\n        io.KeyMap[ImGuiKey_Z] = 'z';\r\n    }\r\n}\r\n\r\n\r\n\r\nvoid ImGui_ImplCinder_NewFrameGuard(const ci::app::WindowRef& window) {\r\n    if (!sTriggerNewFrame)\r\n        return;\r\n\r\n    ImGui_ImplOpenGL3_NewFrame();\r\n\r\n    ImGuiIO& io = ImGui::GetIO();\r\n    IM_ASSERT(io.Fonts->IsBuilt()); // Font atlas needs to be built, call renderer _NewFrame() function e.g. ImGui_ImplOpenGL3_NewFrame() \r\n\r\n    // Setup display size\r\n    io.DisplaySize = ci::app::toPixels(window->getSize());\r\n\r\n    // Setup time step\r\n    static double g_Time = 0.0f;\r\n    double current_time = ci::app::getElapsedSeconds();\r\n    io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f / 60.0f);\r\n    g_Time = current_time;\r\n\r\n    ImGui::NewFrame();\r\n\r\n    sTriggerNewFrame = false;\r\n}\r\n\r\nvoid ImGui_ImplCinder_PostDraw(bool ENABLE_REMOTE_GUI, bool ENABLE_LOCAL_GUI)\r\n{\r\n    ImGui::Render();\r\n    auto draw_data = ImGui::GetDrawData();\r\n    if (ENABLE_REMOTE_GUI)\r\n        ImGui::RemoteDraw(draw_data->CmdLists, draw_data->CmdListsCount);\r\n    if (ENABLE_LOCAL_GUI)\r\n        ImGui_ImplOpenGL3_RenderDrawData(draw_data);\r\n    sTriggerNewFrame = true;\r\n}\r\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/DearLogger.cpp",
    "content": "#include \"DearLogger.h\"\r\n\r\nnamespace ImGui\r\n{\r\n    DearLogger::DearLogger()\r\n    {\r\n        AutoScroll = true;\r\n        ScrollToBottom = false;\r\n        Clear();\r\n    }\r\n\r\n    void    DearLogger::Clear()\r\n    {\r\n        Buf.clear();\r\n        LineOffsets.clear();\r\n        LineOffsets.push_back(0);\r\n    }\r\n\r\n    void    DearLogger::AddLog(const char* fmt, ...) IM_FMTARGS(2)\r\n    {\r\n        int old_size = Buf.size();\r\n        va_list args;\r\n        va_start(args, fmt);\r\n        Buf.appendfv(fmt, args);\r\n        va_end(args);\r\n        for (int new_size = Buf.size(); old_size < new_size; old_size++)\r\n            if (Buf[old_size] == '\\n')\r\n                LineOffsets.push_back(old_size + 1);\r\n        if (AutoScroll)\r\n            ScrollToBottom = true;\r\n    }\r\n\r\n    void DearLogger::write(const ci::log::Metadata& meta, const std::string& text)\r\n    {\r\n        AddLog(\"%s : %s\\n\", meta.toString().c_str(), text.c_str());\r\n    }\r\n\r\n    void   DearLogger::Draw(const char* title, bool* p_open)\r\n    {\r\n        if (!ImGui::Begin(title, p_open))\r\n        {\r\n            ImGui::End();\r\n            return;\r\n        }\r\n\r\n        // Options menu\r\n        if (ImGui::BeginPopup(\"Options\"))\r\n        {\r\n            if (ImGui::Checkbox(\"Auto-scroll\", &AutoScroll))\r\n                if (AutoScroll)\r\n                    ScrollToBottom = true;\r\n            ImGui::EndPopup();\r\n        }\r\n\r\n        // Main window\r\n        if (ImGui::Button(\"Options\"))\r\n            ImGui::OpenPopup(\"Options\");\r\n        ImGui::SameLine();\r\n        bool clear = ImGui::Button(\"Clear\");\r\n        ImGui::SameLine();\r\n        bool copy = ImGui::Button(\"Copy\");\r\n        ImGui::SameLine();\r\n        Filter.Draw(\"Filter\", -100.0f);\r\n\r\n        ImGui::Separator();\r\n        ImGui::BeginChild(\"scrolling\", ImVec2(0, 0), false, ImGuiWindowFlags_HorizontalScrollbar);\r\n\r\n        if (clear)\r\n            Clear();\r\n        if (copy)\r\n            ImGui::LogToClipboard();\r\n\r\n        ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0));\r\n        const char* buf = Buf.begin();\r\n        const char* buf_end = Buf.end();\r\n        if (Filter.IsActive())\r\n        {\r\n            // In this example we don't use the clipper when Filter is enabled.\r\n            // This is because we don't have a random access on the result on our filter.\r\n            // A real application processing logs with ten of thousands of entries may want to store the result of search/filter.\r\n            // especially if the filtering function is not trivial (e.g. reg-exp).\r\n            for (int line_no = 0; line_no < LineOffsets.Size; line_no++)\r\n            {\r\n                const char* line_start = buf + LineOffsets[line_no];\r\n                const char* line_end = (line_no + 1 < LineOffsets.Size) ? (buf + LineOffsets[line_no + 1] - 1) : buf_end;\r\n                if (Filter.PassFilter(line_start, line_end))\r\n                    ImGui::TextUnformatted(line_start, line_end);\r\n            }\r\n        }\r\n        else\r\n        {\r\n            // The simplest and easy way to display the entire buffer:\r\n            //   ImGui::TextUnformatted(buf_begin, buf_end);\r\n            // And it'll just work. TextUnformatted() has specialization for large blob of text and will fast-forward to skip non-visible lines.\r\n            // Here we instead demonstrate using the clipper to only process lines that are within the visible area.\r\n            // If you have tens of thousands of items and their processing cost is non-negligible, coarse clipping them on your side is recommended.\r\n            // Using ImGuiListClipper requires A) random access into your data, and B) items all being the  same height,\r\n            // both of which we can handle since we an array pointing to the beginning of each line of text.\r\n            // When using the filter (in the block of code above) we don't have random access into the data to display anymore, which is why we don't use the clipper.\r\n            // Storing or skimming through the search result would make it possible (and would be recommended if you want to search through tens of thousands of entries)\r\n            ImGuiListClipper clipper;\r\n            clipper.Begin(LineOffsets.Size);\r\n            while (clipper.Step())\r\n            {\r\n                for (int line_no = clipper.DisplayStart; line_no < clipper.DisplayEnd; line_no++)\r\n                {\r\n                    const char* line_start = buf + LineOffsets[line_no];\r\n                    const char* line_end = (line_no + 1 < LineOffsets.Size) ? (buf + LineOffsets[line_no + 1] - 1) : buf_end;\r\n                    ImGui::TextUnformatted(line_start, line_end);\r\n                }\r\n            }\r\n            clipper.End();\r\n        }\r\n        ImGui::PopStyleVar();\r\n\r\n        if (ScrollToBottom)\r\n            ImGui::SetScrollHereY(1.0f);\r\n        ScrollToBottom = false;\r\n        ImGui::EndChild();\r\n        ImGui::End();\r\n    }\r\n}\r\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/IconFontCppHeaders/IconsFontAwesome5.h",
    "content": "// Generated by https://github.com/juliettef/IconFontCppHeaders script GenerateIconFontCppHeaders.py for language C++11\n// from https://raw.githubusercontent.com/FortAwesome/Font-Awesome/master/metadata/icons.yml\n// for use with https://github.com/FortAwesome/Font-Awesome/blob/master/webfonts/fa-solid-900.ttf, https://github.com/FortAwesome/Font-Awesome/blob/master/webfonts/fa-regular-400.ttf, \n#pragma once\n\n#define FONT_ICON_FILE_NAME_FAR \"fa-regular-400.ttf\"\n#define FONT_ICON_FILE_NAME_FAS \"fa-solid-900.ttf\"\n\n#define ICON_MIN_FA 0xf000\n#define ICON_MAX_FA 0xf976\n#define ICON_FA_AD u8\"\\uf641\"\n#define ICON_FA_ADDRESS_BOOK u8\"\\uf2b9\"\n#define ICON_FA_ADDRESS_CARD u8\"\\uf2bb\"\n#define ICON_FA_ADJUST u8\"\\uf042\"\n#define ICON_FA_AIR_FRESHENER u8\"\\uf5d0\"\n#define ICON_FA_ALIGN_CENTER u8\"\\uf037\"\n#define ICON_FA_ALIGN_JUSTIFY u8\"\\uf039\"\n#define ICON_FA_ALIGN_LEFT u8\"\\uf036\"\n#define ICON_FA_ALIGN_RIGHT u8\"\\uf038\"\n#define ICON_FA_ALLERGIES u8\"\\uf461\"\n#define ICON_FA_AMBULANCE u8\"\\uf0f9\"\n#define ICON_FA_AMERICAN_SIGN_LANGUAGE_INTERPRETING u8\"\\uf2a3\"\n#define ICON_FA_ANCHOR u8\"\\uf13d\"\n#define ICON_FA_ANGLE_DOUBLE_DOWN u8\"\\uf103\"\n#define ICON_FA_ANGLE_DOUBLE_LEFT u8\"\\uf100\"\n#define ICON_FA_ANGLE_DOUBLE_RIGHT u8\"\\uf101\"\n#define ICON_FA_ANGLE_DOUBLE_UP u8\"\\uf102\"\n#define ICON_FA_ANGLE_DOWN u8\"\\uf107\"\n#define ICON_FA_ANGLE_LEFT u8\"\\uf104\"\n#define ICON_FA_ANGLE_RIGHT u8\"\\uf105\"\n#define ICON_FA_ANGLE_UP u8\"\\uf106\"\n#define ICON_FA_ANGRY u8\"\\uf556\"\n#define ICON_FA_ANKH u8\"\\uf644\"\n#define ICON_FA_APPLE_ALT u8\"\\uf5d1\"\n#define ICON_FA_ARCHIVE u8\"\\uf187\"\n#define ICON_FA_ARCHWAY u8\"\\uf557\"\n#define ICON_FA_ARROW_ALT_CIRCLE_DOWN u8\"\\uf358\"\n#define ICON_FA_ARROW_ALT_CIRCLE_LEFT u8\"\\uf359\"\n#define ICON_FA_ARROW_ALT_CIRCLE_RIGHT u8\"\\uf35a\"\n#define ICON_FA_ARROW_ALT_CIRCLE_UP u8\"\\uf35b\"\n#define ICON_FA_ARROW_CIRCLE_DOWN u8\"\\uf0ab\"\n#define ICON_FA_ARROW_CIRCLE_LEFT u8\"\\uf0a8\"\n#define ICON_FA_ARROW_CIRCLE_RIGHT u8\"\\uf0a9\"\n#define ICON_FA_ARROW_CIRCLE_UP u8\"\\uf0aa\"\n#define ICON_FA_ARROW_DOWN u8\"\\uf063\"\n#define ICON_FA_ARROW_LEFT u8\"\\uf060\"\n#define ICON_FA_ARROW_RIGHT u8\"\\uf061\"\n#define ICON_FA_ARROW_UP u8\"\\uf062\"\n#define ICON_FA_ARROWS_ALT u8\"\\uf0b2\"\n#define ICON_FA_ARROWS_ALT_H u8\"\\uf337\"\n#define ICON_FA_ARROWS_ALT_V u8\"\\uf338\"\n#define ICON_FA_ASSISTIVE_LISTENING_SYSTEMS u8\"\\uf2a2\"\n#define ICON_FA_ASTERISK u8\"\\uf069\"\n#define ICON_FA_AT u8\"\\uf1fa\"\n#define ICON_FA_ATLAS u8\"\\uf558\"\n#define ICON_FA_ATOM u8\"\\uf5d2\"\n#define ICON_FA_AUDIO_DESCRIPTION u8\"\\uf29e\"\n#define ICON_FA_AWARD u8\"\\uf559\"\n#define ICON_FA_BABY u8\"\\uf77c\"\n#define ICON_FA_BABY_CARRIAGE u8\"\\uf77d\"\n#define ICON_FA_BACKSPACE u8\"\\uf55a\"\n#define ICON_FA_BACKWARD u8\"\\uf04a\"\n#define ICON_FA_BACON u8\"\\uf7e5\"\n#define ICON_FA_BACTERIA u8\"\\uf959\"\n#define ICON_FA_BACTERIUM u8\"\\uf95a\"\n#define ICON_FA_BAHAI u8\"\\uf666\"\n#define ICON_FA_BALANCE_SCALE u8\"\\uf24e\"\n#define ICON_FA_BALANCE_SCALE_LEFT u8\"\\uf515\"\n#define ICON_FA_BALANCE_SCALE_RIGHT u8\"\\uf516\"\n#define ICON_FA_BAN u8\"\\uf05e\"\n#define ICON_FA_BAND_AID u8\"\\uf462\"\n#define ICON_FA_BARCODE u8\"\\uf02a\"\n#define ICON_FA_BARS u8\"\\uf0c9\"\n#define ICON_FA_BASEBALL_BALL u8\"\\uf433\"\n#define ICON_FA_BASKETBALL_BALL u8\"\\uf434\"\n#define ICON_FA_BATH u8\"\\uf2cd\"\n#define ICON_FA_BATTERY_EMPTY u8\"\\uf244\"\n#define ICON_FA_BATTERY_FULL u8\"\\uf240\"\n#define ICON_FA_BATTERY_HALF u8\"\\uf242\"\n#define ICON_FA_BATTERY_QUARTER u8\"\\uf243\"\n#define ICON_FA_BATTERY_THREE_QUARTERS u8\"\\uf241\"\n#define ICON_FA_BED u8\"\\uf236\"\n#define ICON_FA_BEER u8\"\\uf0fc\"\n#define ICON_FA_BELL u8\"\\uf0f3\"\n#define ICON_FA_BELL_SLASH u8\"\\uf1f6\"\n#define ICON_FA_BEZIER_CURVE u8\"\\uf55b\"\n#define ICON_FA_BIBLE u8\"\\uf647\"\n#define ICON_FA_BICYCLE u8\"\\uf206\"\n#define ICON_FA_BIKING u8\"\\uf84a\"\n#define ICON_FA_BINOCULARS u8\"\\uf1e5\"\n#define ICON_FA_BIOHAZARD u8\"\\uf780\"\n#define ICON_FA_BIRTHDAY_CAKE u8\"\\uf1fd\"\n#define ICON_FA_BLENDER u8\"\\uf517\"\n#define ICON_FA_BLENDER_PHONE u8\"\\uf6b6\"\n#define ICON_FA_BLIND u8\"\\uf29d\"\n#define ICON_FA_BLOG u8\"\\uf781\"\n#define ICON_FA_BOLD u8\"\\uf032\"\n#define ICON_FA_BOLT u8\"\\uf0e7\"\n#define ICON_FA_BOMB u8\"\\uf1e2\"\n#define ICON_FA_BONE u8\"\\uf5d7\"\n#define ICON_FA_BONG u8\"\\uf55c\"\n#define ICON_FA_BOOK u8\"\\uf02d\"\n#define ICON_FA_BOOK_DEAD u8\"\\uf6b7\"\n#define ICON_FA_BOOK_MEDICAL u8\"\\uf7e6\"\n#define ICON_FA_BOOK_OPEN u8\"\\uf518\"\n#define ICON_FA_BOOK_READER u8\"\\uf5da\"\n#define ICON_FA_BOOKMARK u8\"\\uf02e\"\n#define ICON_FA_BORDER_ALL u8\"\\uf84c\"\n#define ICON_FA_BORDER_NONE u8\"\\uf850\"\n#define ICON_FA_BORDER_STYLE u8\"\\uf853\"\n#define ICON_FA_BOWLING_BALL u8\"\\uf436\"\n#define ICON_FA_BOX u8\"\\uf466\"\n#define ICON_FA_BOX_OPEN u8\"\\uf49e\"\n#define ICON_FA_BOX_TISSUE u8\"\\uf95b\"\n#define ICON_FA_BOXES u8\"\\uf468\"\n#define ICON_FA_BRAILLE u8\"\\uf2a1\"\n#define ICON_FA_BRAIN u8\"\\uf5dc\"\n#define ICON_FA_BREAD_SLICE u8\"\\uf7ec\"\n#define ICON_FA_BRIEFCASE u8\"\\uf0b1\"\n#define ICON_FA_BRIEFCASE_MEDICAL u8\"\\uf469\"\n#define ICON_FA_BROADCAST_TOWER u8\"\\uf519\"\n#define ICON_FA_BROOM u8\"\\uf51a\"\n#define ICON_FA_BRUSH u8\"\\uf55d\"\n#define ICON_FA_BUG u8\"\\uf188\"\n#define ICON_FA_BUILDING u8\"\\uf1ad\"\n#define ICON_FA_BULLHORN u8\"\\uf0a1\"\n#define ICON_FA_BULLSEYE u8\"\\uf140\"\n#define ICON_FA_BURN u8\"\\uf46a\"\n#define ICON_FA_BUS u8\"\\uf207\"\n#define ICON_FA_BUS_ALT u8\"\\uf55e\"\n#define ICON_FA_BUSINESS_TIME u8\"\\uf64a\"\n#define ICON_FA_CALCULATOR u8\"\\uf1ec\"\n#define ICON_FA_CALENDAR u8\"\\uf133\"\n#define ICON_FA_CALENDAR_ALT u8\"\\uf073\"\n#define ICON_FA_CALENDAR_CHECK u8\"\\uf274\"\n#define ICON_FA_CALENDAR_DAY u8\"\\uf783\"\n#define ICON_FA_CALENDAR_MINUS u8\"\\uf272\"\n#define ICON_FA_CALENDAR_PLUS u8\"\\uf271\"\n#define ICON_FA_CALENDAR_TIMES u8\"\\uf273\"\n#define ICON_FA_CALENDAR_WEEK u8\"\\uf784\"\n#define ICON_FA_CAMERA u8\"\\uf030\"\n#define ICON_FA_CAMERA_RETRO u8\"\\uf083\"\n#define ICON_FA_CAMPGROUND u8\"\\uf6bb\"\n#define ICON_FA_CANDY_CANE u8\"\\uf786\"\n#define ICON_FA_CANNABIS u8\"\\uf55f\"\n#define ICON_FA_CAPSULES u8\"\\uf46b\"\n#define ICON_FA_CAR u8\"\\uf1b9\"\n#define ICON_FA_CAR_ALT u8\"\\uf5de\"\n#define ICON_FA_CAR_BATTERY u8\"\\uf5df\"\n#define ICON_FA_CAR_CRASH u8\"\\uf5e1\"\n#define ICON_FA_CAR_SIDE u8\"\\uf5e4\"\n#define ICON_FA_CARAVAN u8\"\\uf8ff\"\n#define ICON_FA_CARET_DOWN u8\"\\uf0d7\"\n#define ICON_FA_CARET_LEFT u8\"\\uf0d9\"\n#define ICON_FA_CARET_RIGHT u8\"\\uf0da\"\n#define ICON_FA_CARET_SQUARE_DOWN u8\"\\uf150\"\n#define ICON_FA_CARET_SQUARE_LEFT u8\"\\uf191\"\n#define ICON_FA_CARET_SQUARE_RIGHT u8\"\\uf152\"\n#define ICON_FA_CARET_SQUARE_UP u8\"\\uf151\"\n#define ICON_FA_CARET_UP u8\"\\uf0d8\"\n#define ICON_FA_CARROT u8\"\\uf787\"\n#define ICON_FA_CART_ARROW_DOWN u8\"\\uf218\"\n#define ICON_FA_CART_PLUS u8\"\\uf217\"\n#define ICON_FA_CASH_REGISTER u8\"\\uf788\"\n#define ICON_FA_CAT u8\"\\uf6be\"\n#define ICON_FA_CERTIFICATE u8\"\\uf0a3\"\n#define ICON_FA_CHAIR u8\"\\uf6c0\"\n#define ICON_FA_CHALKBOARD u8\"\\uf51b\"\n#define ICON_FA_CHALKBOARD_TEACHER u8\"\\uf51c\"\n#define ICON_FA_CHARGING_STATION u8\"\\uf5e7\"\n#define ICON_FA_CHART_AREA u8\"\\uf1fe\"\n#define ICON_FA_CHART_BAR u8\"\\uf080\"\n#define ICON_FA_CHART_LINE u8\"\\uf201\"\n#define ICON_FA_CHART_PIE u8\"\\uf200\"\n#define ICON_FA_CHECK u8\"\\uf00c\"\n#define ICON_FA_CHECK_CIRCLE u8\"\\uf058\"\n#define ICON_FA_CHECK_DOUBLE u8\"\\uf560\"\n#define ICON_FA_CHECK_SQUARE u8\"\\uf14a\"\n#define ICON_FA_CHEESE u8\"\\uf7ef\"\n#define ICON_FA_CHESS u8\"\\uf439\"\n#define ICON_FA_CHESS_BISHOP u8\"\\uf43a\"\n#define ICON_FA_CHESS_BOARD u8\"\\uf43c\"\n#define ICON_FA_CHESS_KING u8\"\\uf43f\"\n#define ICON_FA_CHESS_KNIGHT u8\"\\uf441\"\n#define ICON_FA_CHESS_PAWN u8\"\\uf443\"\n#define ICON_FA_CHESS_QUEEN u8\"\\uf445\"\n#define ICON_FA_CHESS_ROOK u8\"\\uf447\"\n#define ICON_FA_CHEVRON_CIRCLE_DOWN u8\"\\uf13a\"\n#define ICON_FA_CHEVRON_CIRCLE_LEFT u8\"\\uf137\"\n#define ICON_FA_CHEVRON_CIRCLE_RIGHT u8\"\\uf138\"\n#define ICON_FA_CHEVRON_CIRCLE_UP u8\"\\uf139\"\n#define ICON_FA_CHEVRON_DOWN u8\"\\uf078\"\n#define ICON_FA_CHEVRON_LEFT u8\"\\uf053\"\n#define ICON_FA_CHEVRON_RIGHT u8\"\\uf054\"\n#define ICON_FA_CHEVRON_UP u8\"\\uf077\"\n#define ICON_FA_CHILD u8\"\\uf1ae\"\n#define ICON_FA_CHURCH u8\"\\uf51d\"\n#define ICON_FA_CIRCLE u8\"\\uf111\"\n#define ICON_FA_CIRCLE_NOTCH u8\"\\uf1ce\"\n#define ICON_FA_CITY u8\"\\uf64f\"\n#define ICON_FA_CLINIC_MEDICAL u8\"\\uf7f2\"\n#define ICON_FA_CLIPBOARD u8\"\\uf328\"\n#define ICON_FA_CLIPBOARD_CHECK u8\"\\uf46c\"\n#define ICON_FA_CLIPBOARD_LIST u8\"\\uf46d\"\n#define ICON_FA_CLOCK u8\"\\uf017\"\n#define ICON_FA_CLONE u8\"\\uf24d\"\n#define ICON_FA_CLOSED_CAPTIONING u8\"\\uf20a\"\n#define ICON_FA_CLOUD u8\"\\uf0c2\"\n#define ICON_FA_CLOUD_DOWNLOAD_ALT u8\"\\uf381\"\n#define ICON_FA_CLOUD_MEATBALL u8\"\\uf73b\"\n#define ICON_FA_CLOUD_MOON u8\"\\uf6c3\"\n#define ICON_FA_CLOUD_MOON_RAIN u8\"\\uf73c\"\n#define ICON_FA_CLOUD_RAIN u8\"\\uf73d\"\n#define ICON_FA_CLOUD_SHOWERS_HEAVY u8\"\\uf740\"\n#define ICON_FA_CLOUD_SUN u8\"\\uf6c4\"\n#define ICON_FA_CLOUD_SUN_RAIN u8\"\\uf743\"\n#define ICON_FA_CLOUD_UPLOAD_ALT u8\"\\uf382\"\n#define ICON_FA_COCKTAIL u8\"\\uf561\"\n#define ICON_FA_CODE u8\"\\uf121\"\n#define ICON_FA_CODE_BRANCH u8\"\\uf126\"\n#define ICON_FA_COFFEE u8\"\\uf0f4\"\n#define ICON_FA_COG u8\"\\uf013\"\n#define ICON_FA_COGS u8\"\\uf085\"\n#define ICON_FA_COINS u8\"\\uf51e\"\n#define ICON_FA_COLUMNS u8\"\\uf0db\"\n#define ICON_FA_COMMENT u8\"\\uf075\"\n#define ICON_FA_COMMENT_ALT u8\"\\uf27a\"\n#define ICON_FA_COMMENT_DOLLAR u8\"\\uf651\"\n#define ICON_FA_COMMENT_DOTS u8\"\\uf4ad\"\n#define ICON_FA_COMMENT_MEDICAL u8\"\\uf7f5\"\n#define ICON_FA_COMMENT_SLASH u8\"\\uf4b3\"\n#define ICON_FA_COMMENTS u8\"\\uf086\"\n#define ICON_FA_COMMENTS_DOLLAR u8\"\\uf653\"\n#define ICON_FA_COMPACT_DISC u8\"\\uf51f\"\n#define ICON_FA_COMPASS u8\"\\uf14e\"\n#define ICON_FA_COMPRESS u8\"\\uf066\"\n#define ICON_FA_COMPRESS_ALT u8\"\\uf422\"\n#define ICON_FA_COMPRESS_ARROWS_ALT u8\"\\uf78c\"\n#define ICON_FA_CONCIERGE_BELL u8\"\\uf562\"\n#define ICON_FA_COOKIE u8\"\\uf563\"\n#define ICON_FA_COOKIE_BITE u8\"\\uf564\"\n#define ICON_FA_COPY u8\"\\uf0c5\"\n#define ICON_FA_COPYRIGHT u8\"\\uf1f9\"\n#define ICON_FA_COUCH u8\"\\uf4b8\"\n#define ICON_FA_CREDIT_CARD u8\"\\uf09d\"\n#define ICON_FA_CROP u8\"\\uf125\"\n#define ICON_FA_CROP_ALT u8\"\\uf565\"\n#define ICON_FA_CROSS u8\"\\uf654\"\n#define ICON_FA_CROSSHAIRS u8\"\\uf05b\"\n#define ICON_FA_CROW u8\"\\uf520\"\n#define ICON_FA_CROWN u8\"\\uf521\"\n#define ICON_FA_CRUTCH u8\"\\uf7f7\"\n#define ICON_FA_CUBE u8\"\\uf1b2\"\n#define ICON_FA_CUBES u8\"\\uf1b3\"\n#define ICON_FA_CUT u8\"\\uf0c4\"\n#define ICON_FA_DATABASE u8\"\\uf1c0\"\n#define ICON_FA_DEAF u8\"\\uf2a4\"\n#define ICON_FA_DEMOCRAT u8\"\\uf747\"\n#define ICON_FA_DESKTOP u8\"\\uf108\"\n#define ICON_FA_DHARMACHAKRA u8\"\\uf655\"\n#define ICON_FA_DIAGNOSES u8\"\\uf470\"\n#define ICON_FA_DICE u8\"\\uf522\"\n#define ICON_FA_DICE_D20 u8\"\\uf6cf\"\n#define ICON_FA_DICE_D6 u8\"\\uf6d1\"\n#define ICON_FA_DICE_FIVE u8\"\\uf523\"\n#define ICON_FA_DICE_FOUR u8\"\\uf524\"\n#define ICON_FA_DICE_ONE u8\"\\uf525\"\n#define ICON_FA_DICE_SIX u8\"\\uf526\"\n#define ICON_FA_DICE_THREE u8\"\\uf527\"\n#define ICON_FA_DICE_TWO u8\"\\uf528\"\n#define ICON_FA_DIGITAL_TACHOGRAPH u8\"\\uf566\"\n#define ICON_FA_DIRECTIONS u8\"\\uf5eb\"\n#define ICON_FA_DISEASE u8\"\\uf7fa\"\n#define ICON_FA_DIVIDE u8\"\\uf529\"\n#define ICON_FA_DIZZY u8\"\\uf567\"\n#define ICON_FA_DNA u8\"\\uf471\"\n#define ICON_FA_DOG u8\"\\uf6d3\"\n#define ICON_FA_DOLLAR_SIGN u8\"\\uf155\"\n#define ICON_FA_DOLLY u8\"\\uf472\"\n#define ICON_FA_DOLLY_FLATBED u8\"\\uf474\"\n#define ICON_FA_DONATE u8\"\\uf4b9\"\n#define ICON_FA_DOOR_CLOSED u8\"\\uf52a\"\n#define ICON_FA_DOOR_OPEN u8\"\\uf52b\"\n#define ICON_FA_DOT_CIRCLE u8\"\\uf192\"\n#define ICON_FA_DOVE u8\"\\uf4ba\"\n#define ICON_FA_DOWNLOAD u8\"\\uf019\"\n#define ICON_FA_DRAFTING_COMPASS u8\"\\uf568\"\n#define ICON_FA_DRAGON u8\"\\uf6d5\"\n#define ICON_FA_DRAW_POLYGON u8\"\\uf5ee\"\n#define ICON_FA_DRUM u8\"\\uf569\"\n#define ICON_FA_DRUM_STEELPAN u8\"\\uf56a\"\n#define ICON_FA_DRUMSTICK_BITE u8\"\\uf6d7\"\n#define ICON_FA_DUMBBELL u8\"\\uf44b\"\n#define ICON_FA_DUMPSTER u8\"\\uf793\"\n#define ICON_FA_DUMPSTER_FIRE u8\"\\uf794\"\n#define ICON_FA_DUNGEON u8\"\\uf6d9\"\n#define ICON_FA_EDIT u8\"\\uf044\"\n#define ICON_FA_EGG u8\"\\uf7fb\"\n#define ICON_FA_EJECT u8\"\\uf052\"\n#define ICON_FA_ELLIPSIS_H u8\"\\uf141\"\n#define ICON_FA_ELLIPSIS_V u8\"\\uf142\"\n#define ICON_FA_ENVELOPE u8\"\\uf0e0\"\n#define ICON_FA_ENVELOPE_OPEN u8\"\\uf2b6\"\n#define ICON_FA_ENVELOPE_OPEN_TEXT u8\"\\uf658\"\n#define ICON_FA_ENVELOPE_SQUARE u8\"\\uf199\"\n#define ICON_FA_EQUALS u8\"\\uf52c\"\n#define ICON_FA_ERASER u8\"\\uf12d\"\n#define ICON_FA_ETHERNET u8\"\\uf796\"\n#define ICON_FA_EURO_SIGN u8\"\\uf153\"\n#define ICON_FA_EXCHANGE_ALT u8\"\\uf362\"\n#define ICON_FA_EXCLAMATION u8\"\\uf12a\"\n#define ICON_FA_EXCLAMATION_CIRCLE u8\"\\uf06a\"\n#define ICON_FA_EXCLAMATION_TRIANGLE u8\"\\uf071\"\n#define ICON_FA_EXPAND u8\"\\uf065\"\n#define ICON_FA_EXPAND_ALT u8\"\\uf424\"\n#define ICON_FA_EXPAND_ARROWS_ALT u8\"\\uf31e\"\n#define ICON_FA_EXTERNAL_LINK_ALT u8\"\\uf35d\"\n#define ICON_FA_EXTERNAL_LINK_SQUARE_ALT u8\"\\uf360\"\n#define ICON_FA_EYE u8\"\\uf06e\"\n#define ICON_FA_EYE_DROPPER u8\"\\uf1fb\"\n#define ICON_FA_EYE_SLASH u8\"\\uf070\"\n#define ICON_FA_FAN u8\"\\uf863\"\n#define ICON_FA_FAST_BACKWARD u8\"\\uf049\"\n#define ICON_FA_FAST_FORWARD u8\"\\uf050\"\n#define ICON_FA_FAUCET u8\"\\uf905\"\n#define ICON_FA_FAX u8\"\\uf1ac\"\n#define ICON_FA_FEATHER u8\"\\uf52d\"\n#define ICON_FA_FEATHER_ALT u8\"\\uf56b\"\n#define ICON_FA_FEMALE u8\"\\uf182\"\n#define ICON_FA_FIGHTER_JET u8\"\\uf0fb\"\n#define ICON_FA_FILE u8\"\\uf15b\"\n#define ICON_FA_FILE_ALT u8\"\\uf15c\"\n#define ICON_FA_FILE_ARCHIVE u8\"\\uf1c6\"\n#define ICON_FA_FILE_AUDIO u8\"\\uf1c7\"\n#define ICON_FA_FILE_CODE u8\"\\uf1c9\"\n#define ICON_FA_FILE_CONTRACT u8\"\\uf56c\"\n#define ICON_FA_FILE_CSV u8\"\\uf6dd\"\n#define ICON_FA_FILE_DOWNLOAD u8\"\\uf56d\"\n#define ICON_FA_FILE_EXCEL u8\"\\uf1c3\"\n#define ICON_FA_FILE_EXPORT u8\"\\uf56e\"\n#define ICON_FA_FILE_IMAGE u8\"\\uf1c5\"\n#define ICON_FA_FILE_IMPORT u8\"\\uf56f\"\n#define ICON_FA_FILE_INVOICE u8\"\\uf570\"\n#define ICON_FA_FILE_INVOICE_DOLLAR u8\"\\uf571\"\n#define ICON_FA_FILE_MEDICAL u8\"\\uf477\"\n#define ICON_FA_FILE_MEDICAL_ALT u8\"\\uf478\"\n#define ICON_FA_FILE_PDF u8\"\\uf1c1\"\n#define ICON_FA_FILE_POWERPOINT u8\"\\uf1c4\"\n#define ICON_FA_FILE_PRESCRIPTION u8\"\\uf572\"\n#define ICON_FA_FILE_SIGNATURE u8\"\\uf573\"\n#define ICON_FA_FILE_UPLOAD u8\"\\uf574\"\n#define ICON_FA_FILE_VIDEO u8\"\\uf1c8\"\n#define ICON_FA_FILE_WORD u8\"\\uf1c2\"\n#define ICON_FA_FILL u8\"\\uf575\"\n#define ICON_FA_FILL_DRIP u8\"\\uf576\"\n#define ICON_FA_FILM u8\"\\uf008\"\n#define ICON_FA_FILTER u8\"\\uf0b0\"\n#define ICON_FA_FINGERPRINT u8\"\\uf577\"\n#define ICON_FA_FIRE u8\"\\uf06d\"\n#define ICON_FA_FIRE_ALT u8\"\\uf7e4\"\n#define ICON_FA_FIRE_EXTINGUISHER u8\"\\uf134\"\n#define ICON_FA_FIRST_AID u8\"\\uf479\"\n#define ICON_FA_FISH u8\"\\uf578\"\n#define ICON_FA_FIST_RAISED u8\"\\uf6de\"\n#define ICON_FA_FLAG u8\"\\uf024\"\n#define ICON_FA_FLAG_CHECKERED u8\"\\uf11e\"\n#define ICON_FA_FLAG_USA u8\"\\uf74d\"\n#define ICON_FA_FLASK u8\"\\uf0c3\"\n#define ICON_FA_FLUSHED u8\"\\uf579\"\n#define ICON_FA_FOLDER u8\"\\uf07b\"\n#define ICON_FA_FOLDER_MINUS u8\"\\uf65d\"\n#define ICON_FA_FOLDER_OPEN u8\"\\uf07c\"\n#define ICON_FA_FOLDER_PLUS u8\"\\uf65e\"\n#define ICON_FA_FONT u8\"\\uf031\"\n#define ICON_FA_FONT_AWESOME_LOGO_FULL u8\"\\uf4e6\"\n#define ICON_FA_FOOTBALL_BALL u8\"\\uf44e\"\n#define ICON_FA_FORWARD u8\"\\uf04e\"\n#define ICON_FA_FROG u8\"\\uf52e\"\n#define ICON_FA_FROWN u8\"\\uf119\"\n#define ICON_FA_FROWN_OPEN u8\"\\uf57a\"\n#define ICON_FA_FUNNEL_DOLLAR u8\"\\uf662\"\n#define ICON_FA_FUTBOL u8\"\\uf1e3\"\n#define ICON_FA_GAMEPAD u8\"\\uf11b\"\n#define ICON_FA_GAS_PUMP u8\"\\uf52f\"\n#define ICON_FA_GAVEL u8\"\\uf0e3\"\n#define ICON_FA_GEM u8\"\\uf3a5\"\n#define ICON_FA_GENDERLESS u8\"\\uf22d\"\n#define ICON_FA_GHOST u8\"\\uf6e2\"\n#define ICON_FA_GIFT u8\"\\uf06b\"\n#define ICON_FA_GIFTS u8\"\\uf79c\"\n#define ICON_FA_GLASS_CHEERS u8\"\\uf79f\"\n#define ICON_FA_GLASS_MARTINI u8\"\\uf000\"\n#define ICON_FA_GLASS_MARTINI_ALT u8\"\\uf57b\"\n#define ICON_FA_GLASS_WHISKEY u8\"\\uf7a0\"\n#define ICON_FA_GLASSES u8\"\\uf530\"\n#define ICON_FA_GLOBE u8\"\\uf0ac\"\n#define ICON_FA_GLOBE_AFRICA u8\"\\uf57c\"\n#define ICON_FA_GLOBE_AMERICAS u8\"\\uf57d\"\n#define ICON_FA_GLOBE_ASIA u8\"\\uf57e\"\n#define ICON_FA_GLOBE_EUROPE u8\"\\uf7a2\"\n#define ICON_FA_GOLF_BALL u8\"\\uf450\"\n#define ICON_FA_GOPURAM u8\"\\uf664\"\n#define ICON_FA_GRADUATION_CAP u8\"\\uf19d\"\n#define ICON_FA_GREATER_THAN u8\"\\uf531\"\n#define ICON_FA_GREATER_THAN_EQUAL u8\"\\uf532\"\n#define ICON_FA_GRIMACE u8\"\\uf57f\"\n#define ICON_FA_GRIN u8\"\\uf580\"\n#define ICON_FA_GRIN_ALT u8\"\\uf581\"\n#define ICON_FA_GRIN_BEAM u8\"\\uf582\"\n#define ICON_FA_GRIN_BEAM_SWEAT u8\"\\uf583\"\n#define ICON_FA_GRIN_HEARTS u8\"\\uf584\"\n#define ICON_FA_GRIN_SQUINT u8\"\\uf585\"\n#define ICON_FA_GRIN_SQUINT_TEARS u8\"\\uf586\"\n#define ICON_FA_GRIN_STARS u8\"\\uf587\"\n#define ICON_FA_GRIN_TEARS u8\"\\uf588\"\n#define ICON_FA_GRIN_TONGUE u8\"\\uf589\"\n#define ICON_FA_GRIN_TONGUE_SQUINT u8\"\\uf58a\"\n#define ICON_FA_GRIN_TONGUE_WINK u8\"\\uf58b\"\n#define ICON_FA_GRIN_WINK u8\"\\uf58c\"\n#define ICON_FA_GRIP_HORIZONTAL u8\"\\uf58d\"\n#define ICON_FA_GRIP_LINES u8\"\\uf7a4\"\n#define ICON_FA_GRIP_LINES_VERTICAL u8\"\\uf7a5\"\n#define ICON_FA_GRIP_VERTICAL u8\"\\uf58e\"\n#define ICON_FA_GUITAR u8\"\\uf7a6\"\n#define ICON_FA_H_SQUARE u8\"\\uf0fd\"\n#define ICON_FA_HAMBURGER u8\"\\uf805\"\n#define ICON_FA_HAMMER u8\"\\uf6e3\"\n#define ICON_FA_HAMSA u8\"\\uf665\"\n#define ICON_FA_HAND_HOLDING u8\"\\uf4bd\"\n#define ICON_FA_HAND_HOLDING_HEART u8\"\\uf4be\"\n#define ICON_FA_HAND_HOLDING_MEDICAL u8\"\\uf95c\"\n#define ICON_FA_HAND_HOLDING_USD u8\"\\uf4c0\"\n#define ICON_FA_HAND_HOLDING_WATER u8\"\\uf4c1\"\n#define ICON_FA_HAND_LIZARD u8\"\\uf258\"\n#define ICON_FA_HAND_MIDDLE_FINGER u8\"\\uf806\"\n#define ICON_FA_HAND_PAPER u8\"\\uf256\"\n#define ICON_FA_HAND_PEACE u8\"\\uf25b\"\n#define ICON_FA_HAND_POINT_DOWN u8\"\\uf0a7\"\n#define ICON_FA_HAND_POINT_LEFT u8\"\\uf0a5\"\n#define ICON_FA_HAND_POINT_RIGHT u8\"\\uf0a4\"\n#define ICON_FA_HAND_POINT_UP u8\"\\uf0a6\"\n#define ICON_FA_HAND_POINTER u8\"\\uf25a\"\n#define ICON_FA_HAND_ROCK u8\"\\uf255\"\n#define ICON_FA_HAND_SCISSORS u8\"\\uf257\"\n#define ICON_FA_HAND_SPARKLES u8\"\\uf95d\"\n#define ICON_FA_HAND_SPOCK u8\"\\uf259\"\n#define ICON_FA_HANDS u8\"\\uf4c2\"\n#define ICON_FA_HANDS_HELPING u8\"\\uf4c4\"\n#define ICON_FA_HANDS_WASH u8\"\\uf95e\"\n#define ICON_FA_HANDSHAKE u8\"\\uf2b5\"\n#define ICON_FA_HANDSHAKE_ALT_SLASH u8\"\\uf95f\"\n#define ICON_FA_HANDSHAKE_SLASH u8\"\\uf960\"\n#define ICON_FA_HANUKIAH u8\"\\uf6e6\"\n#define ICON_FA_HARD_HAT u8\"\\uf807\"\n#define ICON_FA_HASHTAG u8\"\\uf292\"\n#define ICON_FA_HAT_COWBOY u8\"\\uf8c0\"\n#define ICON_FA_HAT_COWBOY_SIDE u8\"\\uf8c1\"\n#define ICON_FA_HAT_WIZARD u8\"\\uf6e8\"\n#define ICON_FA_HDD u8\"\\uf0a0\"\n#define ICON_FA_HEAD_SIDE_COUGH u8\"\\uf961\"\n#define ICON_FA_HEAD_SIDE_COUGH_SLASH u8\"\\uf962\"\n#define ICON_FA_HEAD_SIDE_MASK u8\"\\uf963\"\n#define ICON_FA_HEAD_SIDE_VIRUS u8\"\\uf964\"\n#define ICON_FA_HEADING u8\"\\uf1dc\"\n#define ICON_FA_HEADPHONES u8\"\\uf025\"\n#define ICON_FA_HEADPHONES_ALT u8\"\\uf58f\"\n#define ICON_FA_HEADSET u8\"\\uf590\"\n#define ICON_FA_HEART u8\"\\uf004\"\n#define ICON_FA_HEART_BROKEN u8\"\\uf7a9\"\n#define ICON_FA_HEARTBEAT u8\"\\uf21e\"\n#define ICON_FA_HELICOPTER u8\"\\uf533\"\n#define ICON_FA_HIGHLIGHTER u8\"\\uf591\"\n#define ICON_FA_HIKING u8\"\\uf6ec\"\n#define ICON_FA_HIPPO u8\"\\uf6ed\"\n#define ICON_FA_HISTORY u8\"\\uf1da\"\n#define ICON_FA_HOCKEY_PUCK u8\"\\uf453\"\n#define ICON_FA_HOLLY_BERRY u8\"\\uf7aa\"\n#define ICON_FA_HOME u8\"\\uf015\"\n#define ICON_FA_HORSE u8\"\\uf6f0\"\n#define ICON_FA_HORSE_HEAD u8\"\\uf7ab\"\n#define ICON_FA_HOSPITAL u8\"\\uf0f8\"\n#define ICON_FA_HOSPITAL_ALT u8\"\\uf47d\"\n#define ICON_FA_HOSPITAL_SYMBOL u8\"\\uf47e\"\n#define ICON_FA_HOSPITAL_USER u8\"\\uf80d\"\n#define ICON_FA_HOT_TUB u8\"\\uf593\"\n#define ICON_FA_HOTDOG u8\"\\uf80f\"\n#define ICON_FA_HOTEL u8\"\\uf594\"\n#define ICON_FA_HOURGLASS u8\"\\uf254\"\n#define ICON_FA_HOURGLASS_END u8\"\\uf253\"\n#define ICON_FA_HOURGLASS_HALF u8\"\\uf252\"\n#define ICON_FA_HOURGLASS_START u8\"\\uf251\"\n#define ICON_FA_HOUSE_DAMAGE u8\"\\uf6f1\"\n#define ICON_FA_HOUSE_USER u8\"\\uf965\"\n#define ICON_FA_HRYVNIA u8\"\\uf6f2\"\n#define ICON_FA_I_CURSOR u8\"\\uf246\"\n#define ICON_FA_ICE_CREAM u8\"\\uf810\"\n#define ICON_FA_ICICLES u8\"\\uf7ad\"\n#define ICON_FA_ICONS u8\"\\uf86d\"\n#define ICON_FA_ID_BADGE u8\"\\uf2c1\"\n#define ICON_FA_ID_CARD u8\"\\uf2c2\"\n#define ICON_FA_ID_CARD_ALT u8\"\\uf47f\"\n#define ICON_FA_IGLOO u8\"\\uf7ae\"\n#define ICON_FA_IMAGE u8\"\\uf03e\"\n#define ICON_FA_IMAGES u8\"\\uf302\"\n#define ICON_FA_INBOX u8\"\\uf01c\"\n#define ICON_FA_INDENT u8\"\\uf03c\"\n#define ICON_FA_INDUSTRY u8\"\\uf275\"\n#define ICON_FA_INFINITY u8\"\\uf534\"\n#define ICON_FA_INFO u8\"\\uf129\"\n#define ICON_FA_INFO_CIRCLE u8\"\\uf05a\"\n#define ICON_FA_ITALIC u8\"\\uf033\"\n#define ICON_FA_JEDI u8\"\\uf669\"\n#define ICON_FA_JOINT u8\"\\uf595\"\n#define ICON_FA_JOURNAL_WHILLS u8\"\\uf66a\"\n#define ICON_FA_KAABA u8\"\\uf66b\"\n#define ICON_FA_KEY u8\"\\uf084\"\n#define ICON_FA_KEYBOARD u8\"\\uf11c\"\n#define ICON_FA_KHANDA u8\"\\uf66d\"\n#define ICON_FA_KISS u8\"\\uf596\"\n#define ICON_FA_KISS_BEAM u8\"\\uf597\"\n#define ICON_FA_KISS_WINK_HEART u8\"\\uf598\"\n#define ICON_FA_KIWI_BIRD u8\"\\uf535\"\n#define ICON_FA_LANDMARK u8\"\\uf66f\"\n#define ICON_FA_LANGUAGE u8\"\\uf1ab\"\n#define ICON_FA_LAPTOP u8\"\\uf109\"\n#define ICON_FA_LAPTOP_CODE u8\"\\uf5fc\"\n#define ICON_FA_LAPTOP_HOUSE u8\"\\uf966\"\n#define ICON_FA_LAPTOP_MEDICAL u8\"\\uf812\"\n#define ICON_FA_LAUGH u8\"\\uf599\"\n#define ICON_FA_LAUGH_BEAM u8\"\\uf59a\"\n#define ICON_FA_LAUGH_SQUINT u8\"\\uf59b\"\n#define ICON_FA_LAUGH_WINK u8\"\\uf59c\"\n#define ICON_FA_LAYER_GROUP u8\"\\uf5fd\"\n#define ICON_FA_LEAF u8\"\\uf06c\"\n#define ICON_FA_LEMON u8\"\\uf094\"\n#define ICON_FA_LESS_THAN u8\"\\uf536\"\n#define ICON_FA_LESS_THAN_EQUAL u8\"\\uf537\"\n#define ICON_FA_LEVEL_DOWN_ALT u8\"\\uf3be\"\n#define ICON_FA_LEVEL_UP_ALT u8\"\\uf3bf\"\n#define ICON_FA_LIFE_RING u8\"\\uf1cd\"\n#define ICON_FA_LIGHTBULB u8\"\\uf0eb\"\n#define ICON_FA_LINK u8\"\\uf0c1\"\n#define ICON_FA_LIRA_SIGN u8\"\\uf195\"\n#define ICON_FA_LIST u8\"\\uf03a\"\n#define ICON_FA_LIST_ALT u8\"\\uf022\"\n#define ICON_FA_LIST_OL u8\"\\uf0cb\"\n#define ICON_FA_LIST_UL u8\"\\uf0ca\"\n#define ICON_FA_LOCATION_ARROW u8\"\\uf124\"\n#define ICON_FA_LOCK u8\"\\uf023\"\n#define ICON_FA_LOCK_OPEN u8\"\\uf3c1\"\n#define ICON_FA_LONG_ARROW_ALT_DOWN u8\"\\uf309\"\n#define ICON_FA_LONG_ARROW_ALT_LEFT u8\"\\uf30a\"\n#define ICON_FA_LONG_ARROW_ALT_RIGHT u8\"\\uf30b\"\n#define ICON_FA_LONG_ARROW_ALT_UP u8\"\\uf30c\"\n#define ICON_FA_LOW_VISION u8\"\\uf2a8\"\n#define ICON_FA_LUGGAGE_CART u8\"\\uf59d\"\n#define ICON_FA_LUNGS u8\"\\uf604\"\n#define ICON_FA_LUNGS_VIRUS u8\"\\uf967\"\n#define ICON_FA_MAGIC u8\"\\uf0d0\"\n#define ICON_FA_MAGNET u8\"\\uf076\"\n#define ICON_FA_MAIL_BULK u8\"\\uf674\"\n#define ICON_FA_MALE u8\"\\uf183\"\n#define ICON_FA_MAP u8\"\\uf279\"\n#define ICON_FA_MAP_MARKED u8\"\\uf59f\"\n#define ICON_FA_MAP_MARKED_ALT u8\"\\uf5a0\"\n#define ICON_FA_MAP_MARKER u8\"\\uf041\"\n#define ICON_FA_MAP_MARKER_ALT u8\"\\uf3c5\"\n#define ICON_FA_MAP_PIN u8\"\\uf276\"\n#define ICON_FA_MAP_SIGNS u8\"\\uf277\"\n#define ICON_FA_MARKER u8\"\\uf5a1\"\n#define ICON_FA_MARS u8\"\\uf222\"\n#define ICON_FA_MARS_DOUBLE u8\"\\uf227\"\n#define ICON_FA_MARS_STROKE u8\"\\uf229\"\n#define ICON_FA_MARS_STROKE_H u8\"\\uf22b\"\n#define ICON_FA_MARS_STROKE_V u8\"\\uf22a\"\n#define ICON_FA_MASK u8\"\\uf6fa\"\n#define ICON_FA_MEDAL u8\"\\uf5a2\"\n#define ICON_FA_MEDKIT u8\"\\uf0fa\"\n#define ICON_FA_MEH u8\"\\uf11a\"\n#define ICON_FA_MEH_BLANK u8\"\\uf5a4\"\n#define ICON_FA_MEH_ROLLING_EYES u8\"\\uf5a5\"\n#define ICON_FA_MEMORY u8\"\\uf538\"\n#define ICON_FA_MENORAH u8\"\\uf676\"\n#define ICON_FA_MERCURY u8\"\\uf223\"\n#define ICON_FA_METEOR u8\"\\uf753\"\n#define ICON_FA_MICROCHIP u8\"\\uf2db\"\n#define ICON_FA_MICROPHONE u8\"\\uf130\"\n#define ICON_FA_MICROPHONE_ALT u8\"\\uf3c9\"\n#define ICON_FA_MICROPHONE_ALT_SLASH u8\"\\uf539\"\n#define ICON_FA_MICROPHONE_SLASH u8\"\\uf131\"\n#define ICON_FA_MICROSCOPE u8\"\\uf610\"\n#define ICON_FA_MINUS u8\"\\uf068\"\n#define ICON_FA_MINUS_CIRCLE u8\"\\uf056\"\n#define ICON_FA_MINUS_SQUARE u8\"\\uf146\"\n#define ICON_FA_MITTEN u8\"\\uf7b5\"\n#define ICON_FA_MOBILE u8\"\\uf10b\"\n#define ICON_FA_MOBILE_ALT u8\"\\uf3cd\"\n#define ICON_FA_MONEY_BILL u8\"\\uf0d6\"\n#define ICON_FA_MONEY_BILL_ALT u8\"\\uf3d1\"\n#define ICON_FA_MONEY_BILL_WAVE u8\"\\uf53a\"\n#define ICON_FA_MONEY_BILL_WAVE_ALT u8\"\\uf53b\"\n#define ICON_FA_MONEY_CHECK u8\"\\uf53c\"\n#define ICON_FA_MONEY_CHECK_ALT u8\"\\uf53d\"\n#define ICON_FA_MONUMENT u8\"\\uf5a6\"\n#define ICON_FA_MOON u8\"\\uf186\"\n#define ICON_FA_MORTAR_PESTLE u8\"\\uf5a7\"\n#define ICON_FA_MOSQUE u8\"\\uf678\"\n#define ICON_FA_MOTORCYCLE u8\"\\uf21c\"\n#define ICON_FA_MOUNTAIN u8\"\\uf6fc\"\n#define ICON_FA_MOUSE u8\"\\uf8cc\"\n#define ICON_FA_MOUSE_POINTER u8\"\\uf245\"\n#define ICON_FA_MUG_HOT u8\"\\uf7b6\"\n#define ICON_FA_MUSIC u8\"\\uf001\"\n#define ICON_FA_NETWORK_WIRED u8\"\\uf6ff\"\n#define ICON_FA_NEUTER u8\"\\uf22c\"\n#define ICON_FA_NEWSPAPER u8\"\\uf1ea\"\n#define ICON_FA_NOT_EQUAL u8\"\\uf53e\"\n#define ICON_FA_NOTES_MEDICAL u8\"\\uf481\"\n#define ICON_FA_OBJECT_GROUP u8\"\\uf247\"\n#define ICON_FA_OBJECT_UNGROUP u8\"\\uf248\"\n#define ICON_FA_OIL_CAN u8\"\\uf613\"\n#define ICON_FA_OM u8\"\\uf679\"\n#define ICON_FA_OTTER u8\"\\uf700\"\n#define ICON_FA_OUTDENT u8\"\\uf03b\"\n#define ICON_FA_PAGER u8\"\\uf815\"\n#define ICON_FA_PAINT_BRUSH u8\"\\uf1fc\"\n#define ICON_FA_PAINT_ROLLER u8\"\\uf5aa\"\n#define ICON_FA_PALETTE u8\"\\uf53f\"\n#define ICON_FA_PALLET u8\"\\uf482\"\n#define ICON_FA_PAPER_PLANE u8\"\\uf1d8\"\n#define ICON_FA_PAPERCLIP u8\"\\uf0c6\"\n#define ICON_FA_PARACHUTE_BOX u8\"\\uf4cd\"\n#define ICON_FA_PARAGRAPH u8\"\\uf1dd\"\n#define ICON_FA_PARKING u8\"\\uf540\"\n#define ICON_FA_PASSPORT u8\"\\uf5ab\"\n#define ICON_FA_PASTAFARIANISM u8\"\\uf67b\"\n#define ICON_FA_PASTE u8\"\\uf0ea\"\n#define ICON_FA_PAUSE u8\"\\uf04c\"\n#define ICON_FA_PAUSE_CIRCLE u8\"\\uf28b\"\n#define ICON_FA_PAW u8\"\\uf1b0\"\n#define ICON_FA_PEACE u8\"\\uf67c\"\n#define ICON_FA_PEN u8\"\\uf304\"\n#define ICON_FA_PEN_ALT u8\"\\uf305\"\n#define ICON_FA_PEN_FANCY u8\"\\uf5ac\"\n#define ICON_FA_PEN_NIB u8\"\\uf5ad\"\n#define ICON_FA_PEN_SQUARE u8\"\\uf14b\"\n#define ICON_FA_PENCIL_ALT u8\"\\uf303\"\n#define ICON_FA_PENCIL_RULER u8\"\\uf5ae\"\n#define ICON_FA_PEOPLE_ARROWS u8\"\\uf968\"\n#define ICON_FA_PEOPLE_CARRY u8\"\\uf4ce\"\n#define ICON_FA_PEPPER_HOT u8\"\\uf816\"\n#define ICON_FA_PERCENT u8\"\\uf295\"\n#define ICON_FA_PERCENTAGE u8\"\\uf541\"\n#define ICON_FA_PERSON_BOOTH u8\"\\uf756\"\n#define ICON_FA_PHONE u8\"\\uf095\"\n#define ICON_FA_PHONE_ALT u8\"\\uf879\"\n#define ICON_FA_PHONE_SLASH u8\"\\uf3dd\"\n#define ICON_FA_PHONE_SQUARE u8\"\\uf098\"\n#define ICON_FA_PHONE_SQUARE_ALT u8\"\\uf87b\"\n#define ICON_FA_PHONE_VOLUME u8\"\\uf2a0\"\n#define ICON_FA_PHOTO_VIDEO u8\"\\uf87c\"\n#define ICON_FA_PIGGY_BANK u8\"\\uf4d3\"\n#define ICON_FA_PILLS u8\"\\uf484\"\n#define ICON_FA_PIZZA_SLICE u8\"\\uf818\"\n#define ICON_FA_PLACE_OF_WORSHIP u8\"\\uf67f\"\n#define ICON_FA_PLANE u8\"\\uf072\"\n#define ICON_FA_PLANE_ARRIVAL u8\"\\uf5af\"\n#define ICON_FA_PLANE_DEPARTURE u8\"\\uf5b0\"\n#define ICON_FA_PLANE_SLASH u8\"\\uf969\"\n#define ICON_FA_PLAY u8\"\\uf04b\"\n#define ICON_FA_PLAY_CIRCLE u8\"\\uf144\"\n#define ICON_FA_PLUG u8\"\\uf1e6\"\n#define ICON_FA_PLUS u8\"\\uf067\"\n#define ICON_FA_PLUS_CIRCLE u8\"\\uf055\"\n#define ICON_FA_PLUS_SQUARE u8\"\\uf0fe\"\n#define ICON_FA_PODCAST u8\"\\uf2ce\"\n#define ICON_FA_POLL u8\"\\uf681\"\n#define ICON_FA_POLL_H u8\"\\uf682\"\n#define ICON_FA_POO u8\"\\uf2fe\"\n#define ICON_FA_POO_STORM u8\"\\uf75a\"\n#define ICON_FA_POOP u8\"\\uf619\"\n#define ICON_FA_PORTRAIT u8\"\\uf3e0\"\n#define ICON_FA_POUND_SIGN u8\"\\uf154\"\n#define ICON_FA_POWER_OFF u8\"\\uf011\"\n#define ICON_FA_PRAY u8\"\\uf683\"\n#define ICON_FA_PRAYING_HANDS u8\"\\uf684\"\n#define ICON_FA_PRESCRIPTION u8\"\\uf5b1\"\n#define ICON_FA_PRESCRIPTION_BOTTLE u8\"\\uf485\"\n#define ICON_FA_PRESCRIPTION_BOTTLE_ALT u8\"\\uf486\"\n#define ICON_FA_PRINT u8\"\\uf02f\"\n#define ICON_FA_PROCEDURES u8\"\\uf487\"\n#define ICON_FA_PROJECT_DIAGRAM u8\"\\uf542\"\n#define ICON_FA_PUMP_MEDICAL u8\"\\uf96a\"\n#define ICON_FA_PUMP_SOAP u8\"\\uf96b\"\n#define ICON_FA_PUZZLE_PIECE u8\"\\uf12e\"\n#define ICON_FA_QRCODE u8\"\\uf029\"\n#define ICON_FA_QUESTION u8\"\\uf128\"\n#define ICON_FA_QUESTION_CIRCLE u8\"\\uf059\"\n#define ICON_FA_QUIDDITCH u8\"\\uf458\"\n#define ICON_FA_QUOTE_LEFT u8\"\\uf10d\"\n#define ICON_FA_QUOTE_RIGHT u8\"\\uf10e\"\n#define ICON_FA_QURAN u8\"\\uf687\"\n#define ICON_FA_RADIATION u8\"\\uf7b9\"\n#define ICON_FA_RADIATION_ALT u8\"\\uf7ba\"\n#define ICON_FA_RAINBOW u8\"\\uf75b\"\n#define ICON_FA_RANDOM u8\"\\uf074\"\n#define ICON_FA_RECEIPT u8\"\\uf543\"\n#define ICON_FA_RECORD_VINYL u8\"\\uf8d9\"\n#define ICON_FA_RECYCLE u8\"\\uf1b8\"\n#define ICON_FA_REDO u8\"\\uf01e\"\n#define ICON_FA_REDO_ALT u8\"\\uf2f9\"\n#define ICON_FA_REGISTERED u8\"\\uf25d\"\n#define ICON_FA_REMOVE_FORMAT u8\"\\uf87d\"\n#define ICON_FA_REPLY u8\"\\uf3e5\"\n#define ICON_FA_REPLY_ALL u8\"\\uf122\"\n#define ICON_FA_REPUBLICAN u8\"\\uf75e\"\n#define ICON_FA_RESTROOM u8\"\\uf7bd\"\n#define ICON_FA_RETWEET u8\"\\uf079\"\n#define ICON_FA_RIBBON u8\"\\uf4d6\"\n#define ICON_FA_RING u8\"\\uf70b\"\n#define ICON_FA_ROAD u8\"\\uf018\"\n#define ICON_FA_ROBOT u8\"\\uf544\"\n#define ICON_FA_ROCKET u8\"\\uf135\"\n#define ICON_FA_ROUTE u8\"\\uf4d7\"\n#define ICON_FA_RSS u8\"\\uf09e\"\n#define ICON_FA_RSS_SQUARE u8\"\\uf143\"\n#define ICON_FA_RUBLE_SIGN u8\"\\uf158\"\n#define ICON_FA_RULER u8\"\\uf545\"\n#define ICON_FA_RULER_COMBINED u8\"\\uf546\"\n#define ICON_FA_RULER_HORIZONTAL u8\"\\uf547\"\n#define ICON_FA_RULER_VERTICAL u8\"\\uf548\"\n#define ICON_FA_RUNNING u8\"\\uf70c\"\n#define ICON_FA_RUPEE_SIGN u8\"\\uf156\"\n#define ICON_FA_SAD_CRY u8\"\\uf5b3\"\n#define ICON_FA_SAD_TEAR u8\"\\uf5b4\"\n#define ICON_FA_SATELLITE u8\"\\uf7bf\"\n#define ICON_FA_SATELLITE_DISH u8\"\\uf7c0\"\n#define ICON_FA_SAVE u8\"\\uf0c7\"\n#define ICON_FA_SCHOOL u8\"\\uf549\"\n#define ICON_FA_SCREWDRIVER u8\"\\uf54a\"\n#define ICON_FA_SCROLL u8\"\\uf70e\"\n#define ICON_FA_SD_CARD u8\"\\uf7c2\"\n#define ICON_FA_SEARCH u8\"\\uf002\"\n#define ICON_FA_SEARCH_DOLLAR u8\"\\uf688\"\n#define ICON_FA_SEARCH_LOCATION u8\"\\uf689\"\n#define ICON_FA_SEARCH_MINUS u8\"\\uf010\"\n#define ICON_FA_SEARCH_PLUS u8\"\\uf00e\"\n#define ICON_FA_SEEDLING u8\"\\uf4d8\"\n#define ICON_FA_SERVER u8\"\\uf233\"\n#define ICON_FA_SHAPES u8\"\\uf61f\"\n#define ICON_FA_SHARE u8\"\\uf064\"\n#define ICON_FA_SHARE_ALT u8\"\\uf1e0\"\n#define ICON_FA_SHARE_ALT_SQUARE u8\"\\uf1e1\"\n#define ICON_FA_SHARE_SQUARE u8\"\\uf14d\"\n#define ICON_FA_SHEKEL_SIGN u8\"\\uf20b\"\n#define ICON_FA_SHIELD_ALT u8\"\\uf3ed\"\n#define ICON_FA_SHIELD_VIRUS u8\"\\uf96c\"\n#define ICON_FA_SHIP u8\"\\uf21a\"\n#define ICON_FA_SHIPPING_FAST u8\"\\uf48b\"\n#define ICON_FA_SHOE_PRINTS u8\"\\uf54b\"\n#define ICON_FA_SHOPPING_BAG u8\"\\uf290\"\n#define ICON_FA_SHOPPING_BASKET u8\"\\uf291\"\n#define ICON_FA_SHOPPING_CART u8\"\\uf07a\"\n#define ICON_FA_SHOWER u8\"\\uf2cc\"\n#define ICON_FA_SHUTTLE_VAN u8\"\\uf5b6\"\n#define ICON_FA_SIGN u8\"\\uf4d9\"\n#define ICON_FA_SIGN_IN_ALT u8\"\\uf2f6\"\n#define ICON_FA_SIGN_LANGUAGE u8\"\\uf2a7\"\n#define ICON_FA_SIGN_OUT_ALT u8\"\\uf2f5\"\n#define ICON_FA_SIGNAL u8\"\\uf012\"\n#define ICON_FA_SIGNATURE u8\"\\uf5b7\"\n#define ICON_FA_SIM_CARD u8\"\\uf7c4\"\n#define ICON_FA_SINK u8\"\\uf96d\"\n#define ICON_FA_SITEMAP u8\"\\uf0e8\"\n#define ICON_FA_SKATING u8\"\\uf7c5\"\n#define ICON_FA_SKIING u8\"\\uf7c9\"\n#define ICON_FA_SKIING_NORDIC u8\"\\uf7ca\"\n#define ICON_FA_SKULL u8\"\\uf54c\"\n#define ICON_FA_SKULL_CROSSBONES u8\"\\uf714\"\n#define ICON_FA_SLASH u8\"\\uf715\"\n#define ICON_FA_SLEIGH u8\"\\uf7cc\"\n#define ICON_FA_SLIDERS_H u8\"\\uf1de\"\n#define ICON_FA_SMILE u8\"\\uf118\"\n#define ICON_FA_SMILE_BEAM u8\"\\uf5b8\"\n#define ICON_FA_SMILE_WINK u8\"\\uf4da\"\n#define ICON_FA_SMOG u8\"\\uf75f\"\n#define ICON_FA_SMOKING u8\"\\uf48d\"\n#define ICON_FA_SMOKING_BAN u8\"\\uf54d\"\n#define ICON_FA_SMS u8\"\\uf7cd\"\n#define ICON_FA_SNOWBOARDING u8\"\\uf7ce\"\n#define ICON_FA_SNOWFLAKE u8\"\\uf2dc\"\n#define ICON_FA_SNOWMAN u8\"\\uf7d0\"\n#define ICON_FA_SNOWPLOW u8\"\\uf7d2\"\n#define ICON_FA_SOAP u8\"\\uf96e\"\n#define ICON_FA_SOCKS u8\"\\uf696\"\n#define ICON_FA_SOLAR_PANEL u8\"\\uf5ba\"\n#define ICON_FA_SORT u8\"\\uf0dc\"\n#define ICON_FA_SORT_ALPHA_DOWN u8\"\\uf15d\"\n#define ICON_FA_SORT_ALPHA_DOWN_ALT u8\"\\uf881\"\n#define ICON_FA_SORT_ALPHA_UP u8\"\\uf15e\"\n#define ICON_FA_SORT_ALPHA_UP_ALT u8\"\\uf882\"\n#define ICON_FA_SORT_AMOUNT_DOWN u8\"\\uf160\"\n#define ICON_FA_SORT_AMOUNT_DOWN_ALT u8\"\\uf884\"\n#define ICON_FA_SORT_AMOUNT_UP u8\"\\uf161\"\n#define ICON_FA_SORT_AMOUNT_UP_ALT u8\"\\uf885\"\n#define ICON_FA_SORT_DOWN u8\"\\uf0dd\"\n#define ICON_FA_SORT_NUMERIC_DOWN u8\"\\uf162\"\n#define ICON_FA_SORT_NUMERIC_DOWN_ALT u8\"\\uf886\"\n#define ICON_FA_SORT_NUMERIC_UP u8\"\\uf163\"\n#define ICON_FA_SORT_NUMERIC_UP_ALT u8\"\\uf887\"\n#define ICON_FA_SORT_UP u8\"\\uf0de\"\n#define ICON_FA_SPA u8\"\\uf5bb\"\n#define ICON_FA_SPACE_SHUTTLE u8\"\\uf197\"\n#define ICON_FA_SPELL_CHECK u8\"\\uf891\"\n#define ICON_FA_SPIDER u8\"\\uf717\"\n#define ICON_FA_SPINNER u8\"\\uf110\"\n#define ICON_FA_SPLOTCH u8\"\\uf5bc\"\n#define ICON_FA_SPRAY_CAN u8\"\\uf5bd\"\n#define ICON_FA_SQUARE u8\"\\uf0c8\"\n#define ICON_FA_SQUARE_FULL u8\"\\uf45c\"\n#define ICON_FA_SQUARE_ROOT_ALT u8\"\\uf698\"\n#define ICON_FA_STAMP u8\"\\uf5bf\"\n#define ICON_FA_STAR u8\"\\uf005\"\n#define ICON_FA_STAR_AND_CRESCENT u8\"\\uf699\"\n#define ICON_FA_STAR_HALF u8\"\\uf089\"\n#define ICON_FA_STAR_HALF_ALT u8\"\\uf5c0\"\n#define ICON_FA_STAR_OF_DAVID u8\"\\uf69a\"\n#define ICON_FA_STAR_OF_LIFE u8\"\\uf621\"\n#define ICON_FA_STEP_BACKWARD u8\"\\uf048\"\n#define ICON_FA_STEP_FORWARD u8\"\\uf051\"\n#define ICON_FA_STETHOSCOPE u8\"\\uf0f1\"\n#define ICON_FA_STICKY_NOTE u8\"\\uf249\"\n#define ICON_FA_STOP u8\"\\uf04d\"\n#define ICON_FA_STOP_CIRCLE u8\"\\uf28d\"\n#define ICON_FA_STOPWATCH u8\"\\uf2f2\"\n#define ICON_FA_STOPWATCH_20 u8\"\\uf96f\"\n#define ICON_FA_STORE u8\"\\uf54e\"\n#define ICON_FA_STORE_ALT u8\"\\uf54f\"\n#define ICON_FA_STORE_ALT_SLASH u8\"\\uf970\"\n#define ICON_FA_STORE_SLASH u8\"\\uf971\"\n#define ICON_FA_STREAM u8\"\\uf550\"\n#define ICON_FA_STREET_VIEW u8\"\\uf21d\"\n#define ICON_FA_STRIKETHROUGH u8\"\\uf0cc\"\n#define ICON_FA_STROOPWAFEL u8\"\\uf551\"\n#define ICON_FA_SUBSCRIPT u8\"\\uf12c\"\n#define ICON_FA_SUBWAY u8\"\\uf239\"\n#define ICON_FA_SUITCASE u8\"\\uf0f2\"\n#define ICON_FA_SUITCASE_ROLLING u8\"\\uf5c1\"\n#define ICON_FA_SUN u8\"\\uf185\"\n#define ICON_FA_SUPERSCRIPT u8\"\\uf12b\"\n#define ICON_FA_SURPRISE u8\"\\uf5c2\"\n#define ICON_FA_SWATCHBOOK u8\"\\uf5c3\"\n#define ICON_FA_SWIMMER u8\"\\uf5c4\"\n#define ICON_FA_SWIMMING_POOL u8\"\\uf5c5\"\n#define ICON_FA_SYNAGOGUE u8\"\\uf69b\"\n#define ICON_FA_SYNC u8\"\\uf021\"\n#define ICON_FA_SYNC_ALT u8\"\\uf2f1\"\n#define ICON_FA_SYRINGE u8\"\\uf48e\"\n#define ICON_FA_TABLE u8\"\\uf0ce\"\n#define ICON_FA_TABLE_TENNIS u8\"\\uf45d\"\n#define ICON_FA_TABLET u8\"\\uf10a\"\n#define ICON_FA_TABLET_ALT u8\"\\uf3fa\"\n#define ICON_FA_TABLETS u8\"\\uf490\"\n#define ICON_FA_TACHOMETER_ALT u8\"\\uf3fd\"\n#define ICON_FA_TAG u8\"\\uf02b\"\n#define ICON_FA_TAGS u8\"\\uf02c\"\n#define ICON_FA_TAPE u8\"\\uf4db\"\n#define ICON_FA_TASKS u8\"\\uf0ae\"\n#define ICON_FA_TAXI u8\"\\uf1ba\"\n#define ICON_FA_TEETH u8\"\\uf62e\"\n#define ICON_FA_TEETH_OPEN u8\"\\uf62f\"\n#define ICON_FA_TEMPERATURE_HIGH u8\"\\uf769\"\n#define ICON_FA_TEMPERATURE_LOW u8\"\\uf76b\"\n#define ICON_FA_TENGE u8\"\\uf7d7\"\n#define ICON_FA_TERMINAL u8\"\\uf120\"\n#define ICON_FA_TEXT_HEIGHT u8\"\\uf034\"\n#define ICON_FA_TEXT_WIDTH u8\"\\uf035\"\n#define ICON_FA_TH u8\"\\uf00a\"\n#define ICON_FA_TH_LARGE u8\"\\uf009\"\n#define ICON_FA_TH_LIST u8\"\\uf00b\"\n#define ICON_FA_THEATER_MASKS u8\"\\uf630\"\n#define ICON_FA_THERMOMETER u8\"\\uf491\"\n#define ICON_FA_THERMOMETER_EMPTY u8\"\\uf2cb\"\n#define ICON_FA_THERMOMETER_FULL u8\"\\uf2c7\"\n#define ICON_FA_THERMOMETER_HALF u8\"\\uf2c9\"\n#define ICON_FA_THERMOMETER_QUARTER u8\"\\uf2ca\"\n#define ICON_FA_THERMOMETER_THREE_QUARTERS u8\"\\uf2c8\"\n#define ICON_FA_THUMBS_DOWN u8\"\\uf165\"\n#define ICON_FA_THUMBS_UP u8\"\\uf164\"\n#define ICON_FA_THUMBTACK u8\"\\uf08d\"\n#define ICON_FA_TICKET_ALT u8\"\\uf3ff\"\n#define ICON_FA_TIMES u8\"\\uf00d\"\n#define ICON_FA_TIMES_CIRCLE u8\"\\uf057\"\n#define ICON_FA_TINT u8\"\\uf043\"\n#define ICON_FA_TINT_SLASH u8\"\\uf5c7\"\n#define ICON_FA_TIRED u8\"\\uf5c8\"\n#define ICON_FA_TOGGLE_OFF u8\"\\uf204\"\n#define ICON_FA_TOGGLE_ON u8\"\\uf205\"\n#define ICON_FA_TOILET u8\"\\uf7d8\"\n#define ICON_FA_TOILET_PAPER u8\"\\uf71e\"\n#define ICON_FA_TOILET_PAPER_SLASH u8\"\\uf972\"\n#define ICON_FA_TOOLBOX u8\"\\uf552\"\n#define ICON_FA_TOOLS u8\"\\uf7d9\"\n#define ICON_FA_TOOTH u8\"\\uf5c9\"\n#define ICON_FA_TORAH u8\"\\uf6a0\"\n#define ICON_FA_TORII_GATE u8\"\\uf6a1\"\n#define ICON_FA_TRACTOR u8\"\\uf722\"\n#define ICON_FA_TRADEMARK u8\"\\uf25c\"\n#define ICON_FA_TRAFFIC_LIGHT u8\"\\uf637\"\n#define ICON_FA_TRAILER u8\"\\uf941\"\n#define ICON_FA_TRAIN u8\"\\uf238\"\n#define ICON_FA_TRAM u8\"\\uf7da\"\n#define ICON_FA_TRANSGENDER u8\"\\uf224\"\n#define ICON_FA_TRANSGENDER_ALT u8\"\\uf225\"\n#define ICON_FA_TRASH u8\"\\uf1f8\"\n#define ICON_FA_TRASH_ALT u8\"\\uf2ed\"\n#define ICON_FA_TRASH_RESTORE u8\"\\uf829\"\n#define ICON_FA_TRASH_RESTORE_ALT u8\"\\uf82a\"\n#define ICON_FA_TREE u8\"\\uf1bb\"\n#define ICON_FA_TROPHY u8\"\\uf091\"\n#define ICON_FA_TRUCK u8\"\\uf0d1\"\n#define ICON_FA_TRUCK_LOADING u8\"\\uf4de\"\n#define ICON_FA_TRUCK_MONSTER u8\"\\uf63b\"\n#define ICON_FA_TRUCK_MOVING u8\"\\uf4df\"\n#define ICON_FA_TRUCK_PICKUP u8\"\\uf63c\"\n#define ICON_FA_TSHIRT u8\"\\uf553\"\n#define ICON_FA_TTY u8\"\\uf1e4\"\n#define ICON_FA_TV u8\"\\uf26c\"\n#define ICON_FA_UMBRELLA u8\"\\uf0e9\"\n#define ICON_FA_UMBRELLA_BEACH u8\"\\uf5ca\"\n#define ICON_FA_UNDERLINE u8\"\\uf0cd\"\n#define ICON_FA_UNDO u8\"\\uf0e2\"\n#define ICON_FA_UNDO_ALT u8\"\\uf2ea\"\n#define ICON_FA_UNIVERSAL_ACCESS u8\"\\uf29a\"\n#define ICON_FA_UNIVERSITY u8\"\\uf19c\"\n#define ICON_FA_UNLINK u8\"\\uf127\"\n#define ICON_FA_UNLOCK u8\"\\uf09c\"\n#define ICON_FA_UNLOCK_ALT u8\"\\uf13e\"\n#define ICON_FA_UPLOAD u8\"\\uf093\"\n#define ICON_FA_USER u8\"\\uf007\"\n#define ICON_FA_USER_ALT u8\"\\uf406\"\n#define ICON_FA_USER_ALT_SLASH u8\"\\uf4fa\"\n#define ICON_FA_USER_ASTRONAUT u8\"\\uf4fb\"\n#define ICON_FA_USER_CHECK u8\"\\uf4fc\"\n#define ICON_FA_USER_CIRCLE u8\"\\uf2bd\"\n#define ICON_FA_USER_CLOCK u8\"\\uf4fd\"\n#define ICON_FA_USER_COG u8\"\\uf4fe\"\n#define ICON_FA_USER_EDIT u8\"\\uf4ff\"\n#define ICON_FA_USER_FRIENDS u8\"\\uf500\"\n#define ICON_FA_USER_GRADUATE u8\"\\uf501\"\n#define ICON_FA_USER_INJURED u8\"\\uf728\"\n#define ICON_FA_USER_LOCK u8\"\\uf502\"\n#define ICON_FA_USER_MD u8\"\\uf0f0\"\n#define ICON_FA_USER_MINUS u8\"\\uf503\"\n#define ICON_FA_USER_NINJA u8\"\\uf504\"\n#define ICON_FA_USER_NURSE u8\"\\uf82f\"\n#define ICON_FA_USER_PLUS u8\"\\uf234\"\n#define ICON_FA_USER_SECRET u8\"\\uf21b\"\n#define ICON_FA_USER_SHIELD u8\"\\uf505\"\n#define ICON_FA_USER_SLASH u8\"\\uf506\"\n#define ICON_FA_USER_TAG u8\"\\uf507\"\n#define ICON_FA_USER_TIE u8\"\\uf508\"\n#define ICON_FA_USER_TIMES u8\"\\uf235\"\n#define ICON_FA_USERS u8\"\\uf0c0\"\n#define ICON_FA_USERS_COG u8\"\\uf509\"\n#define ICON_FA_USERS_SLASH u8\"\\uf973\"\n#define ICON_FA_UTENSIL_SPOON u8\"\\uf2e5\"\n#define ICON_FA_UTENSILS u8\"\\uf2e7\"\n#define ICON_FA_VECTOR_SQUARE u8\"\\uf5cb\"\n#define ICON_FA_VENUS u8\"\\uf221\"\n#define ICON_FA_VENUS_DOUBLE u8\"\\uf226\"\n#define ICON_FA_VENUS_MARS u8\"\\uf228\"\n#define ICON_FA_VIAL u8\"\\uf492\"\n#define ICON_FA_VIALS u8\"\\uf493\"\n#define ICON_FA_VIDEO u8\"\\uf03d\"\n#define ICON_FA_VIDEO_SLASH u8\"\\uf4e2\"\n#define ICON_FA_VIHARA u8\"\\uf6a7\"\n#define ICON_FA_VIRUS u8\"\\uf974\"\n#define ICON_FA_VIRUS_SLASH u8\"\\uf975\"\n#define ICON_FA_VIRUSES u8\"\\uf976\"\n#define ICON_FA_VOICEMAIL u8\"\\uf897\"\n#define ICON_FA_VOLLEYBALL_BALL u8\"\\uf45f\"\n#define ICON_FA_VOLUME_DOWN u8\"\\uf027\"\n#define ICON_FA_VOLUME_MUTE u8\"\\uf6a9\"\n#define ICON_FA_VOLUME_OFF u8\"\\uf026\"\n#define ICON_FA_VOLUME_UP u8\"\\uf028\"\n#define ICON_FA_VOTE_YEA u8\"\\uf772\"\n#define ICON_FA_VR_CARDBOARD u8\"\\uf729\"\n#define ICON_FA_WALKING u8\"\\uf554\"\n#define ICON_FA_WALLET u8\"\\uf555\"\n#define ICON_FA_WAREHOUSE u8\"\\uf494\"\n#define ICON_FA_WATER u8\"\\uf773\"\n#define ICON_FA_WAVE_SQUARE u8\"\\uf83e\"\n#define ICON_FA_WEIGHT u8\"\\uf496\"\n#define ICON_FA_WEIGHT_HANGING u8\"\\uf5cd\"\n#define ICON_FA_WHEELCHAIR u8\"\\uf193\"\n#define ICON_FA_WIFI u8\"\\uf1eb\"\n#define ICON_FA_WIND u8\"\\uf72e\"\n#define ICON_FA_WINDOW_CLOSE u8\"\\uf410\"\n#define ICON_FA_WINDOW_MAXIMIZE u8\"\\uf2d0\"\n#define ICON_FA_WINDOW_MINIMIZE u8\"\\uf2d1\"\n#define ICON_FA_WINDOW_RESTORE u8\"\\uf2d2\"\n#define ICON_FA_WINE_BOTTLE u8\"\\uf72f\"\n#define ICON_FA_WINE_GLASS u8\"\\uf4e3\"\n#define ICON_FA_WINE_GLASS_ALT u8\"\\uf5ce\"\n#define ICON_FA_WON_SIGN u8\"\\uf159\"\n#define ICON_FA_WRENCH u8\"\\uf0ad\"\n#define ICON_FA_X_RAY u8\"\\uf497\"\n#define ICON_FA_YEN_SIGN u8\"\\uf157\"\n#define ICON_FA_YIN_YANG u8\"\\uf6ad\"\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/IconFontCppHeaders/IconsFontAwesome5Pro.h",
    "content": "// Generated by https://github.com/juliettef/IconFontCppHeaders script GenerateIconFontCppHeaders.py for language C++11\n// from icons.yml\n// for use with fa-light-300.ttf, fa-regular-400.ttf, fa-solid-900.ttf\n#pragma once\n\n#define FONT_ICON_FILE_NAME_FAL \"fa-light-300.ttf\"\n#define FONT_ICON_FILE_NAME_FAR \"fa-regular-400.ttf\"\n#define FONT_ICON_FILE_NAME_FAS \"fa-solid-900.ttf\"\n\n#define ICON_MIN_FA 0xf000\n#define ICON_MAX_FA 0xf976\n#define ICON_FA_ABACUS u8\"\\uf640\"\n#define ICON_FA_ACORN u8\"\\uf6ae\"\n#define ICON_FA_AD u8\"\\uf641\"\n#define ICON_FA_ADDRESS_BOOK u8\"\\uf2b9\"\n#define ICON_FA_ADDRESS_CARD u8\"\\uf2bb\"\n#define ICON_FA_ADJUST u8\"\\uf042\"\n#define ICON_FA_AIR_CONDITIONER u8\"\\uf8f4\"\n#define ICON_FA_AIR_FRESHENER u8\"\\uf5d0\"\n#define ICON_FA_ALARM_CLOCK u8\"\\uf34e\"\n#define ICON_FA_ALARM_EXCLAMATION u8\"\\uf843\"\n#define ICON_FA_ALARM_PLUS u8\"\\uf844\"\n#define ICON_FA_ALARM_SNOOZE u8\"\\uf845\"\n#define ICON_FA_ALBUM u8\"\\uf89f\"\n#define ICON_FA_ALBUM_COLLECTION u8\"\\uf8a0\"\n#define ICON_FA_ALICORN u8\"\\uf6b0\"\n#define ICON_FA_ALIEN u8\"\\uf8f5\"\n#define ICON_FA_ALIEN_MONSTER u8\"\\uf8f6\"\n#define ICON_FA_ALIGN_CENTER u8\"\\uf037\"\n#define ICON_FA_ALIGN_JUSTIFY u8\"\\uf039\"\n#define ICON_FA_ALIGN_LEFT u8\"\\uf036\"\n#define ICON_FA_ALIGN_RIGHT u8\"\\uf038\"\n#define ICON_FA_ALIGN_SLASH u8\"\\uf846\"\n#define ICON_FA_ALLERGIES u8\"\\uf461\"\n#define ICON_FA_AMBULANCE u8\"\\uf0f9\"\n#define ICON_FA_AMERICAN_SIGN_LANGUAGE_INTERPRETING u8\"\\uf2a3\"\n#define ICON_FA_AMP_GUITAR u8\"\\uf8a1\"\n#define ICON_FA_ANALYTICS u8\"\\uf643\"\n#define ICON_FA_ANCHOR u8\"\\uf13d\"\n#define ICON_FA_ANGEL u8\"\\uf779\"\n#define ICON_FA_ANGLE_DOUBLE_DOWN u8\"\\uf103\"\n#define ICON_FA_ANGLE_DOUBLE_LEFT u8\"\\uf100\"\n#define ICON_FA_ANGLE_DOUBLE_RIGHT u8\"\\uf101\"\n#define ICON_FA_ANGLE_DOUBLE_UP u8\"\\uf102\"\n#define ICON_FA_ANGLE_DOWN u8\"\\uf107\"\n#define ICON_FA_ANGLE_LEFT u8\"\\uf104\"\n#define ICON_FA_ANGLE_RIGHT u8\"\\uf105\"\n#define ICON_FA_ANGLE_UP u8\"\\uf106\"\n#define ICON_FA_ANGRY u8\"\\uf556\"\n#define ICON_FA_ANKH u8\"\\uf644\"\n#define ICON_FA_APPLE_ALT u8\"\\uf5d1\"\n#define ICON_FA_APPLE_CRATE u8\"\\uf6b1\"\n#define ICON_FA_ARCHIVE u8\"\\uf187\"\n#define ICON_FA_ARCHWAY u8\"\\uf557\"\n#define ICON_FA_ARROW_ALT_CIRCLE_DOWN u8\"\\uf358\"\n#define ICON_FA_ARROW_ALT_CIRCLE_LEFT u8\"\\uf359\"\n#define ICON_FA_ARROW_ALT_CIRCLE_RIGHT u8\"\\uf35a\"\n#define ICON_FA_ARROW_ALT_CIRCLE_UP u8\"\\uf35b\"\n#define ICON_FA_ARROW_ALT_DOWN u8\"\\uf354\"\n#define ICON_FA_ARROW_ALT_FROM_BOTTOM u8\"\\uf346\"\n#define ICON_FA_ARROW_ALT_FROM_LEFT u8\"\\uf347\"\n#define ICON_FA_ARROW_ALT_FROM_RIGHT u8\"\\uf348\"\n#define ICON_FA_ARROW_ALT_FROM_TOP u8\"\\uf349\"\n#define ICON_FA_ARROW_ALT_LEFT u8\"\\uf355\"\n#define ICON_FA_ARROW_ALT_RIGHT u8\"\\uf356\"\n#define ICON_FA_ARROW_ALT_SQUARE_DOWN u8\"\\uf350\"\n#define ICON_FA_ARROW_ALT_SQUARE_LEFT u8\"\\uf351\"\n#define ICON_FA_ARROW_ALT_SQUARE_RIGHT u8\"\\uf352\"\n#define ICON_FA_ARROW_ALT_SQUARE_UP u8\"\\uf353\"\n#define ICON_FA_ARROW_ALT_TO_BOTTOM u8\"\\uf34a\"\n#define ICON_FA_ARROW_ALT_TO_LEFT u8\"\\uf34b\"\n#define ICON_FA_ARROW_ALT_TO_RIGHT u8\"\\uf34c\"\n#define ICON_FA_ARROW_ALT_TO_TOP u8\"\\uf34d\"\n#define ICON_FA_ARROW_ALT_UP u8\"\\uf357\"\n#define ICON_FA_ARROW_CIRCLE_DOWN u8\"\\uf0ab\"\n#define ICON_FA_ARROW_CIRCLE_LEFT u8\"\\uf0a8\"\n#define ICON_FA_ARROW_CIRCLE_RIGHT u8\"\\uf0a9\"\n#define ICON_FA_ARROW_CIRCLE_UP u8\"\\uf0aa\"\n#define ICON_FA_ARROW_DOWN u8\"\\uf063\"\n#define ICON_FA_ARROW_FROM_BOTTOM u8\"\\uf342\"\n#define ICON_FA_ARROW_FROM_LEFT u8\"\\uf343\"\n#define ICON_FA_ARROW_FROM_RIGHT u8\"\\uf344\"\n#define ICON_FA_ARROW_FROM_TOP u8\"\\uf345\"\n#define ICON_FA_ARROW_LEFT u8\"\\uf060\"\n#define ICON_FA_ARROW_RIGHT u8\"\\uf061\"\n#define ICON_FA_ARROW_SQUARE_DOWN u8\"\\uf339\"\n#define ICON_FA_ARROW_SQUARE_LEFT u8\"\\uf33a\"\n#define ICON_FA_ARROW_SQUARE_RIGHT u8\"\\uf33b\"\n#define ICON_FA_ARROW_SQUARE_UP u8\"\\uf33c\"\n#define ICON_FA_ARROW_TO_BOTTOM u8\"\\uf33d\"\n#define ICON_FA_ARROW_TO_LEFT u8\"\\uf33e\"\n#define ICON_FA_ARROW_TO_RIGHT u8\"\\uf340\"\n#define ICON_FA_ARROW_TO_TOP u8\"\\uf341\"\n#define ICON_FA_ARROW_UP u8\"\\uf062\"\n#define ICON_FA_ARROWS u8\"\\uf047\"\n#define ICON_FA_ARROWS_ALT u8\"\\uf0b2\"\n#define ICON_FA_ARROWS_ALT_H u8\"\\uf337\"\n#define ICON_FA_ARROWS_ALT_V u8\"\\uf338\"\n#define ICON_FA_ARROWS_H u8\"\\uf07e\"\n#define ICON_FA_ARROWS_V u8\"\\uf07d\"\n#define ICON_FA_ASSISTIVE_LISTENING_SYSTEMS u8\"\\uf2a2\"\n#define ICON_FA_ASTERISK u8\"\\uf069\"\n#define ICON_FA_AT u8\"\\uf1fa\"\n#define ICON_FA_ATLAS u8\"\\uf558\"\n#define ICON_FA_ATOM u8\"\\uf5d2\"\n#define ICON_FA_ATOM_ALT u8\"\\uf5d3\"\n#define ICON_FA_AUDIO_DESCRIPTION u8\"\\uf29e\"\n#define ICON_FA_AWARD u8\"\\uf559\"\n#define ICON_FA_AXE u8\"\\uf6b2\"\n#define ICON_FA_AXE_BATTLE u8\"\\uf6b3\"\n#define ICON_FA_BABY u8\"\\uf77c\"\n#define ICON_FA_BABY_CARRIAGE u8\"\\uf77d\"\n#define ICON_FA_BACKPACK u8\"\\uf5d4\"\n#define ICON_FA_BACKSPACE u8\"\\uf55a\"\n#define ICON_FA_BACKWARD u8\"\\uf04a\"\n#define ICON_FA_BACON u8\"\\uf7e5\"\n#define ICON_FA_BACTERIA u8\"\\uf959\"\n#define ICON_FA_BACTERIUM u8\"\\uf95a\"\n#define ICON_FA_BADGE u8\"\\uf335\"\n#define ICON_FA_BADGE_CHECK u8\"\\uf336\"\n#define ICON_FA_BADGE_DOLLAR u8\"\\uf645\"\n#define ICON_FA_BADGE_PERCENT u8\"\\uf646\"\n#define ICON_FA_BADGE_SHERIFF u8\"\\uf8a2\"\n#define ICON_FA_BADGER_HONEY u8\"\\uf6b4\"\n#define ICON_FA_BAGS_SHOPPING u8\"\\uf847\"\n#define ICON_FA_BAHAI u8\"\\uf666\"\n#define ICON_FA_BALANCE_SCALE u8\"\\uf24e\"\n#define ICON_FA_BALANCE_SCALE_LEFT u8\"\\uf515\"\n#define ICON_FA_BALANCE_SCALE_RIGHT u8\"\\uf516\"\n#define ICON_FA_BALL_PILE u8\"\\uf77e\"\n#define ICON_FA_BALLOT u8\"\\uf732\"\n#define ICON_FA_BALLOT_CHECK u8\"\\uf733\"\n#define ICON_FA_BAN u8\"\\uf05e\"\n#define ICON_FA_BAND_AID u8\"\\uf462\"\n#define ICON_FA_BANJO u8\"\\uf8a3\"\n#define ICON_FA_BARCODE u8\"\\uf02a\"\n#define ICON_FA_BARCODE_ALT u8\"\\uf463\"\n#define ICON_FA_BARCODE_READ u8\"\\uf464\"\n#define ICON_FA_BARCODE_SCAN u8\"\\uf465\"\n#define ICON_FA_BARS u8\"\\uf0c9\"\n#define ICON_FA_BASEBALL u8\"\\uf432\"\n#define ICON_FA_BASEBALL_BALL u8\"\\uf433\"\n#define ICON_FA_BASKETBALL_BALL u8\"\\uf434\"\n#define ICON_FA_BASKETBALL_HOOP u8\"\\uf435\"\n#define ICON_FA_BAT u8\"\\uf6b5\"\n#define ICON_FA_BATH u8\"\\uf2cd\"\n#define ICON_FA_BATTERY_BOLT u8\"\\uf376\"\n#define ICON_FA_BATTERY_EMPTY u8\"\\uf244\"\n#define ICON_FA_BATTERY_FULL u8\"\\uf240\"\n#define ICON_FA_BATTERY_HALF u8\"\\uf242\"\n#define ICON_FA_BATTERY_QUARTER u8\"\\uf243\"\n#define ICON_FA_BATTERY_SLASH u8\"\\uf377\"\n#define ICON_FA_BATTERY_THREE_QUARTERS u8\"\\uf241\"\n#define ICON_FA_BED u8\"\\uf236\"\n#define ICON_FA_BED_ALT u8\"\\uf8f7\"\n#define ICON_FA_BED_BUNK u8\"\\uf8f8\"\n#define ICON_FA_BED_EMPTY u8\"\\uf8f9\"\n#define ICON_FA_BEER u8\"\\uf0fc\"\n#define ICON_FA_BELL u8\"\\uf0f3\"\n#define ICON_FA_BELL_EXCLAMATION u8\"\\uf848\"\n#define ICON_FA_BELL_ON u8\"\\uf8fa\"\n#define ICON_FA_BELL_PLUS u8\"\\uf849\"\n#define ICON_FA_BELL_SCHOOL u8\"\\uf5d5\"\n#define ICON_FA_BELL_SCHOOL_SLASH u8\"\\uf5d6\"\n#define ICON_FA_BELL_SLASH u8\"\\uf1f6\"\n#define ICON_FA_BELLS u8\"\\uf77f\"\n#define ICON_FA_BETAMAX u8\"\\uf8a4\"\n#define ICON_FA_BEZIER_CURVE u8\"\\uf55b\"\n#define ICON_FA_BIBLE u8\"\\uf647\"\n#define ICON_FA_BICYCLE u8\"\\uf206\"\n#define ICON_FA_BIKING u8\"\\uf84a\"\n#define ICON_FA_BIKING_MOUNTAIN u8\"\\uf84b\"\n#define ICON_FA_BINOCULARS u8\"\\uf1e5\"\n#define ICON_FA_BIOHAZARD u8\"\\uf780\"\n#define ICON_FA_BIRTHDAY_CAKE u8\"\\uf1fd\"\n#define ICON_FA_BLANKET u8\"\\uf498\"\n#define ICON_FA_BLENDER u8\"\\uf517\"\n#define ICON_FA_BLENDER_PHONE u8\"\\uf6b6\"\n#define ICON_FA_BLIND u8\"\\uf29d\"\n#define ICON_FA_BLINDS u8\"\\uf8fb\"\n#define ICON_FA_BLINDS_OPEN u8\"\\uf8fc\"\n#define ICON_FA_BLINDS_RAISED u8\"\\uf8fd\"\n#define ICON_FA_BLOG u8\"\\uf781\"\n#define ICON_FA_BOLD u8\"\\uf032\"\n#define ICON_FA_BOLT u8\"\\uf0e7\"\n#define ICON_FA_BOMB u8\"\\uf1e2\"\n#define ICON_FA_BONE u8\"\\uf5d7\"\n#define ICON_FA_BONE_BREAK u8\"\\uf5d8\"\n#define ICON_FA_BONG u8\"\\uf55c\"\n#define ICON_FA_BOOK u8\"\\uf02d\"\n#define ICON_FA_BOOK_ALT u8\"\\uf5d9\"\n#define ICON_FA_BOOK_DEAD u8\"\\uf6b7\"\n#define ICON_FA_BOOK_HEART u8\"\\uf499\"\n#define ICON_FA_BOOK_MEDICAL u8\"\\uf7e6\"\n#define ICON_FA_BOOK_OPEN u8\"\\uf518\"\n#define ICON_FA_BOOK_READER u8\"\\uf5da\"\n#define ICON_FA_BOOK_SPELLS u8\"\\uf6b8\"\n#define ICON_FA_BOOK_USER u8\"\\uf7e7\"\n#define ICON_FA_BOOKMARK u8\"\\uf02e\"\n#define ICON_FA_BOOKS u8\"\\uf5db\"\n#define ICON_FA_BOOKS_MEDICAL u8\"\\uf7e8\"\n#define ICON_FA_BOOMBOX u8\"\\uf8a5\"\n#define ICON_FA_BOOT u8\"\\uf782\"\n#define ICON_FA_BOOTH_CURTAIN u8\"\\uf734\"\n#define ICON_FA_BORDER_ALL u8\"\\uf84c\"\n#define ICON_FA_BORDER_BOTTOM u8\"\\uf84d\"\n#define ICON_FA_BORDER_CENTER_H u8\"\\uf89c\"\n#define ICON_FA_BORDER_CENTER_V u8\"\\uf89d\"\n#define ICON_FA_BORDER_INNER u8\"\\uf84e\"\n#define ICON_FA_BORDER_LEFT u8\"\\uf84f\"\n#define ICON_FA_BORDER_NONE u8\"\\uf850\"\n#define ICON_FA_BORDER_OUTER u8\"\\uf851\"\n#define ICON_FA_BORDER_RIGHT u8\"\\uf852\"\n#define ICON_FA_BORDER_STYLE u8\"\\uf853\"\n#define ICON_FA_BORDER_STYLE_ALT u8\"\\uf854\"\n#define ICON_FA_BORDER_TOP u8\"\\uf855\"\n#define ICON_FA_BOW_ARROW u8\"\\uf6b9\"\n#define ICON_FA_BOWLING_BALL u8\"\\uf436\"\n#define ICON_FA_BOWLING_PINS u8\"\\uf437\"\n#define ICON_FA_BOX u8\"\\uf466\"\n#define ICON_FA_BOX_ALT u8\"\\uf49a\"\n#define ICON_FA_BOX_BALLOT u8\"\\uf735\"\n#define ICON_FA_BOX_CHECK u8\"\\uf467\"\n#define ICON_FA_BOX_FRAGILE u8\"\\uf49b\"\n#define ICON_FA_BOX_FULL u8\"\\uf49c\"\n#define ICON_FA_BOX_HEART u8\"\\uf49d\"\n#define ICON_FA_BOX_OPEN u8\"\\uf49e\"\n#define ICON_FA_BOX_TISSUE u8\"\\uf95b\"\n#define ICON_FA_BOX_UP u8\"\\uf49f\"\n#define ICON_FA_BOX_USD u8\"\\uf4a0\"\n#define ICON_FA_BOXES u8\"\\uf468\"\n#define ICON_FA_BOXES_ALT u8\"\\uf4a1\"\n#define ICON_FA_BOXING_GLOVE u8\"\\uf438\"\n#define ICON_FA_BRACKETS u8\"\\uf7e9\"\n#define ICON_FA_BRACKETS_CURLY u8\"\\uf7ea\"\n#define ICON_FA_BRAILLE u8\"\\uf2a1\"\n#define ICON_FA_BRAIN u8\"\\uf5dc\"\n#define ICON_FA_BREAD_LOAF u8\"\\uf7eb\"\n#define ICON_FA_BREAD_SLICE u8\"\\uf7ec\"\n#define ICON_FA_BRIEFCASE u8\"\\uf0b1\"\n#define ICON_FA_BRIEFCASE_MEDICAL u8\"\\uf469\"\n#define ICON_FA_BRING_FORWARD u8\"\\uf856\"\n#define ICON_FA_BRING_FRONT u8\"\\uf857\"\n#define ICON_FA_BROADCAST_TOWER u8\"\\uf519\"\n#define ICON_FA_BROOM u8\"\\uf51a\"\n#define ICON_FA_BROWSER u8\"\\uf37e\"\n#define ICON_FA_BRUSH u8\"\\uf55d\"\n#define ICON_FA_BUG u8\"\\uf188\"\n#define ICON_FA_BUILDING u8\"\\uf1ad\"\n#define ICON_FA_BULLHORN u8\"\\uf0a1\"\n#define ICON_FA_BULLSEYE u8\"\\uf140\"\n#define ICON_FA_BULLSEYE_ARROW u8\"\\uf648\"\n#define ICON_FA_BULLSEYE_POINTER u8\"\\uf649\"\n#define ICON_FA_BURGER_SODA u8\"\\uf858\"\n#define ICON_FA_BURN u8\"\\uf46a\"\n#define ICON_FA_BURRITO u8\"\\uf7ed\"\n#define ICON_FA_BUS u8\"\\uf207\"\n#define ICON_FA_BUS_ALT u8\"\\uf55e\"\n#define ICON_FA_BUS_SCHOOL u8\"\\uf5dd\"\n#define ICON_FA_BUSINESS_TIME u8\"\\uf64a\"\n#define ICON_FA_CABINET_FILING u8\"\\uf64b\"\n#define ICON_FA_CACTUS u8\"\\uf8a7\"\n#define ICON_FA_CALCULATOR u8\"\\uf1ec\"\n#define ICON_FA_CALCULATOR_ALT u8\"\\uf64c\"\n#define ICON_FA_CALENDAR u8\"\\uf133\"\n#define ICON_FA_CALENDAR_ALT u8\"\\uf073\"\n#define ICON_FA_CALENDAR_CHECK u8\"\\uf274\"\n#define ICON_FA_CALENDAR_DAY u8\"\\uf783\"\n#define ICON_FA_CALENDAR_EDIT u8\"\\uf333\"\n#define ICON_FA_CALENDAR_EXCLAMATION u8\"\\uf334\"\n#define ICON_FA_CALENDAR_MINUS u8\"\\uf272\"\n#define ICON_FA_CALENDAR_PLUS u8\"\\uf271\"\n#define ICON_FA_CALENDAR_STAR u8\"\\uf736\"\n#define ICON_FA_CALENDAR_TIMES u8\"\\uf273\"\n#define ICON_FA_CALENDAR_WEEK u8\"\\uf784\"\n#define ICON_FA_CAMCORDER u8\"\\uf8a8\"\n#define ICON_FA_CAMERA u8\"\\uf030\"\n#define ICON_FA_CAMERA_ALT u8\"\\uf332\"\n#define ICON_FA_CAMERA_HOME u8\"\\uf8fe\"\n#define ICON_FA_CAMERA_MOVIE u8\"\\uf8a9\"\n#define ICON_FA_CAMERA_POLAROID u8\"\\uf8aa\"\n#define ICON_FA_CAMERA_RETRO u8\"\\uf083\"\n#define ICON_FA_CAMPFIRE u8\"\\uf6ba\"\n#define ICON_FA_CAMPGROUND u8\"\\uf6bb\"\n#define ICON_FA_CANDLE_HOLDER u8\"\\uf6bc\"\n#define ICON_FA_CANDY_CANE u8\"\\uf786\"\n#define ICON_FA_CANDY_CORN u8\"\\uf6bd\"\n#define ICON_FA_CANNABIS u8\"\\uf55f\"\n#define ICON_FA_CAPSULES u8\"\\uf46b\"\n#define ICON_FA_CAR u8\"\\uf1b9\"\n#define ICON_FA_CAR_ALT u8\"\\uf5de\"\n#define ICON_FA_CAR_BATTERY u8\"\\uf5df\"\n#define ICON_FA_CAR_BUILDING u8\"\\uf859\"\n#define ICON_FA_CAR_BUMP u8\"\\uf5e0\"\n#define ICON_FA_CAR_BUS u8\"\\uf85a\"\n#define ICON_FA_CAR_CRASH u8\"\\uf5e1\"\n#define ICON_FA_CAR_GARAGE u8\"\\uf5e2\"\n#define ICON_FA_CAR_MECHANIC u8\"\\uf5e3\"\n#define ICON_FA_CAR_SIDE u8\"\\uf5e4\"\n#define ICON_FA_CAR_TILT u8\"\\uf5e5\"\n#define ICON_FA_CAR_WASH u8\"\\uf5e6\"\n#define ICON_FA_CARAVAN u8\"\\uf8ff\"\n#define ICON_FA_CARAVAN_ALT u8\"\\uf900\"\n#define ICON_FA_CARET_CIRCLE_DOWN u8\"\\uf32d\"\n#define ICON_FA_CARET_CIRCLE_LEFT u8\"\\uf32e\"\n#define ICON_FA_CARET_CIRCLE_RIGHT u8\"\\uf330\"\n#define ICON_FA_CARET_CIRCLE_UP u8\"\\uf331\"\n#define ICON_FA_CARET_DOWN u8\"\\uf0d7\"\n#define ICON_FA_CARET_LEFT u8\"\\uf0d9\"\n#define ICON_FA_CARET_RIGHT u8\"\\uf0da\"\n#define ICON_FA_CARET_SQUARE_DOWN u8\"\\uf150\"\n#define ICON_FA_CARET_SQUARE_LEFT u8\"\\uf191\"\n#define ICON_FA_CARET_SQUARE_RIGHT u8\"\\uf152\"\n#define ICON_FA_CARET_SQUARE_UP u8\"\\uf151\"\n#define ICON_FA_CARET_UP u8\"\\uf0d8\"\n#define ICON_FA_CARROT u8\"\\uf787\"\n#define ICON_FA_CARS u8\"\\uf85b\"\n#define ICON_FA_CART_ARROW_DOWN u8\"\\uf218\"\n#define ICON_FA_CART_PLUS u8\"\\uf217\"\n#define ICON_FA_CASH_REGISTER u8\"\\uf788\"\n#define ICON_FA_CASSETTE_TAPE u8\"\\uf8ab\"\n#define ICON_FA_CAT u8\"\\uf6be\"\n#define ICON_FA_CAT_SPACE u8\"\\uf901\"\n#define ICON_FA_CAULDRON u8\"\\uf6bf\"\n#define ICON_FA_CCTV u8\"\\uf8ac\"\n#define ICON_FA_CERTIFICATE u8\"\\uf0a3\"\n#define ICON_FA_CHAIR u8\"\\uf6c0\"\n#define ICON_FA_CHAIR_OFFICE u8\"\\uf6c1\"\n#define ICON_FA_CHALKBOARD u8\"\\uf51b\"\n#define ICON_FA_CHALKBOARD_TEACHER u8\"\\uf51c\"\n#define ICON_FA_CHARGING_STATION u8\"\\uf5e7\"\n#define ICON_FA_CHART_AREA u8\"\\uf1fe\"\n#define ICON_FA_CHART_BAR u8\"\\uf080\"\n#define ICON_FA_CHART_LINE u8\"\\uf201\"\n#define ICON_FA_CHART_LINE_DOWN u8\"\\uf64d\"\n#define ICON_FA_CHART_NETWORK u8\"\\uf78a\"\n#define ICON_FA_CHART_PIE u8\"\\uf200\"\n#define ICON_FA_CHART_PIE_ALT u8\"\\uf64e\"\n#define ICON_FA_CHART_SCATTER u8\"\\uf7ee\"\n#define ICON_FA_CHECK u8\"\\uf00c\"\n#define ICON_FA_CHECK_CIRCLE u8\"\\uf058\"\n#define ICON_FA_CHECK_DOUBLE u8\"\\uf560\"\n#define ICON_FA_CHECK_SQUARE u8\"\\uf14a\"\n#define ICON_FA_CHEESE u8\"\\uf7ef\"\n#define ICON_FA_CHEESE_SWISS u8\"\\uf7f0\"\n#define ICON_FA_CHEESEBURGER u8\"\\uf7f1\"\n#define ICON_FA_CHESS u8\"\\uf439\"\n#define ICON_FA_CHESS_BISHOP u8\"\\uf43a\"\n#define ICON_FA_CHESS_BISHOP_ALT u8\"\\uf43b\"\n#define ICON_FA_CHESS_BOARD u8\"\\uf43c\"\n#define ICON_FA_CHESS_CLOCK u8\"\\uf43d\"\n#define ICON_FA_CHESS_CLOCK_ALT u8\"\\uf43e\"\n#define ICON_FA_CHESS_KING u8\"\\uf43f\"\n#define ICON_FA_CHESS_KING_ALT u8\"\\uf440\"\n#define ICON_FA_CHESS_KNIGHT u8\"\\uf441\"\n#define ICON_FA_CHESS_KNIGHT_ALT u8\"\\uf442\"\n#define ICON_FA_CHESS_PAWN u8\"\\uf443\"\n#define ICON_FA_CHESS_PAWN_ALT u8\"\\uf444\"\n#define ICON_FA_CHESS_QUEEN u8\"\\uf445\"\n#define ICON_FA_CHESS_QUEEN_ALT u8\"\\uf446\"\n#define ICON_FA_CHESS_ROOK u8\"\\uf447\"\n#define ICON_FA_CHESS_ROOK_ALT u8\"\\uf448\"\n#define ICON_FA_CHEVRON_CIRCLE_DOWN u8\"\\uf13a\"\n#define ICON_FA_CHEVRON_CIRCLE_LEFT u8\"\\uf137\"\n#define ICON_FA_CHEVRON_CIRCLE_RIGHT u8\"\\uf138\"\n#define ICON_FA_CHEVRON_CIRCLE_UP u8\"\\uf139\"\n#define ICON_FA_CHEVRON_DOUBLE_DOWN u8\"\\uf322\"\n#define ICON_FA_CHEVRON_DOUBLE_LEFT u8\"\\uf323\"\n#define ICON_FA_CHEVRON_DOUBLE_RIGHT u8\"\\uf324\"\n#define ICON_FA_CHEVRON_DOUBLE_UP u8\"\\uf325\"\n#define ICON_FA_CHEVRON_DOWN u8\"\\uf078\"\n#define ICON_FA_CHEVRON_LEFT u8\"\\uf053\"\n#define ICON_FA_CHEVRON_RIGHT u8\"\\uf054\"\n#define ICON_FA_CHEVRON_SQUARE_DOWN u8\"\\uf329\"\n#define ICON_FA_CHEVRON_SQUARE_LEFT u8\"\\uf32a\"\n#define ICON_FA_CHEVRON_SQUARE_RIGHT u8\"\\uf32b\"\n#define ICON_FA_CHEVRON_SQUARE_UP u8\"\\uf32c\"\n#define ICON_FA_CHEVRON_UP u8\"\\uf077\"\n#define ICON_FA_CHILD u8\"\\uf1ae\"\n#define ICON_FA_CHIMNEY u8\"\\uf78b\"\n#define ICON_FA_CHURCH u8\"\\uf51d\"\n#define ICON_FA_CIRCLE u8\"\\uf111\"\n#define ICON_FA_CIRCLE_NOTCH u8\"\\uf1ce\"\n#define ICON_FA_CITY u8\"\\uf64f\"\n#define ICON_FA_CLARINET u8\"\\uf8ad\"\n#define ICON_FA_CLAW_MARKS u8\"\\uf6c2\"\n#define ICON_FA_CLINIC_MEDICAL u8\"\\uf7f2\"\n#define ICON_FA_CLIPBOARD u8\"\\uf328\"\n#define ICON_FA_CLIPBOARD_CHECK u8\"\\uf46c\"\n#define ICON_FA_CLIPBOARD_LIST u8\"\\uf46d\"\n#define ICON_FA_CLIPBOARD_LIST_CHECK u8\"\\uf737\"\n#define ICON_FA_CLIPBOARD_PRESCRIPTION u8\"\\uf5e8\"\n#define ICON_FA_CLIPBOARD_USER u8\"\\uf7f3\"\n#define ICON_FA_CLOCK u8\"\\uf017\"\n#define ICON_FA_CLONE u8\"\\uf24d\"\n#define ICON_FA_CLOSED_CAPTIONING u8\"\\uf20a\"\n#define ICON_FA_CLOUD u8\"\\uf0c2\"\n#define ICON_FA_CLOUD_DOWNLOAD u8\"\\uf0ed\"\n#define ICON_FA_CLOUD_DOWNLOAD_ALT u8\"\\uf381\"\n#define ICON_FA_CLOUD_DRIZZLE u8\"\\uf738\"\n#define ICON_FA_CLOUD_HAIL u8\"\\uf739\"\n#define ICON_FA_CLOUD_HAIL_MIXED u8\"\\uf73a\"\n#define ICON_FA_CLOUD_MEATBALL u8\"\\uf73b\"\n#define ICON_FA_CLOUD_MOON u8\"\\uf6c3\"\n#define ICON_FA_CLOUD_MOON_RAIN u8\"\\uf73c\"\n#define ICON_FA_CLOUD_MUSIC u8\"\\uf8ae\"\n#define ICON_FA_CLOUD_RAIN u8\"\\uf73d\"\n#define ICON_FA_CLOUD_RAINBOW u8\"\\uf73e\"\n#define ICON_FA_CLOUD_SHOWERS u8\"\\uf73f\"\n#define ICON_FA_CLOUD_SHOWERS_HEAVY u8\"\\uf740\"\n#define ICON_FA_CLOUD_SLEET u8\"\\uf741\"\n#define ICON_FA_CLOUD_SNOW u8\"\\uf742\"\n#define ICON_FA_CLOUD_SUN u8\"\\uf6c4\"\n#define ICON_FA_CLOUD_SUN_RAIN u8\"\\uf743\"\n#define ICON_FA_CLOUD_UPLOAD u8\"\\uf0ee\"\n#define ICON_FA_CLOUD_UPLOAD_ALT u8\"\\uf382\"\n#define ICON_FA_CLOUDS u8\"\\uf744\"\n#define ICON_FA_CLOUDS_MOON u8\"\\uf745\"\n#define ICON_FA_CLOUDS_SUN u8\"\\uf746\"\n#define ICON_FA_CLUB u8\"\\uf327\"\n#define ICON_FA_COCKTAIL u8\"\\uf561\"\n#define ICON_FA_CODE u8\"\\uf121\"\n#define ICON_FA_CODE_BRANCH u8\"\\uf126\"\n#define ICON_FA_CODE_COMMIT u8\"\\uf386\"\n#define ICON_FA_CODE_MERGE u8\"\\uf387\"\n#define ICON_FA_COFFEE u8\"\\uf0f4\"\n#define ICON_FA_COFFEE_POT u8\"\\uf902\"\n#define ICON_FA_COFFEE_TOGO u8\"\\uf6c5\"\n#define ICON_FA_COFFIN u8\"\\uf6c6\"\n#define ICON_FA_COFFIN_CROSS u8\"\\uf951\"\n#define ICON_FA_COG u8\"\\uf013\"\n#define ICON_FA_COGS u8\"\\uf085\"\n#define ICON_FA_COIN u8\"\\uf85c\"\n#define ICON_FA_COINS u8\"\\uf51e\"\n#define ICON_FA_COLUMNS u8\"\\uf0db\"\n#define ICON_FA_COMET u8\"\\uf903\"\n#define ICON_FA_COMMENT u8\"\\uf075\"\n#define ICON_FA_COMMENT_ALT u8\"\\uf27a\"\n#define ICON_FA_COMMENT_ALT_CHECK u8\"\\uf4a2\"\n#define ICON_FA_COMMENT_ALT_DOLLAR u8\"\\uf650\"\n#define ICON_FA_COMMENT_ALT_DOTS u8\"\\uf4a3\"\n#define ICON_FA_COMMENT_ALT_EDIT u8\"\\uf4a4\"\n#define ICON_FA_COMMENT_ALT_EXCLAMATION u8\"\\uf4a5\"\n#define ICON_FA_COMMENT_ALT_LINES u8\"\\uf4a6\"\n#define ICON_FA_COMMENT_ALT_MEDICAL u8\"\\uf7f4\"\n#define ICON_FA_COMMENT_ALT_MINUS u8\"\\uf4a7\"\n#define ICON_FA_COMMENT_ALT_MUSIC u8\"\\uf8af\"\n#define ICON_FA_COMMENT_ALT_PLUS u8\"\\uf4a8\"\n#define ICON_FA_COMMENT_ALT_SLASH u8\"\\uf4a9\"\n#define ICON_FA_COMMENT_ALT_SMILE u8\"\\uf4aa\"\n#define ICON_FA_COMMENT_ALT_TIMES u8\"\\uf4ab\"\n#define ICON_FA_COMMENT_CHECK u8\"\\uf4ac\"\n#define ICON_FA_COMMENT_DOLLAR u8\"\\uf651\"\n#define ICON_FA_COMMENT_DOTS u8\"\\uf4ad\"\n#define ICON_FA_COMMENT_EDIT u8\"\\uf4ae\"\n#define ICON_FA_COMMENT_EXCLAMATION u8\"\\uf4af\"\n#define ICON_FA_COMMENT_LINES u8\"\\uf4b0\"\n#define ICON_FA_COMMENT_MEDICAL u8\"\\uf7f5\"\n#define ICON_FA_COMMENT_MINUS u8\"\\uf4b1\"\n#define ICON_FA_COMMENT_MUSIC u8\"\\uf8b0\"\n#define ICON_FA_COMMENT_PLUS u8\"\\uf4b2\"\n#define ICON_FA_COMMENT_SLASH u8\"\\uf4b3\"\n#define ICON_FA_COMMENT_SMILE u8\"\\uf4b4\"\n#define ICON_FA_COMMENT_TIMES u8\"\\uf4b5\"\n#define ICON_FA_COMMENTS u8\"\\uf086\"\n#define ICON_FA_COMMENTS_ALT u8\"\\uf4b6\"\n#define ICON_FA_COMMENTS_ALT_DOLLAR u8\"\\uf652\"\n#define ICON_FA_COMMENTS_DOLLAR u8\"\\uf653\"\n#define ICON_FA_COMPACT_DISC u8\"\\uf51f\"\n#define ICON_FA_COMPASS u8\"\\uf14e\"\n#define ICON_FA_COMPASS_SLASH u8\"\\uf5e9\"\n#define ICON_FA_COMPRESS u8\"\\uf066\"\n#define ICON_FA_COMPRESS_ALT u8\"\\uf422\"\n#define ICON_FA_COMPRESS_ARROWS_ALT u8\"\\uf78c\"\n#define ICON_FA_COMPRESS_WIDE u8\"\\uf326\"\n#define ICON_FA_COMPUTER_CLASSIC u8\"\\uf8b1\"\n#define ICON_FA_COMPUTER_SPEAKER u8\"\\uf8b2\"\n#define ICON_FA_CONCIERGE_BELL u8\"\\uf562\"\n#define ICON_FA_CONSTRUCTION u8\"\\uf85d\"\n#define ICON_FA_CONTAINER_STORAGE u8\"\\uf4b7\"\n#define ICON_FA_CONVEYOR_BELT u8\"\\uf46e\"\n#define ICON_FA_CONVEYOR_BELT_ALT u8\"\\uf46f\"\n#define ICON_FA_COOKIE u8\"\\uf563\"\n#define ICON_FA_COOKIE_BITE u8\"\\uf564\"\n#define ICON_FA_COPY u8\"\\uf0c5\"\n#define ICON_FA_COPYRIGHT u8\"\\uf1f9\"\n#define ICON_FA_CORN u8\"\\uf6c7\"\n#define ICON_FA_COUCH u8\"\\uf4b8\"\n#define ICON_FA_COW u8\"\\uf6c8\"\n#define ICON_FA_COWBELL u8\"\\uf8b3\"\n#define ICON_FA_COWBELL_MORE u8\"\\uf8b4\"\n#define ICON_FA_CREDIT_CARD u8\"\\uf09d\"\n#define ICON_FA_CREDIT_CARD_BLANK u8\"\\uf389\"\n#define ICON_FA_CREDIT_CARD_FRONT u8\"\\uf38a\"\n#define ICON_FA_CRICKET u8\"\\uf449\"\n#define ICON_FA_CROISSANT u8\"\\uf7f6\"\n#define ICON_FA_CROP u8\"\\uf125\"\n#define ICON_FA_CROP_ALT u8\"\\uf565\"\n#define ICON_FA_CROSS u8\"\\uf654\"\n#define ICON_FA_CROSSHAIRS u8\"\\uf05b\"\n#define ICON_FA_CROW u8\"\\uf520\"\n#define ICON_FA_CROWN u8\"\\uf521\"\n#define ICON_FA_CRUTCH u8\"\\uf7f7\"\n#define ICON_FA_CRUTCHES u8\"\\uf7f8\"\n#define ICON_FA_CUBE u8\"\\uf1b2\"\n#define ICON_FA_CUBES u8\"\\uf1b3\"\n#define ICON_FA_CURLING u8\"\\uf44a\"\n#define ICON_FA_CUT u8\"\\uf0c4\"\n#define ICON_FA_DAGGER u8\"\\uf6cb\"\n#define ICON_FA_DATABASE u8\"\\uf1c0\"\n#define ICON_FA_DEAF u8\"\\uf2a4\"\n#define ICON_FA_DEBUG u8\"\\uf7f9\"\n#define ICON_FA_DEER u8\"\\uf78e\"\n#define ICON_FA_DEER_RUDOLPH u8\"\\uf78f\"\n#define ICON_FA_DEMOCRAT u8\"\\uf747\"\n#define ICON_FA_DESKTOP u8\"\\uf108\"\n#define ICON_FA_DESKTOP_ALT u8\"\\uf390\"\n#define ICON_FA_DEWPOINT u8\"\\uf748\"\n#define ICON_FA_DHARMACHAKRA u8\"\\uf655\"\n#define ICON_FA_DIAGNOSES u8\"\\uf470\"\n#define ICON_FA_DIAMOND u8\"\\uf219\"\n#define ICON_FA_DICE u8\"\\uf522\"\n#define ICON_FA_DICE_D10 u8\"\\uf6cd\"\n#define ICON_FA_DICE_D12 u8\"\\uf6ce\"\n#define ICON_FA_DICE_D20 u8\"\\uf6cf\"\n#define ICON_FA_DICE_D4 u8\"\\uf6d0\"\n#define ICON_FA_DICE_D6 u8\"\\uf6d1\"\n#define ICON_FA_DICE_D8 u8\"\\uf6d2\"\n#define ICON_FA_DICE_FIVE u8\"\\uf523\"\n#define ICON_FA_DICE_FOUR u8\"\\uf524\"\n#define ICON_FA_DICE_ONE u8\"\\uf525\"\n#define ICON_FA_DICE_SIX u8\"\\uf526\"\n#define ICON_FA_DICE_THREE u8\"\\uf527\"\n#define ICON_FA_DICE_TWO u8\"\\uf528\"\n#define ICON_FA_DIGGING u8\"\\uf85e\"\n#define ICON_FA_DIGITAL_TACHOGRAPH u8\"\\uf566\"\n#define ICON_FA_DIPLOMA u8\"\\uf5ea\"\n#define ICON_FA_DIRECTIONS u8\"\\uf5eb\"\n#define ICON_FA_DISC_DRIVE u8\"\\uf8b5\"\n#define ICON_FA_DISEASE u8\"\\uf7fa\"\n#define ICON_FA_DIVIDE u8\"\\uf529\"\n#define ICON_FA_DIZZY u8\"\\uf567\"\n#define ICON_FA_DNA u8\"\\uf471\"\n#define ICON_FA_DO_NOT_ENTER u8\"\\uf5ec\"\n#define ICON_FA_DOG u8\"\\uf6d3\"\n#define ICON_FA_DOG_LEASHED u8\"\\uf6d4\"\n#define ICON_FA_DOLLAR_SIGN u8\"\\uf155\"\n#define ICON_FA_DOLLY u8\"\\uf472\"\n#define ICON_FA_DOLLY_EMPTY u8\"\\uf473\"\n#define ICON_FA_DOLLY_FLATBED u8\"\\uf474\"\n#define ICON_FA_DOLLY_FLATBED_ALT u8\"\\uf475\"\n#define ICON_FA_DOLLY_FLATBED_EMPTY u8\"\\uf476\"\n#define ICON_FA_DONATE u8\"\\uf4b9\"\n#define ICON_FA_DOOR_CLOSED u8\"\\uf52a\"\n#define ICON_FA_DOOR_OPEN u8\"\\uf52b\"\n#define ICON_FA_DOT_CIRCLE u8\"\\uf192\"\n#define ICON_FA_DOVE u8\"\\uf4ba\"\n#define ICON_FA_DOWNLOAD u8\"\\uf019\"\n#define ICON_FA_DRAFTING_COMPASS u8\"\\uf568\"\n#define ICON_FA_DRAGON u8\"\\uf6d5\"\n#define ICON_FA_DRAW_CIRCLE u8\"\\uf5ed\"\n#define ICON_FA_DRAW_POLYGON u8\"\\uf5ee\"\n#define ICON_FA_DRAW_SQUARE u8\"\\uf5ef\"\n#define ICON_FA_DREIDEL u8\"\\uf792\"\n#define ICON_FA_DRONE u8\"\\uf85f\"\n#define ICON_FA_DRONE_ALT u8\"\\uf860\"\n#define ICON_FA_DRUM u8\"\\uf569\"\n#define ICON_FA_DRUM_STEELPAN u8\"\\uf56a\"\n#define ICON_FA_DRUMSTICK u8\"\\uf6d6\"\n#define ICON_FA_DRUMSTICK_BITE u8\"\\uf6d7\"\n#define ICON_FA_DRYER u8\"\\uf861\"\n#define ICON_FA_DRYER_ALT u8\"\\uf862\"\n#define ICON_FA_DUCK u8\"\\uf6d8\"\n#define ICON_FA_DUMBBELL u8\"\\uf44b\"\n#define ICON_FA_DUMPSTER u8\"\\uf793\"\n#define ICON_FA_DUMPSTER_FIRE u8\"\\uf794\"\n#define ICON_FA_DUNGEON u8\"\\uf6d9\"\n#define ICON_FA_EAR u8\"\\uf5f0\"\n#define ICON_FA_EAR_MUFFS u8\"\\uf795\"\n#define ICON_FA_ECLIPSE u8\"\\uf749\"\n#define ICON_FA_ECLIPSE_ALT u8\"\\uf74a\"\n#define ICON_FA_EDIT u8\"\\uf044\"\n#define ICON_FA_EGG u8\"\\uf7fb\"\n#define ICON_FA_EGG_FRIED u8\"\\uf7fc\"\n#define ICON_FA_EJECT u8\"\\uf052\"\n#define ICON_FA_ELEPHANT u8\"\\uf6da\"\n#define ICON_FA_ELLIPSIS_H u8\"\\uf141\"\n#define ICON_FA_ELLIPSIS_H_ALT u8\"\\uf39b\"\n#define ICON_FA_ELLIPSIS_V u8\"\\uf142\"\n#define ICON_FA_ELLIPSIS_V_ALT u8\"\\uf39c\"\n#define ICON_FA_EMPTY_SET u8\"\\uf656\"\n#define ICON_FA_ENGINE_WARNING u8\"\\uf5f2\"\n#define ICON_FA_ENVELOPE u8\"\\uf0e0\"\n#define ICON_FA_ENVELOPE_OPEN u8\"\\uf2b6\"\n#define ICON_FA_ENVELOPE_OPEN_DOLLAR u8\"\\uf657\"\n#define ICON_FA_ENVELOPE_OPEN_TEXT u8\"\\uf658\"\n#define ICON_FA_ENVELOPE_SQUARE u8\"\\uf199\"\n#define ICON_FA_EQUALS u8\"\\uf52c\"\n#define ICON_FA_ERASER u8\"\\uf12d\"\n#define ICON_FA_ETHERNET u8\"\\uf796\"\n#define ICON_FA_EURO_SIGN u8\"\\uf153\"\n#define ICON_FA_EXCHANGE u8\"\\uf0ec\"\n#define ICON_FA_EXCHANGE_ALT u8\"\\uf362\"\n#define ICON_FA_EXCLAMATION u8\"\\uf12a\"\n#define ICON_FA_EXCLAMATION_CIRCLE u8\"\\uf06a\"\n#define ICON_FA_EXCLAMATION_SQUARE u8\"\\uf321\"\n#define ICON_FA_EXCLAMATION_TRIANGLE u8\"\\uf071\"\n#define ICON_FA_EXPAND u8\"\\uf065\"\n#define ICON_FA_EXPAND_ALT u8\"\\uf424\"\n#define ICON_FA_EXPAND_ARROWS u8\"\\uf31d\"\n#define ICON_FA_EXPAND_ARROWS_ALT u8\"\\uf31e\"\n#define ICON_FA_EXPAND_WIDE u8\"\\uf320\"\n#define ICON_FA_EXTERNAL_LINK u8\"\\uf08e\"\n#define ICON_FA_EXTERNAL_LINK_ALT u8\"\\uf35d\"\n#define ICON_FA_EXTERNAL_LINK_SQUARE u8\"\\uf14c\"\n#define ICON_FA_EXTERNAL_LINK_SQUARE_ALT u8\"\\uf360\"\n#define ICON_FA_EYE u8\"\\uf06e\"\n#define ICON_FA_EYE_DROPPER u8\"\\uf1fb\"\n#define ICON_FA_EYE_EVIL u8\"\\uf6db\"\n#define ICON_FA_EYE_SLASH u8\"\\uf070\"\n#define ICON_FA_FAN u8\"\\uf863\"\n#define ICON_FA_FAN_TABLE u8\"\\uf904\"\n#define ICON_FA_FARM u8\"\\uf864\"\n#define ICON_FA_FAST_BACKWARD u8\"\\uf049\"\n#define ICON_FA_FAST_FORWARD u8\"\\uf050\"\n#define ICON_FA_FAUCET u8\"\\uf905\"\n#define ICON_FA_FAUCET_DRIP u8\"\\uf906\"\n#define ICON_FA_FAX u8\"\\uf1ac\"\n#define ICON_FA_FEATHER u8\"\\uf52d\"\n#define ICON_FA_FEATHER_ALT u8\"\\uf56b\"\n#define ICON_FA_FEMALE u8\"\\uf182\"\n#define ICON_FA_FIELD_HOCKEY u8\"\\uf44c\"\n#define ICON_FA_FIGHTER_JET u8\"\\uf0fb\"\n#define ICON_FA_FILE u8\"\\uf15b\"\n#define ICON_FA_FILE_ALT u8\"\\uf15c\"\n#define ICON_FA_FILE_ARCHIVE u8\"\\uf1c6\"\n#define ICON_FA_FILE_AUDIO u8\"\\uf1c7\"\n#define ICON_FA_FILE_CERTIFICATE u8\"\\uf5f3\"\n#define ICON_FA_FILE_CHART_LINE u8\"\\uf659\"\n#define ICON_FA_FILE_CHART_PIE u8\"\\uf65a\"\n#define ICON_FA_FILE_CHECK u8\"\\uf316\"\n#define ICON_FA_FILE_CODE u8\"\\uf1c9\"\n#define ICON_FA_FILE_CONTRACT u8\"\\uf56c\"\n#define ICON_FA_FILE_CSV u8\"\\uf6dd\"\n#define ICON_FA_FILE_DOWNLOAD u8\"\\uf56d\"\n#define ICON_FA_FILE_EDIT u8\"\\uf31c\"\n#define ICON_FA_FILE_EXCEL u8\"\\uf1c3\"\n#define ICON_FA_FILE_EXCLAMATION u8\"\\uf31a\"\n#define ICON_FA_FILE_EXPORT u8\"\\uf56e\"\n#define ICON_FA_FILE_IMAGE u8\"\\uf1c5\"\n#define ICON_FA_FILE_IMPORT u8\"\\uf56f\"\n#define ICON_FA_FILE_INVOICE u8\"\\uf570\"\n#define ICON_FA_FILE_INVOICE_DOLLAR u8\"\\uf571\"\n#define ICON_FA_FILE_MEDICAL u8\"\\uf477\"\n#define ICON_FA_FILE_MEDICAL_ALT u8\"\\uf478\"\n#define ICON_FA_FILE_MINUS u8\"\\uf318\"\n#define ICON_FA_FILE_MUSIC u8\"\\uf8b6\"\n#define ICON_FA_FILE_PDF u8\"\\uf1c1\"\n#define ICON_FA_FILE_PLUS u8\"\\uf319\"\n#define ICON_FA_FILE_POWERPOINT u8\"\\uf1c4\"\n#define ICON_FA_FILE_PRESCRIPTION u8\"\\uf572\"\n#define ICON_FA_FILE_SEARCH u8\"\\uf865\"\n#define ICON_FA_FILE_SIGNATURE u8\"\\uf573\"\n#define ICON_FA_FILE_SPREADSHEET u8\"\\uf65b\"\n#define ICON_FA_FILE_TIMES u8\"\\uf317\"\n#define ICON_FA_FILE_UPLOAD u8\"\\uf574\"\n#define ICON_FA_FILE_USER u8\"\\uf65c\"\n#define ICON_FA_FILE_VIDEO u8\"\\uf1c8\"\n#define ICON_FA_FILE_WORD u8\"\\uf1c2\"\n#define ICON_FA_FILES_MEDICAL u8\"\\uf7fd\"\n#define ICON_FA_FILL u8\"\\uf575\"\n#define ICON_FA_FILL_DRIP u8\"\\uf576\"\n#define ICON_FA_FILM u8\"\\uf008\"\n#define ICON_FA_FILM_ALT u8\"\\uf3a0\"\n#define ICON_FA_FILM_CANISTER u8\"\\uf8b7\"\n#define ICON_FA_FILTER u8\"\\uf0b0\"\n#define ICON_FA_FINGERPRINT u8\"\\uf577\"\n#define ICON_FA_FIRE u8\"\\uf06d\"\n#define ICON_FA_FIRE_ALT u8\"\\uf7e4\"\n#define ICON_FA_FIRE_EXTINGUISHER u8\"\\uf134\"\n#define ICON_FA_FIRE_SMOKE u8\"\\uf74b\"\n#define ICON_FA_FIREPLACE u8\"\\uf79a\"\n#define ICON_FA_FIRST_AID u8\"\\uf479\"\n#define ICON_FA_FISH u8\"\\uf578\"\n#define ICON_FA_FISH_COOKED u8\"\\uf7fe\"\n#define ICON_FA_FIST_RAISED u8\"\\uf6de\"\n#define ICON_FA_FLAG u8\"\\uf024\"\n#define ICON_FA_FLAG_ALT u8\"\\uf74c\"\n#define ICON_FA_FLAG_CHECKERED u8\"\\uf11e\"\n#define ICON_FA_FLAG_USA u8\"\\uf74d\"\n#define ICON_FA_FLAME u8\"\\uf6df\"\n#define ICON_FA_FLASHLIGHT u8\"\\uf8b8\"\n#define ICON_FA_FLASK u8\"\\uf0c3\"\n#define ICON_FA_FLASK_POISON u8\"\\uf6e0\"\n#define ICON_FA_FLASK_POTION u8\"\\uf6e1\"\n#define ICON_FA_FLOWER u8\"\\uf7ff\"\n#define ICON_FA_FLOWER_DAFFODIL u8\"\\uf800\"\n#define ICON_FA_FLOWER_TULIP u8\"\\uf801\"\n#define ICON_FA_FLUSHED u8\"\\uf579\"\n#define ICON_FA_FLUTE u8\"\\uf8b9\"\n#define ICON_FA_FLUX_CAPACITOR u8\"\\uf8ba\"\n#define ICON_FA_FOG u8\"\\uf74e\"\n#define ICON_FA_FOLDER u8\"\\uf07b\"\n#define ICON_FA_FOLDER_DOWNLOAD u8\"\\uf953\"\n#define ICON_FA_FOLDER_MINUS u8\"\\uf65d\"\n#define ICON_FA_FOLDER_OPEN u8\"\\uf07c\"\n#define ICON_FA_FOLDER_PLUS u8\"\\uf65e\"\n#define ICON_FA_FOLDER_TIMES u8\"\\uf65f\"\n#define ICON_FA_FOLDER_TREE u8\"\\uf802\"\n#define ICON_FA_FOLDER_UPLOAD u8\"\\uf954\"\n#define ICON_FA_FOLDERS u8\"\\uf660\"\n#define ICON_FA_FONT u8\"\\uf031\"\n#define ICON_FA_FONT_AWESOME_LOGO_FULL u8\"\\uf4e6\"\n#define ICON_FA_FONT_CASE u8\"\\uf866\"\n#define ICON_FA_FOOTBALL_BALL u8\"\\uf44e\"\n#define ICON_FA_FOOTBALL_HELMET u8\"\\uf44f\"\n#define ICON_FA_FORKLIFT u8\"\\uf47a\"\n#define ICON_FA_FORWARD u8\"\\uf04e\"\n#define ICON_FA_FRAGILE u8\"\\uf4bb\"\n#define ICON_FA_FRENCH_FRIES u8\"\\uf803\"\n#define ICON_FA_FROG u8\"\\uf52e\"\n#define ICON_FA_FROSTY_HEAD u8\"\\uf79b\"\n#define ICON_FA_FROWN u8\"\\uf119\"\n#define ICON_FA_FROWN_OPEN u8\"\\uf57a\"\n#define ICON_FA_FUNCTION u8\"\\uf661\"\n#define ICON_FA_FUNNEL_DOLLAR u8\"\\uf662\"\n#define ICON_FA_FUTBOL u8\"\\uf1e3\"\n#define ICON_FA_GALAXY u8\"\\uf908\"\n#define ICON_FA_GAME_BOARD u8\"\\uf867\"\n#define ICON_FA_GAME_BOARD_ALT u8\"\\uf868\"\n#define ICON_FA_GAME_CONSOLE_HANDHELD u8\"\\uf8bb\"\n#define ICON_FA_GAMEPAD u8\"\\uf11b\"\n#define ICON_FA_GAMEPAD_ALT u8\"\\uf8bc\"\n#define ICON_FA_GARAGE u8\"\\uf909\"\n#define ICON_FA_GARAGE_CAR u8\"\\uf90a\"\n#define ICON_FA_GARAGE_OPEN u8\"\\uf90b\"\n#define ICON_FA_GAS_PUMP u8\"\\uf52f\"\n#define ICON_FA_GAS_PUMP_SLASH u8\"\\uf5f4\"\n#define ICON_FA_GAVEL u8\"\\uf0e3\"\n#define ICON_FA_GEM u8\"\\uf3a5\"\n#define ICON_FA_GENDERLESS u8\"\\uf22d\"\n#define ICON_FA_GHOST u8\"\\uf6e2\"\n#define ICON_FA_GIFT u8\"\\uf06b\"\n#define ICON_FA_GIFT_CARD u8\"\\uf663\"\n#define ICON_FA_GIFTS u8\"\\uf79c\"\n#define ICON_FA_GINGERBREAD_MAN u8\"\\uf79d\"\n#define ICON_FA_GLASS u8\"\\uf804\"\n#define ICON_FA_GLASS_CHAMPAGNE u8\"\\uf79e\"\n#define ICON_FA_GLASS_CHEERS u8\"\\uf79f\"\n#define ICON_FA_GLASS_CITRUS u8\"\\uf869\"\n#define ICON_FA_GLASS_MARTINI u8\"\\uf000\"\n#define ICON_FA_GLASS_MARTINI_ALT u8\"\\uf57b\"\n#define ICON_FA_GLASS_WHISKEY u8\"\\uf7a0\"\n#define ICON_FA_GLASS_WHISKEY_ROCKS u8\"\\uf7a1\"\n#define ICON_FA_GLASSES u8\"\\uf530\"\n#define ICON_FA_GLASSES_ALT u8\"\\uf5f5\"\n#define ICON_FA_GLOBE u8\"\\uf0ac\"\n#define ICON_FA_GLOBE_AFRICA u8\"\\uf57c\"\n#define ICON_FA_GLOBE_AMERICAS u8\"\\uf57d\"\n#define ICON_FA_GLOBE_ASIA u8\"\\uf57e\"\n#define ICON_FA_GLOBE_EUROPE u8\"\\uf7a2\"\n#define ICON_FA_GLOBE_SNOW u8\"\\uf7a3\"\n#define ICON_FA_GLOBE_STAND u8\"\\uf5f6\"\n#define ICON_FA_GOLF_BALL u8\"\\uf450\"\n#define ICON_FA_GOLF_CLUB u8\"\\uf451\"\n#define ICON_FA_GOPURAM u8\"\\uf664\"\n#define ICON_FA_GRADUATION_CAP u8\"\\uf19d\"\n#define ICON_FA_GRAMOPHONE u8\"\\uf8bd\"\n#define ICON_FA_GREATER_THAN u8\"\\uf531\"\n#define ICON_FA_GREATER_THAN_EQUAL u8\"\\uf532\"\n#define ICON_FA_GRIMACE u8\"\\uf57f\"\n#define ICON_FA_GRIN u8\"\\uf580\"\n#define ICON_FA_GRIN_ALT u8\"\\uf581\"\n#define ICON_FA_GRIN_BEAM u8\"\\uf582\"\n#define ICON_FA_GRIN_BEAM_SWEAT u8\"\\uf583\"\n#define ICON_FA_GRIN_HEARTS u8\"\\uf584\"\n#define ICON_FA_GRIN_SQUINT u8\"\\uf585\"\n#define ICON_FA_GRIN_SQUINT_TEARS u8\"\\uf586\"\n#define ICON_FA_GRIN_STARS u8\"\\uf587\"\n#define ICON_FA_GRIN_TEARS u8\"\\uf588\"\n#define ICON_FA_GRIN_TONGUE u8\"\\uf589\"\n#define ICON_FA_GRIN_TONGUE_SQUINT u8\"\\uf58a\"\n#define ICON_FA_GRIN_TONGUE_WINK u8\"\\uf58b\"\n#define ICON_FA_GRIN_WINK u8\"\\uf58c\"\n#define ICON_FA_GRIP_HORIZONTAL u8\"\\uf58d\"\n#define ICON_FA_GRIP_LINES u8\"\\uf7a4\"\n#define ICON_FA_GRIP_LINES_VERTICAL u8\"\\uf7a5\"\n#define ICON_FA_GRIP_VERTICAL u8\"\\uf58e\"\n#define ICON_FA_GUITAR u8\"\\uf7a6\"\n#define ICON_FA_GUITAR_ELECTRIC u8\"\\uf8be\"\n#define ICON_FA_GUITARS u8\"\\uf8bf\"\n#define ICON_FA_H_SQUARE u8\"\\uf0fd\"\n#define ICON_FA_H1 u8\"\\uf313\"\n#define ICON_FA_H2 u8\"\\uf314\"\n#define ICON_FA_H3 u8\"\\uf315\"\n#define ICON_FA_H4 u8\"\\uf86a\"\n#define ICON_FA_HAMBURGER u8\"\\uf805\"\n#define ICON_FA_HAMMER u8\"\\uf6e3\"\n#define ICON_FA_HAMMER_WAR u8\"\\uf6e4\"\n#define ICON_FA_HAMSA u8\"\\uf665\"\n#define ICON_FA_HAND_HEART u8\"\\uf4bc\"\n#define ICON_FA_HAND_HOLDING u8\"\\uf4bd\"\n#define ICON_FA_HAND_HOLDING_BOX u8\"\\uf47b\"\n#define ICON_FA_HAND_HOLDING_HEART u8\"\\uf4be\"\n#define ICON_FA_HAND_HOLDING_MAGIC u8\"\\uf6e5\"\n#define ICON_FA_HAND_HOLDING_MEDICAL u8\"\\uf95c\"\n#define ICON_FA_HAND_HOLDING_SEEDLING u8\"\\uf4bf\"\n#define ICON_FA_HAND_HOLDING_USD u8\"\\uf4c0\"\n#define ICON_FA_HAND_HOLDING_WATER u8\"\\uf4c1\"\n#define ICON_FA_HAND_LIZARD u8\"\\uf258\"\n#define ICON_FA_HAND_MIDDLE_FINGER u8\"\\uf806\"\n#define ICON_FA_HAND_PAPER u8\"\\uf256\"\n#define ICON_FA_HAND_PEACE u8\"\\uf25b\"\n#define ICON_FA_HAND_POINT_DOWN u8\"\\uf0a7\"\n#define ICON_FA_HAND_POINT_LEFT u8\"\\uf0a5\"\n#define ICON_FA_HAND_POINT_RIGHT u8\"\\uf0a4\"\n#define ICON_FA_HAND_POINT_UP u8\"\\uf0a6\"\n#define ICON_FA_HAND_POINTER u8\"\\uf25a\"\n#define ICON_FA_HAND_RECEIVING u8\"\\uf47c\"\n#define ICON_FA_HAND_ROCK u8\"\\uf255\"\n#define ICON_FA_HAND_SCISSORS u8\"\\uf257\"\n#define ICON_FA_HAND_SPARKLES u8\"\\uf95d\"\n#define ICON_FA_HAND_SPOCK u8\"\\uf259\"\n#define ICON_FA_HANDS u8\"\\uf4c2\"\n#define ICON_FA_HANDS_HEART u8\"\\uf4c3\"\n#define ICON_FA_HANDS_HELPING u8\"\\uf4c4\"\n#define ICON_FA_HANDS_USD u8\"\\uf4c5\"\n#define ICON_FA_HANDS_WASH u8\"\\uf95e\"\n#define ICON_FA_HANDSHAKE u8\"\\uf2b5\"\n#define ICON_FA_HANDSHAKE_ALT u8\"\\uf4c6\"\n#define ICON_FA_HANDSHAKE_ALT_SLASH u8\"\\uf95f\"\n#define ICON_FA_HANDSHAKE_SLASH u8\"\\uf960\"\n#define ICON_FA_HANUKIAH u8\"\\uf6e6\"\n#define ICON_FA_HARD_HAT u8\"\\uf807\"\n#define ICON_FA_HASHTAG u8\"\\uf292\"\n#define ICON_FA_HAT_CHEF u8\"\\uf86b\"\n#define ICON_FA_HAT_COWBOY u8\"\\uf8c0\"\n#define ICON_FA_HAT_COWBOY_SIDE u8\"\\uf8c1\"\n#define ICON_FA_HAT_SANTA u8\"\\uf7a7\"\n#define ICON_FA_HAT_WINTER u8\"\\uf7a8\"\n#define ICON_FA_HAT_WITCH u8\"\\uf6e7\"\n#define ICON_FA_HAT_WIZARD u8\"\\uf6e8\"\n#define ICON_FA_HDD u8\"\\uf0a0\"\n#define ICON_FA_HEAD_SIDE u8\"\\uf6e9\"\n#define ICON_FA_HEAD_SIDE_BRAIN u8\"\\uf808\"\n#define ICON_FA_HEAD_SIDE_COUGH u8\"\\uf961\"\n#define ICON_FA_HEAD_SIDE_COUGH_SLASH u8\"\\uf962\"\n#define ICON_FA_HEAD_SIDE_HEADPHONES u8\"\\uf8c2\"\n#define ICON_FA_HEAD_SIDE_MASK u8\"\\uf963\"\n#define ICON_FA_HEAD_SIDE_MEDICAL u8\"\\uf809\"\n#define ICON_FA_HEAD_SIDE_VIRUS u8\"\\uf964\"\n#define ICON_FA_HEAD_VR u8\"\\uf6ea\"\n#define ICON_FA_HEADING u8\"\\uf1dc\"\n#define ICON_FA_HEADPHONES u8\"\\uf025\"\n#define ICON_FA_HEADPHONES_ALT u8\"\\uf58f\"\n#define ICON_FA_HEADSET u8\"\\uf590\"\n#define ICON_FA_HEART u8\"\\uf004\"\n#define ICON_FA_HEART_BROKEN u8\"\\uf7a9\"\n#define ICON_FA_HEART_CIRCLE u8\"\\uf4c7\"\n#define ICON_FA_HEART_RATE u8\"\\uf5f8\"\n#define ICON_FA_HEART_SQUARE u8\"\\uf4c8\"\n#define ICON_FA_HEARTBEAT u8\"\\uf21e\"\n#define ICON_FA_HEAT u8\"\\uf90c\"\n#define ICON_FA_HELICOPTER u8\"\\uf533\"\n#define ICON_FA_HELMET_BATTLE u8\"\\uf6eb\"\n#define ICON_FA_HEXAGON u8\"\\uf312\"\n#define ICON_FA_HIGHLIGHTER u8\"\\uf591\"\n#define ICON_FA_HIKING u8\"\\uf6ec\"\n#define ICON_FA_HIPPO u8\"\\uf6ed\"\n#define ICON_FA_HISTORY u8\"\\uf1da\"\n#define ICON_FA_HOCKEY_MASK u8\"\\uf6ee\"\n#define ICON_FA_HOCKEY_PUCK u8\"\\uf453\"\n#define ICON_FA_HOCKEY_STICKS u8\"\\uf454\"\n#define ICON_FA_HOLLY_BERRY u8\"\\uf7aa\"\n#define ICON_FA_HOME u8\"\\uf015\"\n#define ICON_FA_HOME_ALT u8\"\\uf80a\"\n#define ICON_FA_HOME_HEART u8\"\\uf4c9\"\n#define ICON_FA_HOME_LG u8\"\\uf80b\"\n#define ICON_FA_HOME_LG_ALT u8\"\\uf80c\"\n#define ICON_FA_HOOD_CLOAK u8\"\\uf6ef\"\n#define ICON_FA_HORIZONTAL_RULE u8\"\\uf86c\"\n#define ICON_FA_HORSE u8\"\\uf6f0\"\n#define ICON_FA_HORSE_HEAD u8\"\\uf7ab\"\n#define ICON_FA_HORSE_SADDLE u8\"\\uf8c3\"\n#define ICON_FA_HOSPITAL u8\"\\uf0f8\"\n#define ICON_FA_HOSPITAL_ALT u8\"\\uf47d\"\n#define ICON_FA_HOSPITAL_SYMBOL u8\"\\uf47e\"\n#define ICON_FA_HOSPITAL_USER u8\"\\uf80d\"\n#define ICON_FA_HOSPITALS u8\"\\uf80e\"\n#define ICON_FA_HOT_TUB u8\"\\uf593\"\n#define ICON_FA_HOTDOG u8\"\\uf80f\"\n#define ICON_FA_HOTEL u8\"\\uf594\"\n#define ICON_FA_HOURGLASS u8\"\\uf254\"\n#define ICON_FA_HOURGLASS_END u8\"\\uf253\"\n#define ICON_FA_HOURGLASS_HALF u8\"\\uf252\"\n#define ICON_FA_HOURGLASS_START u8\"\\uf251\"\n#define ICON_FA_HOUSE u8\"\\uf90d\"\n#define ICON_FA_HOUSE_DAMAGE u8\"\\uf6f1\"\n#define ICON_FA_HOUSE_DAY u8\"\\uf90e\"\n#define ICON_FA_HOUSE_FLOOD u8\"\\uf74f\"\n#define ICON_FA_HOUSE_LEAVE u8\"\\uf90f\"\n#define ICON_FA_HOUSE_NIGHT u8\"\\uf910\"\n#define ICON_FA_HOUSE_RETURN u8\"\\uf911\"\n#define ICON_FA_HOUSE_SIGNAL u8\"\\uf912\"\n#define ICON_FA_HOUSE_USER u8\"\\uf965\"\n#define ICON_FA_HRYVNIA u8\"\\uf6f2\"\n#define ICON_FA_HUMIDITY u8\"\\uf750\"\n#define ICON_FA_HURRICANE u8\"\\uf751\"\n#define ICON_FA_I_CURSOR u8\"\\uf246\"\n#define ICON_FA_ICE_CREAM u8\"\\uf810\"\n#define ICON_FA_ICE_SKATE u8\"\\uf7ac\"\n#define ICON_FA_ICICLES u8\"\\uf7ad\"\n#define ICON_FA_ICONS u8\"\\uf86d\"\n#define ICON_FA_ICONS_ALT u8\"\\uf86e\"\n#define ICON_FA_ID_BADGE u8\"\\uf2c1\"\n#define ICON_FA_ID_CARD u8\"\\uf2c2\"\n#define ICON_FA_ID_CARD_ALT u8\"\\uf47f\"\n#define ICON_FA_IGLOO u8\"\\uf7ae\"\n#define ICON_FA_IMAGE u8\"\\uf03e\"\n#define ICON_FA_IMAGE_POLAROID u8\"\\uf8c4\"\n#define ICON_FA_IMAGES u8\"\\uf302\"\n#define ICON_FA_INBOX u8\"\\uf01c\"\n#define ICON_FA_INBOX_IN u8\"\\uf310\"\n#define ICON_FA_INBOX_OUT u8\"\\uf311\"\n#define ICON_FA_INDENT u8\"\\uf03c\"\n#define ICON_FA_INDUSTRY u8\"\\uf275\"\n#define ICON_FA_INDUSTRY_ALT u8\"\\uf3b3\"\n#define ICON_FA_INFINITY u8\"\\uf534\"\n#define ICON_FA_INFO u8\"\\uf129\"\n#define ICON_FA_INFO_CIRCLE u8\"\\uf05a\"\n#define ICON_FA_INFO_SQUARE u8\"\\uf30f\"\n#define ICON_FA_INHALER u8\"\\uf5f9\"\n#define ICON_FA_INTEGRAL u8\"\\uf667\"\n#define ICON_FA_INTERSECTION u8\"\\uf668\"\n#define ICON_FA_INVENTORY u8\"\\uf480\"\n#define ICON_FA_ISLAND_TROPICAL u8\"\\uf811\"\n#define ICON_FA_ITALIC u8\"\\uf033\"\n#define ICON_FA_JACK_O_LANTERN u8\"\\uf30e\"\n#define ICON_FA_JEDI u8\"\\uf669\"\n#define ICON_FA_JOINT u8\"\\uf595\"\n#define ICON_FA_JOURNAL_WHILLS u8\"\\uf66a\"\n#define ICON_FA_JOYSTICK u8\"\\uf8c5\"\n#define ICON_FA_JUG u8\"\\uf8c6\"\n#define ICON_FA_KAABA u8\"\\uf66b\"\n#define ICON_FA_KAZOO u8\"\\uf8c7\"\n#define ICON_FA_KERNING u8\"\\uf86f\"\n#define ICON_FA_KEY u8\"\\uf084\"\n#define ICON_FA_KEY_SKELETON u8\"\\uf6f3\"\n#define ICON_FA_KEYBOARD u8\"\\uf11c\"\n#define ICON_FA_KEYNOTE u8\"\\uf66c\"\n#define ICON_FA_KHANDA u8\"\\uf66d\"\n#define ICON_FA_KIDNEYS u8\"\\uf5fb\"\n#define ICON_FA_KISS u8\"\\uf596\"\n#define ICON_FA_KISS_BEAM u8\"\\uf597\"\n#define ICON_FA_KISS_WINK_HEART u8\"\\uf598\"\n#define ICON_FA_KITE u8\"\\uf6f4\"\n#define ICON_FA_KIWI_BIRD u8\"\\uf535\"\n#define ICON_FA_KNIFE_KITCHEN u8\"\\uf6f5\"\n#define ICON_FA_LAMBDA u8\"\\uf66e\"\n#define ICON_FA_LAMP u8\"\\uf4ca\"\n#define ICON_FA_LAMP_DESK u8\"\\uf914\"\n#define ICON_FA_LAMP_FLOOR u8\"\\uf915\"\n#define ICON_FA_LANDMARK u8\"\\uf66f\"\n#define ICON_FA_LANDMARK_ALT u8\"\\uf752\"\n#define ICON_FA_LANGUAGE u8\"\\uf1ab\"\n#define ICON_FA_LAPTOP u8\"\\uf109\"\n#define ICON_FA_LAPTOP_CODE u8\"\\uf5fc\"\n#define ICON_FA_LAPTOP_HOUSE u8\"\\uf966\"\n#define ICON_FA_LAPTOP_MEDICAL u8\"\\uf812\"\n#define ICON_FA_LASSO u8\"\\uf8c8\"\n#define ICON_FA_LAUGH u8\"\\uf599\"\n#define ICON_FA_LAUGH_BEAM u8\"\\uf59a\"\n#define ICON_FA_LAUGH_SQUINT u8\"\\uf59b\"\n#define ICON_FA_LAUGH_WINK u8\"\\uf59c\"\n#define ICON_FA_LAYER_GROUP u8\"\\uf5fd\"\n#define ICON_FA_LAYER_MINUS u8\"\\uf5fe\"\n#define ICON_FA_LAYER_PLUS u8\"\\uf5ff\"\n#define ICON_FA_LEAF u8\"\\uf06c\"\n#define ICON_FA_LEAF_HEART u8\"\\uf4cb\"\n#define ICON_FA_LEAF_MAPLE u8\"\\uf6f6\"\n#define ICON_FA_LEAF_OAK u8\"\\uf6f7\"\n#define ICON_FA_LEMON u8\"\\uf094\"\n#define ICON_FA_LESS_THAN u8\"\\uf536\"\n#define ICON_FA_LESS_THAN_EQUAL u8\"\\uf537\"\n#define ICON_FA_LEVEL_DOWN u8\"\\uf149\"\n#define ICON_FA_LEVEL_DOWN_ALT u8\"\\uf3be\"\n#define ICON_FA_LEVEL_UP u8\"\\uf148\"\n#define ICON_FA_LEVEL_UP_ALT u8\"\\uf3bf\"\n#define ICON_FA_LIFE_RING u8\"\\uf1cd\"\n#define ICON_FA_LIGHT_CEILING u8\"\\uf916\"\n#define ICON_FA_LIGHT_SWITCH u8\"\\uf917\"\n#define ICON_FA_LIGHT_SWITCH_OFF u8\"\\uf918\"\n#define ICON_FA_LIGHT_SWITCH_ON u8\"\\uf919\"\n#define ICON_FA_LIGHTBULB u8\"\\uf0eb\"\n#define ICON_FA_LIGHTBULB_DOLLAR u8\"\\uf670\"\n#define ICON_FA_LIGHTBULB_EXCLAMATION u8\"\\uf671\"\n#define ICON_FA_LIGHTBULB_ON u8\"\\uf672\"\n#define ICON_FA_LIGHTBULB_SLASH u8\"\\uf673\"\n#define ICON_FA_LIGHTS_HOLIDAY u8\"\\uf7b2\"\n#define ICON_FA_LINE_COLUMNS u8\"\\uf870\"\n#define ICON_FA_LINE_HEIGHT u8\"\\uf871\"\n#define ICON_FA_LINK u8\"\\uf0c1\"\n#define ICON_FA_LIPS u8\"\\uf600\"\n#define ICON_FA_LIRA_SIGN u8\"\\uf195\"\n#define ICON_FA_LIST u8\"\\uf03a\"\n#define ICON_FA_LIST_ALT u8\"\\uf022\"\n#define ICON_FA_LIST_MUSIC u8\"\\uf8c9\"\n#define ICON_FA_LIST_OL u8\"\\uf0cb\"\n#define ICON_FA_LIST_UL u8\"\\uf0ca\"\n#define ICON_FA_LOCATION u8\"\\uf601\"\n#define ICON_FA_LOCATION_ARROW u8\"\\uf124\"\n#define ICON_FA_LOCATION_CIRCLE u8\"\\uf602\"\n#define ICON_FA_LOCATION_SLASH u8\"\\uf603\"\n#define ICON_FA_LOCK u8\"\\uf023\"\n#define ICON_FA_LOCK_ALT u8\"\\uf30d\"\n#define ICON_FA_LOCK_OPEN u8\"\\uf3c1\"\n#define ICON_FA_LOCK_OPEN_ALT u8\"\\uf3c2\"\n#define ICON_FA_LONG_ARROW_ALT_DOWN u8\"\\uf309\"\n#define ICON_FA_LONG_ARROW_ALT_LEFT u8\"\\uf30a\"\n#define ICON_FA_LONG_ARROW_ALT_RIGHT u8\"\\uf30b\"\n#define ICON_FA_LONG_ARROW_ALT_UP u8\"\\uf30c\"\n#define ICON_FA_LONG_ARROW_DOWN u8\"\\uf175\"\n#define ICON_FA_LONG_ARROW_LEFT u8\"\\uf177\"\n#define ICON_FA_LONG_ARROW_RIGHT u8\"\\uf178\"\n#define ICON_FA_LONG_ARROW_UP u8\"\\uf176\"\n#define ICON_FA_LOVESEAT u8\"\\uf4cc\"\n#define ICON_FA_LOW_VISION u8\"\\uf2a8\"\n#define ICON_FA_LUCHADOR u8\"\\uf455\"\n#define ICON_FA_LUGGAGE_CART u8\"\\uf59d\"\n#define ICON_FA_LUNGS u8\"\\uf604\"\n#define ICON_FA_LUNGS_VIRUS u8\"\\uf967\"\n#define ICON_FA_MACE u8\"\\uf6f8\"\n#define ICON_FA_MAGIC u8\"\\uf0d0\"\n#define ICON_FA_MAGNET u8\"\\uf076\"\n#define ICON_FA_MAIL_BULK u8\"\\uf674\"\n#define ICON_FA_MAILBOX u8\"\\uf813\"\n#define ICON_FA_MALE u8\"\\uf183\"\n#define ICON_FA_MANDOLIN u8\"\\uf6f9\"\n#define ICON_FA_MAP u8\"\\uf279\"\n#define ICON_FA_MAP_MARKED u8\"\\uf59f\"\n#define ICON_FA_MAP_MARKED_ALT u8\"\\uf5a0\"\n#define ICON_FA_MAP_MARKER u8\"\\uf041\"\n#define ICON_FA_MAP_MARKER_ALT u8\"\\uf3c5\"\n#define ICON_FA_MAP_MARKER_ALT_SLASH u8\"\\uf605\"\n#define ICON_FA_MAP_MARKER_CHECK u8\"\\uf606\"\n#define ICON_FA_MAP_MARKER_EDIT u8\"\\uf607\"\n#define ICON_FA_MAP_MARKER_EXCLAMATION u8\"\\uf608\"\n#define ICON_FA_MAP_MARKER_MINUS u8\"\\uf609\"\n#define ICON_FA_MAP_MARKER_PLUS u8\"\\uf60a\"\n#define ICON_FA_MAP_MARKER_QUESTION u8\"\\uf60b\"\n#define ICON_FA_MAP_MARKER_SLASH u8\"\\uf60c\"\n#define ICON_FA_MAP_MARKER_SMILE u8\"\\uf60d\"\n#define ICON_FA_MAP_MARKER_TIMES u8\"\\uf60e\"\n#define ICON_FA_MAP_PIN u8\"\\uf276\"\n#define ICON_FA_MAP_SIGNS u8\"\\uf277\"\n#define ICON_FA_MARKER u8\"\\uf5a1\"\n#define ICON_FA_MARS u8\"\\uf222\"\n#define ICON_FA_MARS_DOUBLE u8\"\\uf227\"\n#define ICON_FA_MARS_STROKE u8\"\\uf229\"\n#define ICON_FA_MARS_STROKE_H u8\"\\uf22b\"\n#define ICON_FA_MARS_STROKE_V u8\"\\uf22a\"\n#define ICON_FA_MASK u8\"\\uf6fa\"\n#define ICON_FA_MEAT u8\"\\uf814\"\n#define ICON_FA_MEDAL u8\"\\uf5a2\"\n#define ICON_FA_MEDKIT u8\"\\uf0fa\"\n#define ICON_FA_MEGAPHONE u8\"\\uf675\"\n#define ICON_FA_MEH u8\"\\uf11a\"\n#define ICON_FA_MEH_BLANK u8\"\\uf5a4\"\n#define ICON_FA_MEH_ROLLING_EYES u8\"\\uf5a5\"\n#define ICON_FA_MEMORY u8\"\\uf538\"\n#define ICON_FA_MENORAH u8\"\\uf676\"\n#define ICON_FA_MERCURY u8\"\\uf223\"\n#define ICON_FA_METEOR u8\"\\uf753\"\n#define ICON_FA_MICROCHIP u8\"\\uf2db\"\n#define ICON_FA_MICROPHONE u8\"\\uf130\"\n#define ICON_FA_MICROPHONE_ALT u8\"\\uf3c9\"\n#define ICON_FA_MICROPHONE_ALT_SLASH u8\"\\uf539\"\n#define ICON_FA_MICROPHONE_SLASH u8\"\\uf131\"\n#define ICON_FA_MICROPHONE_STAND u8\"\\uf8cb\"\n#define ICON_FA_MICROSCOPE u8\"\\uf610\"\n#define ICON_FA_MICROWAVE u8\"\\uf91b\"\n#define ICON_FA_MIND_SHARE u8\"\\uf677\"\n#define ICON_FA_MINUS u8\"\\uf068\"\n#define ICON_FA_MINUS_CIRCLE u8\"\\uf056\"\n#define ICON_FA_MINUS_HEXAGON u8\"\\uf307\"\n#define ICON_FA_MINUS_OCTAGON u8\"\\uf308\"\n#define ICON_FA_MINUS_SQUARE u8\"\\uf146\"\n#define ICON_FA_MISTLETOE u8\"\\uf7b4\"\n#define ICON_FA_MITTEN u8\"\\uf7b5\"\n#define ICON_FA_MOBILE u8\"\\uf10b\"\n#define ICON_FA_MOBILE_ALT u8\"\\uf3cd\"\n#define ICON_FA_MOBILE_ANDROID u8\"\\uf3ce\"\n#define ICON_FA_MOBILE_ANDROID_ALT u8\"\\uf3cf\"\n#define ICON_FA_MONEY_BILL u8\"\\uf0d6\"\n#define ICON_FA_MONEY_BILL_ALT u8\"\\uf3d1\"\n#define ICON_FA_MONEY_BILL_WAVE u8\"\\uf53a\"\n#define ICON_FA_MONEY_BILL_WAVE_ALT u8\"\\uf53b\"\n#define ICON_FA_MONEY_CHECK u8\"\\uf53c\"\n#define ICON_FA_MONEY_CHECK_ALT u8\"\\uf53d\"\n#define ICON_FA_MONEY_CHECK_EDIT u8\"\\uf872\"\n#define ICON_FA_MONEY_CHECK_EDIT_ALT u8\"\\uf873\"\n#define ICON_FA_MONITOR_HEART_RATE u8\"\\uf611\"\n#define ICON_FA_MONKEY u8\"\\uf6fb\"\n#define ICON_FA_MONUMENT u8\"\\uf5a6\"\n#define ICON_FA_MOON u8\"\\uf186\"\n#define ICON_FA_MOON_CLOUD u8\"\\uf754\"\n#define ICON_FA_MOON_STARS u8\"\\uf755\"\n#define ICON_FA_MORTAR_PESTLE u8\"\\uf5a7\"\n#define ICON_FA_MOSQUE u8\"\\uf678\"\n#define ICON_FA_MOTORCYCLE u8\"\\uf21c\"\n#define ICON_FA_MOUNTAIN u8\"\\uf6fc\"\n#define ICON_FA_MOUNTAINS u8\"\\uf6fd\"\n#define ICON_FA_MOUSE u8\"\\uf8cc\"\n#define ICON_FA_MOUSE_ALT u8\"\\uf8cd\"\n#define ICON_FA_MOUSE_POINTER u8\"\\uf245\"\n#define ICON_FA_MP3_PLAYER u8\"\\uf8ce\"\n#define ICON_FA_MUG u8\"\\uf874\"\n#define ICON_FA_MUG_HOT u8\"\\uf7b6\"\n#define ICON_FA_MUG_MARSHMALLOWS u8\"\\uf7b7\"\n#define ICON_FA_MUG_TEA u8\"\\uf875\"\n#define ICON_FA_MUSIC u8\"\\uf001\"\n#define ICON_FA_MUSIC_ALT u8\"\\uf8cf\"\n#define ICON_FA_MUSIC_ALT_SLASH u8\"\\uf8d0\"\n#define ICON_FA_MUSIC_SLASH u8\"\\uf8d1\"\n#define ICON_FA_NARWHAL u8\"\\uf6fe\"\n#define ICON_FA_NETWORK_WIRED u8\"\\uf6ff\"\n#define ICON_FA_NEUTER u8\"\\uf22c\"\n#define ICON_FA_NEWSPAPER u8\"\\uf1ea\"\n#define ICON_FA_NOT_EQUAL u8\"\\uf53e\"\n#define ICON_FA_NOTES_MEDICAL u8\"\\uf481\"\n#define ICON_FA_OBJECT_GROUP u8\"\\uf247\"\n#define ICON_FA_OBJECT_UNGROUP u8\"\\uf248\"\n#define ICON_FA_OCTAGON u8\"\\uf306\"\n#define ICON_FA_OIL_CAN u8\"\\uf613\"\n#define ICON_FA_OIL_TEMP u8\"\\uf614\"\n#define ICON_FA_OM u8\"\\uf679\"\n#define ICON_FA_OMEGA u8\"\\uf67a\"\n#define ICON_FA_ORNAMENT u8\"\\uf7b8\"\n#define ICON_FA_OTTER u8\"\\uf700\"\n#define ICON_FA_OUTDENT u8\"\\uf03b\"\n#define ICON_FA_OUTLET u8\"\\uf91c\"\n#define ICON_FA_OVEN u8\"\\uf91d\"\n#define ICON_FA_OVERLINE u8\"\\uf876\"\n#define ICON_FA_PAGE_BREAK u8\"\\uf877\"\n#define ICON_FA_PAGER u8\"\\uf815\"\n#define ICON_FA_PAINT_BRUSH u8\"\\uf1fc\"\n#define ICON_FA_PAINT_BRUSH_ALT u8\"\\uf5a9\"\n#define ICON_FA_PAINT_ROLLER u8\"\\uf5aa\"\n#define ICON_FA_PALETTE u8\"\\uf53f\"\n#define ICON_FA_PALLET u8\"\\uf482\"\n#define ICON_FA_PALLET_ALT u8\"\\uf483\"\n#define ICON_FA_PAPER_PLANE u8\"\\uf1d8\"\n#define ICON_FA_PAPERCLIP u8\"\\uf0c6\"\n#define ICON_FA_PARACHUTE_BOX u8\"\\uf4cd\"\n#define ICON_FA_PARAGRAPH u8\"\\uf1dd\"\n#define ICON_FA_PARAGRAPH_RTL u8\"\\uf878\"\n#define ICON_FA_PARKING u8\"\\uf540\"\n#define ICON_FA_PARKING_CIRCLE u8\"\\uf615\"\n#define ICON_FA_PARKING_CIRCLE_SLASH u8\"\\uf616\"\n#define ICON_FA_PARKING_SLASH u8\"\\uf617\"\n#define ICON_FA_PASSPORT u8\"\\uf5ab\"\n#define ICON_FA_PASTAFARIANISM u8\"\\uf67b\"\n#define ICON_FA_PASTE u8\"\\uf0ea\"\n#define ICON_FA_PAUSE u8\"\\uf04c\"\n#define ICON_FA_PAUSE_CIRCLE u8\"\\uf28b\"\n#define ICON_FA_PAW u8\"\\uf1b0\"\n#define ICON_FA_PAW_ALT u8\"\\uf701\"\n#define ICON_FA_PAW_CLAWS u8\"\\uf702\"\n#define ICON_FA_PEACE u8\"\\uf67c\"\n#define ICON_FA_PEGASUS u8\"\\uf703\"\n#define ICON_FA_PEN u8\"\\uf304\"\n#define ICON_FA_PEN_ALT u8\"\\uf305\"\n#define ICON_FA_PEN_FANCY u8\"\\uf5ac\"\n#define ICON_FA_PEN_NIB u8\"\\uf5ad\"\n#define ICON_FA_PEN_SQUARE u8\"\\uf14b\"\n#define ICON_FA_PENCIL u8\"\\uf040\"\n#define ICON_FA_PENCIL_ALT u8\"\\uf303\"\n#define ICON_FA_PENCIL_PAINTBRUSH u8\"\\uf618\"\n#define ICON_FA_PENCIL_RULER u8\"\\uf5ae\"\n#define ICON_FA_PENNANT u8\"\\uf456\"\n#define ICON_FA_PEOPLE_ARROWS u8\"\\uf968\"\n#define ICON_FA_PEOPLE_CARRY u8\"\\uf4ce\"\n#define ICON_FA_PEPPER_HOT u8\"\\uf816\"\n#define ICON_FA_PERCENT u8\"\\uf295\"\n#define ICON_FA_PERCENTAGE u8\"\\uf541\"\n#define ICON_FA_PERSON_BOOTH u8\"\\uf756\"\n#define ICON_FA_PERSON_CARRY u8\"\\uf4cf\"\n#define ICON_FA_PERSON_DOLLY u8\"\\uf4d0\"\n#define ICON_FA_PERSON_DOLLY_EMPTY u8\"\\uf4d1\"\n#define ICON_FA_PERSON_SIGN u8\"\\uf757\"\n#define ICON_FA_PHONE u8\"\\uf095\"\n#define ICON_FA_PHONE_ALT u8\"\\uf879\"\n#define ICON_FA_PHONE_LAPTOP u8\"\\uf87a\"\n#define ICON_FA_PHONE_OFFICE u8\"\\uf67d\"\n#define ICON_FA_PHONE_PLUS u8\"\\uf4d2\"\n#define ICON_FA_PHONE_ROTARY u8\"\\uf8d3\"\n#define ICON_FA_PHONE_SLASH u8\"\\uf3dd\"\n#define ICON_FA_PHONE_SQUARE u8\"\\uf098\"\n#define ICON_FA_PHONE_SQUARE_ALT u8\"\\uf87b\"\n#define ICON_FA_PHONE_VOLUME u8\"\\uf2a0\"\n#define ICON_FA_PHOTO_VIDEO u8\"\\uf87c\"\n#define ICON_FA_PI u8\"\\uf67e\"\n#define ICON_FA_PIANO u8\"\\uf8d4\"\n#define ICON_FA_PIANO_KEYBOARD u8\"\\uf8d5\"\n#define ICON_FA_PIE u8\"\\uf705\"\n#define ICON_FA_PIG u8\"\\uf706\"\n#define ICON_FA_PIGGY_BANK u8\"\\uf4d3\"\n#define ICON_FA_PILLS u8\"\\uf484\"\n#define ICON_FA_PIZZA u8\"\\uf817\"\n#define ICON_FA_PIZZA_SLICE u8\"\\uf818\"\n#define ICON_FA_PLACE_OF_WORSHIP u8\"\\uf67f\"\n#define ICON_FA_PLANE u8\"\\uf072\"\n#define ICON_FA_PLANE_ALT u8\"\\uf3de\"\n#define ICON_FA_PLANE_ARRIVAL u8\"\\uf5af\"\n#define ICON_FA_PLANE_DEPARTURE u8\"\\uf5b0\"\n#define ICON_FA_PLANE_SLASH u8\"\\uf969\"\n#define ICON_FA_PLANET_MOON u8\"\\uf91f\"\n#define ICON_FA_PLANET_RINGED u8\"\\uf920\"\n#define ICON_FA_PLAY u8\"\\uf04b\"\n#define ICON_FA_PLAY_CIRCLE u8\"\\uf144\"\n#define ICON_FA_PLUG u8\"\\uf1e6\"\n#define ICON_FA_PLUS u8\"\\uf067\"\n#define ICON_FA_PLUS_CIRCLE u8\"\\uf055\"\n#define ICON_FA_PLUS_HEXAGON u8\"\\uf300\"\n#define ICON_FA_PLUS_OCTAGON u8\"\\uf301\"\n#define ICON_FA_PLUS_SQUARE u8\"\\uf0fe\"\n#define ICON_FA_PODCAST u8\"\\uf2ce\"\n#define ICON_FA_PODIUM u8\"\\uf680\"\n#define ICON_FA_PODIUM_STAR u8\"\\uf758\"\n#define ICON_FA_POLICE_BOX u8\"\\uf921\"\n#define ICON_FA_POLL u8\"\\uf681\"\n#define ICON_FA_POLL_H u8\"\\uf682\"\n#define ICON_FA_POLL_PEOPLE u8\"\\uf759\"\n#define ICON_FA_POO u8\"\\uf2fe\"\n#define ICON_FA_POO_STORM u8\"\\uf75a\"\n#define ICON_FA_POOP u8\"\\uf619\"\n#define ICON_FA_POPCORN u8\"\\uf819\"\n#define ICON_FA_PORTAL_ENTER u8\"\\uf922\"\n#define ICON_FA_PORTAL_EXIT u8\"\\uf923\"\n#define ICON_FA_PORTRAIT u8\"\\uf3e0\"\n#define ICON_FA_POUND_SIGN u8\"\\uf154\"\n#define ICON_FA_POWER_OFF u8\"\\uf011\"\n#define ICON_FA_PRAY u8\"\\uf683\"\n#define ICON_FA_PRAYING_HANDS u8\"\\uf684\"\n#define ICON_FA_PRESCRIPTION u8\"\\uf5b1\"\n#define ICON_FA_PRESCRIPTION_BOTTLE u8\"\\uf485\"\n#define ICON_FA_PRESCRIPTION_BOTTLE_ALT u8\"\\uf486\"\n#define ICON_FA_PRESENTATION u8\"\\uf685\"\n#define ICON_FA_PRINT u8\"\\uf02f\"\n#define ICON_FA_PRINT_SEARCH u8\"\\uf81a\"\n#define ICON_FA_PRINT_SLASH u8\"\\uf686\"\n#define ICON_FA_PROCEDURES u8\"\\uf487\"\n#define ICON_FA_PROJECT_DIAGRAM u8\"\\uf542\"\n#define ICON_FA_PROJECTOR u8\"\\uf8d6\"\n#define ICON_FA_PUMP_MEDICAL u8\"\\uf96a\"\n#define ICON_FA_PUMP_SOAP u8\"\\uf96b\"\n#define ICON_FA_PUMPKIN u8\"\\uf707\"\n#define ICON_FA_PUZZLE_PIECE u8\"\\uf12e\"\n#define ICON_FA_QRCODE u8\"\\uf029\"\n#define ICON_FA_QUESTION u8\"\\uf128\"\n#define ICON_FA_QUESTION_CIRCLE u8\"\\uf059\"\n#define ICON_FA_QUESTION_SQUARE u8\"\\uf2fd\"\n#define ICON_FA_QUIDDITCH u8\"\\uf458\"\n#define ICON_FA_QUOTE_LEFT u8\"\\uf10d\"\n#define ICON_FA_QUOTE_RIGHT u8\"\\uf10e\"\n#define ICON_FA_QURAN u8\"\\uf687\"\n#define ICON_FA_RABBIT u8\"\\uf708\"\n#define ICON_FA_RABBIT_FAST u8\"\\uf709\"\n#define ICON_FA_RACQUET u8\"\\uf45a\"\n#define ICON_FA_RADAR u8\"\\uf924\"\n#define ICON_FA_RADIATION u8\"\\uf7b9\"\n#define ICON_FA_RADIATION_ALT u8\"\\uf7ba\"\n#define ICON_FA_RADIO u8\"\\uf8d7\"\n#define ICON_FA_RADIO_ALT u8\"\\uf8d8\"\n#define ICON_FA_RAINBOW u8\"\\uf75b\"\n#define ICON_FA_RAINDROPS u8\"\\uf75c\"\n#define ICON_FA_RAM u8\"\\uf70a\"\n#define ICON_FA_RAMP_LOADING u8\"\\uf4d4\"\n#define ICON_FA_RANDOM u8\"\\uf074\"\n#define ICON_FA_RAYGUN u8\"\\uf925\"\n#define ICON_FA_RECEIPT u8\"\\uf543\"\n#define ICON_FA_RECORD_VINYL u8\"\\uf8d9\"\n#define ICON_FA_RECTANGLE_LANDSCAPE u8\"\\uf2fa\"\n#define ICON_FA_RECTANGLE_PORTRAIT u8\"\\uf2fb\"\n#define ICON_FA_RECTANGLE_WIDE u8\"\\uf2fc\"\n#define ICON_FA_RECYCLE u8\"\\uf1b8\"\n#define ICON_FA_REDO u8\"\\uf01e\"\n#define ICON_FA_REDO_ALT u8\"\\uf2f9\"\n#define ICON_FA_REFRIGERATOR u8\"\\uf926\"\n#define ICON_FA_REGISTERED u8\"\\uf25d\"\n#define ICON_FA_REMOVE_FORMAT u8\"\\uf87d\"\n#define ICON_FA_REPEAT u8\"\\uf363\"\n#define ICON_FA_REPEAT_1 u8\"\\uf365\"\n#define ICON_FA_REPEAT_1_ALT u8\"\\uf366\"\n#define ICON_FA_REPEAT_ALT u8\"\\uf364\"\n#define ICON_FA_REPLY u8\"\\uf3e5\"\n#define ICON_FA_REPLY_ALL u8\"\\uf122\"\n#define ICON_FA_REPUBLICAN u8\"\\uf75e\"\n#define ICON_FA_RESTROOM u8\"\\uf7bd\"\n#define ICON_FA_RETWEET u8\"\\uf079\"\n#define ICON_FA_RETWEET_ALT u8\"\\uf361\"\n#define ICON_FA_RIBBON u8\"\\uf4d6\"\n#define ICON_FA_RING u8\"\\uf70b\"\n#define ICON_FA_RINGS_WEDDING u8\"\\uf81b\"\n#define ICON_FA_ROAD u8\"\\uf018\"\n#define ICON_FA_ROBOT u8\"\\uf544\"\n#define ICON_FA_ROCKET u8\"\\uf135\"\n#define ICON_FA_ROCKET_LAUNCH u8\"\\uf927\"\n#define ICON_FA_ROUTE u8\"\\uf4d7\"\n#define ICON_FA_ROUTE_HIGHWAY u8\"\\uf61a\"\n#define ICON_FA_ROUTE_INTERSTATE u8\"\\uf61b\"\n#define ICON_FA_ROUTER u8\"\\uf8da\"\n#define ICON_FA_RSS u8\"\\uf09e\"\n#define ICON_FA_RSS_SQUARE u8\"\\uf143\"\n#define ICON_FA_RUBLE_SIGN u8\"\\uf158\"\n#define ICON_FA_RULER u8\"\\uf545\"\n#define ICON_FA_RULER_COMBINED u8\"\\uf546\"\n#define ICON_FA_RULER_HORIZONTAL u8\"\\uf547\"\n#define ICON_FA_RULER_TRIANGLE u8\"\\uf61c\"\n#define ICON_FA_RULER_VERTICAL u8\"\\uf548\"\n#define ICON_FA_RUNNING u8\"\\uf70c\"\n#define ICON_FA_RUPEE_SIGN u8\"\\uf156\"\n#define ICON_FA_RV u8\"\\uf7be\"\n#define ICON_FA_SACK u8\"\\uf81c\"\n#define ICON_FA_SACK_DOLLAR u8\"\\uf81d\"\n#define ICON_FA_SAD_CRY u8\"\\uf5b3\"\n#define ICON_FA_SAD_TEAR u8\"\\uf5b4\"\n#define ICON_FA_SALAD u8\"\\uf81e\"\n#define ICON_FA_SANDWICH u8\"\\uf81f\"\n#define ICON_FA_SATELLITE u8\"\\uf7bf\"\n#define ICON_FA_SATELLITE_DISH u8\"\\uf7c0\"\n#define ICON_FA_SAUSAGE u8\"\\uf820\"\n#define ICON_FA_SAVE u8\"\\uf0c7\"\n#define ICON_FA_SAX_HOT u8\"\\uf8db\"\n#define ICON_FA_SAXOPHONE u8\"\\uf8dc\"\n#define ICON_FA_SCALPEL u8\"\\uf61d\"\n#define ICON_FA_SCALPEL_PATH u8\"\\uf61e\"\n#define ICON_FA_SCANNER u8\"\\uf488\"\n#define ICON_FA_SCANNER_IMAGE u8\"\\uf8f3\"\n#define ICON_FA_SCANNER_KEYBOARD u8\"\\uf489\"\n#define ICON_FA_SCANNER_TOUCHSCREEN u8\"\\uf48a\"\n#define ICON_FA_SCARECROW u8\"\\uf70d\"\n#define ICON_FA_SCARF u8\"\\uf7c1\"\n#define ICON_FA_SCHOOL u8\"\\uf549\"\n#define ICON_FA_SCREWDRIVER u8\"\\uf54a\"\n#define ICON_FA_SCROLL u8\"\\uf70e\"\n#define ICON_FA_SCROLL_OLD u8\"\\uf70f\"\n#define ICON_FA_SCRUBBER u8\"\\uf2f8\"\n#define ICON_FA_SCYTHE u8\"\\uf710\"\n#define ICON_FA_SD_CARD u8\"\\uf7c2\"\n#define ICON_FA_SEARCH u8\"\\uf002\"\n#define ICON_FA_SEARCH_DOLLAR u8\"\\uf688\"\n#define ICON_FA_SEARCH_LOCATION u8\"\\uf689\"\n#define ICON_FA_SEARCH_MINUS u8\"\\uf010\"\n#define ICON_FA_SEARCH_PLUS u8\"\\uf00e\"\n#define ICON_FA_SEEDLING u8\"\\uf4d8\"\n#define ICON_FA_SEND_BACK u8\"\\uf87e\"\n#define ICON_FA_SEND_BACKWARD u8\"\\uf87f\"\n#define ICON_FA_SENSOR u8\"\\uf928\"\n#define ICON_FA_SENSOR_ALERT u8\"\\uf929\"\n#define ICON_FA_SENSOR_FIRE u8\"\\uf92a\"\n#define ICON_FA_SENSOR_ON u8\"\\uf92b\"\n#define ICON_FA_SENSOR_SMOKE u8\"\\uf92c\"\n#define ICON_FA_SERVER u8\"\\uf233\"\n#define ICON_FA_SHAPES u8\"\\uf61f\"\n#define ICON_FA_SHARE u8\"\\uf064\"\n#define ICON_FA_SHARE_ALL u8\"\\uf367\"\n#define ICON_FA_SHARE_ALT u8\"\\uf1e0\"\n#define ICON_FA_SHARE_ALT_SQUARE u8\"\\uf1e1\"\n#define ICON_FA_SHARE_SQUARE u8\"\\uf14d\"\n#define ICON_FA_SHEEP u8\"\\uf711\"\n#define ICON_FA_SHEKEL_SIGN u8\"\\uf20b\"\n#define ICON_FA_SHIELD u8\"\\uf132\"\n#define ICON_FA_SHIELD_ALT u8\"\\uf3ed\"\n#define ICON_FA_SHIELD_CHECK u8\"\\uf2f7\"\n#define ICON_FA_SHIELD_CROSS u8\"\\uf712\"\n#define ICON_FA_SHIELD_VIRUS u8\"\\uf96c\"\n#define ICON_FA_SHIP u8\"\\uf21a\"\n#define ICON_FA_SHIPPING_FAST u8\"\\uf48b\"\n#define ICON_FA_SHIPPING_TIMED u8\"\\uf48c\"\n#define ICON_FA_SHISH_KEBAB u8\"\\uf821\"\n#define ICON_FA_SHOE_PRINTS u8\"\\uf54b\"\n#define ICON_FA_SHOPPING_BAG u8\"\\uf290\"\n#define ICON_FA_SHOPPING_BASKET u8\"\\uf291\"\n#define ICON_FA_SHOPPING_CART u8\"\\uf07a\"\n#define ICON_FA_SHOVEL u8\"\\uf713\"\n#define ICON_FA_SHOVEL_SNOW u8\"\\uf7c3\"\n#define ICON_FA_SHOWER u8\"\\uf2cc\"\n#define ICON_FA_SHREDDER u8\"\\uf68a\"\n#define ICON_FA_SHUTTLE_VAN u8\"\\uf5b6\"\n#define ICON_FA_SHUTTLECOCK u8\"\\uf45b\"\n#define ICON_FA_SICKLE u8\"\\uf822\"\n#define ICON_FA_SIGMA u8\"\\uf68b\"\n#define ICON_FA_SIGN u8\"\\uf4d9\"\n#define ICON_FA_SIGN_IN u8\"\\uf090\"\n#define ICON_FA_SIGN_IN_ALT u8\"\\uf2f6\"\n#define ICON_FA_SIGN_LANGUAGE u8\"\\uf2a7\"\n#define ICON_FA_SIGN_OUT u8\"\\uf08b\"\n#define ICON_FA_SIGN_OUT_ALT u8\"\\uf2f5\"\n#define ICON_FA_SIGNAL u8\"\\uf012\"\n#define ICON_FA_SIGNAL_1 u8\"\\uf68c\"\n#define ICON_FA_SIGNAL_2 u8\"\\uf68d\"\n#define ICON_FA_SIGNAL_3 u8\"\\uf68e\"\n#define ICON_FA_SIGNAL_4 u8\"\\uf68f\"\n#define ICON_FA_SIGNAL_ALT u8\"\\uf690\"\n#define ICON_FA_SIGNAL_ALT_1 u8\"\\uf691\"\n#define ICON_FA_SIGNAL_ALT_2 u8\"\\uf692\"\n#define ICON_FA_SIGNAL_ALT_3 u8\"\\uf693\"\n#define ICON_FA_SIGNAL_ALT_SLASH u8\"\\uf694\"\n#define ICON_FA_SIGNAL_SLASH u8\"\\uf695\"\n#define ICON_FA_SIGNAL_STREAM u8\"\\uf8dd\"\n#define ICON_FA_SIGNATURE u8\"\\uf5b7\"\n#define ICON_FA_SIM_CARD u8\"\\uf7c4\"\n#define ICON_FA_SINK u8\"\\uf96d\"\n#define ICON_FA_SIREN u8\"\\uf92d\"\n#define ICON_FA_SIREN_ON u8\"\\uf92e\"\n#define ICON_FA_SITEMAP u8\"\\uf0e8\"\n#define ICON_FA_SKATING u8\"\\uf7c5\"\n#define ICON_FA_SKELETON u8\"\\uf620\"\n#define ICON_FA_SKI_JUMP u8\"\\uf7c7\"\n#define ICON_FA_SKI_LIFT u8\"\\uf7c8\"\n#define ICON_FA_SKIING u8\"\\uf7c9\"\n#define ICON_FA_SKIING_NORDIC u8\"\\uf7ca\"\n#define ICON_FA_SKULL u8\"\\uf54c\"\n#define ICON_FA_SKULL_COW u8\"\\uf8de\"\n#define ICON_FA_SKULL_CROSSBONES u8\"\\uf714\"\n#define ICON_FA_SLASH u8\"\\uf715\"\n#define ICON_FA_SLEDDING u8\"\\uf7cb\"\n#define ICON_FA_SLEIGH u8\"\\uf7cc\"\n#define ICON_FA_SLIDERS_H u8\"\\uf1de\"\n#define ICON_FA_SLIDERS_H_SQUARE u8\"\\uf3f0\"\n#define ICON_FA_SLIDERS_V u8\"\\uf3f1\"\n#define ICON_FA_SLIDERS_V_SQUARE u8\"\\uf3f2\"\n#define ICON_FA_SMILE u8\"\\uf118\"\n#define ICON_FA_SMILE_BEAM u8\"\\uf5b8\"\n#define ICON_FA_SMILE_PLUS u8\"\\uf5b9\"\n#define ICON_FA_SMILE_WINK u8\"\\uf4da\"\n#define ICON_FA_SMOG u8\"\\uf75f\"\n#define ICON_FA_SMOKE u8\"\\uf760\"\n#define ICON_FA_SMOKING u8\"\\uf48d\"\n#define ICON_FA_SMOKING_BAN u8\"\\uf54d\"\n#define ICON_FA_SMS u8\"\\uf7cd\"\n#define ICON_FA_SNAKE u8\"\\uf716\"\n#define ICON_FA_SNOOZE u8\"\\uf880\"\n#define ICON_FA_SNOW_BLOWING u8\"\\uf761\"\n#define ICON_FA_SNOWBOARDING u8\"\\uf7ce\"\n#define ICON_FA_SNOWFLAKE u8\"\\uf2dc\"\n#define ICON_FA_SNOWFLAKES u8\"\\uf7cf\"\n#define ICON_FA_SNOWMAN u8\"\\uf7d0\"\n#define ICON_FA_SNOWMOBILE u8\"\\uf7d1\"\n#define ICON_FA_SNOWPLOW u8\"\\uf7d2\"\n#define ICON_FA_SOAP u8\"\\uf96e\"\n#define ICON_FA_SOCKS u8\"\\uf696\"\n#define ICON_FA_SOLAR_PANEL u8\"\\uf5ba\"\n#define ICON_FA_SOLAR_SYSTEM u8\"\\uf92f\"\n#define ICON_FA_SORT u8\"\\uf0dc\"\n#define ICON_FA_SORT_ALPHA_DOWN u8\"\\uf15d\"\n#define ICON_FA_SORT_ALPHA_DOWN_ALT u8\"\\uf881\"\n#define ICON_FA_SORT_ALPHA_UP u8\"\\uf15e\"\n#define ICON_FA_SORT_ALPHA_UP_ALT u8\"\\uf882\"\n#define ICON_FA_SORT_ALT u8\"\\uf883\"\n#define ICON_FA_SORT_AMOUNT_DOWN u8\"\\uf160\"\n#define ICON_FA_SORT_AMOUNT_DOWN_ALT u8\"\\uf884\"\n#define ICON_FA_SORT_AMOUNT_UP u8\"\\uf161\"\n#define ICON_FA_SORT_AMOUNT_UP_ALT u8\"\\uf885\"\n#define ICON_FA_SORT_CIRCLE u8\"\\uf930\"\n#define ICON_FA_SORT_CIRCLE_DOWN u8\"\\uf931\"\n#define ICON_FA_SORT_CIRCLE_UP u8\"\\uf932\"\n#define ICON_FA_SORT_DOWN u8\"\\uf0dd\"\n#define ICON_FA_SORT_NUMERIC_DOWN u8\"\\uf162\"\n#define ICON_FA_SORT_NUMERIC_DOWN_ALT u8\"\\uf886\"\n#define ICON_FA_SORT_NUMERIC_UP u8\"\\uf163\"\n#define ICON_FA_SORT_NUMERIC_UP_ALT u8\"\\uf887\"\n#define ICON_FA_SORT_SHAPES_DOWN u8\"\\uf888\"\n#define ICON_FA_SORT_SHAPES_DOWN_ALT u8\"\\uf889\"\n#define ICON_FA_SORT_SHAPES_UP u8\"\\uf88a\"\n#define ICON_FA_SORT_SHAPES_UP_ALT u8\"\\uf88b\"\n#define ICON_FA_SORT_SIZE_DOWN u8\"\\uf88c\"\n#define ICON_FA_SORT_SIZE_DOWN_ALT u8\"\\uf88d\"\n#define ICON_FA_SORT_SIZE_UP u8\"\\uf88e\"\n#define ICON_FA_SORT_SIZE_UP_ALT u8\"\\uf88f\"\n#define ICON_FA_SORT_UP u8\"\\uf0de\"\n#define ICON_FA_SOUP u8\"\\uf823\"\n#define ICON_FA_SPA u8\"\\uf5bb\"\n#define ICON_FA_SPACE_SHUTTLE u8\"\\uf197\"\n#define ICON_FA_SPACE_STATION_MOON u8\"\\uf933\"\n#define ICON_FA_SPACE_STATION_MOON_ALT u8\"\\uf934\"\n#define ICON_FA_SPADE u8\"\\uf2f4\"\n#define ICON_FA_SPARKLES u8\"\\uf890\"\n#define ICON_FA_SPEAKER u8\"\\uf8df\"\n#define ICON_FA_SPEAKERS u8\"\\uf8e0\"\n#define ICON_FA_SPELL_CHECK u8\"\\uf891\"\n#define ICON_FA_SPIDER u8\"\\uf717\"\n#define ICON_FA_SPIDER_BLACK_WIDOW u8\"\\uf718\"\n#define ICON_FA_SPIDER_WEB u8\"\\uf719\"\n#define ICON_FA_SPINNER u8\"\\uf110\"\n#define ICON_FA_SPINNER_THIRD u8\"\\uf3f4\"\n#define ICON_FA_SPLOTCH u8\"\\uf5bc\"\n#define ICON_FA_SPRAY_CAN u8\"\\uf5bd\"\n#define ICON_FA_SPRINKLER u8\"\\uf935\"\n#define ICON_FA_SQUARE u8\"\\uf0c8\"\n#define ICON_FA_SQUARE_FULL u8\"\\uf45c\"\n#define ICON_FA_SQUARE_ROOT u8\"\\uf697\"\n#define ICON_FA_SQUARE_ROOT_ALT u8\"\\uf698\"\n#define ICON_FA_SQUIRREL u8\"\\uf71a\"\n#define ICON_FA_STAFF u8\"\\uf71b\"\n#define ICON_FA_STAMP u8\"\\uf5bf\"\n#define ICON_FA_STAR u8\"\\uf005\"\n#define ICON_FA_STAR_AND_CRESCENT u8\"\\uf699\"\n#define ICON_FA_STAR_CHRISTMAS u8\"\\uf7d4\"\n#define ICON_FA_STAR_EXCLAMATION u8\"\\uf2f3\"\n#define ICON_FA_STAR_HALF u8\"\\uf089\"\n#define ICON_FA_STAR_HALF_ALT u8\"\\uf5c0\"\n#define ICON_FA_STAR_OF_DAVID u8\"\\uf69a\"\n#define ICON_FA_STAR_OF_LIFE u8\"\\uf621\"\n#define ICON_FA_STAR_SHOOTING u8\"\\uf936\"\n#define ICON_FA_STARFIGHTER u8\"\\uf937\"\n#define ICON_FA_STARFIGHTER_ALT u8\"\\uf938\"\n#define ICON_FA_STARS u8\"\\uf762\"\n#define ICON_FA_STARSHIP u8\"\\uf939\"\n#define ICON_FA_STARSHIP_FREIGHTER u8\"\\uf93a\"\n#define ICON_FA_STEAK u8\"\\uf824\"\n#define ICON_FA_STEERING_WHEEL u8\"\\uf622\"\n#define ICON_FA_STEP_BACKWARD u8\"\\uf048\"\n#define ICON_FA_STEP_FORWARD u8\"\\uf051\"\n#define ICON_FA_STETHOSCOPE u8\"\\uf0f1\"\n#define ICON_FA_STICKY_NOTE u8\"\\uf249\"\n#define ICON_FA_STOCKING u8\"\\uf7d5\"\n#define ICON_FA_STOMACH u8\"\\uf623\"\n#define ICON_FA_STOP u8\"\\uf04d\"\n#define ICON_FA_STOP_CIRCLE u8\"\\uf28d\"\n#define ICON_FA_STOPWATCH u8\"\\uf2f2\"\n#define ICON_FA_STOPWATCH_20 u8\"\\uf96f\"\n#define ICON_FA_STORE u8\"\\uf54e\"\n#define ICON_FA_STORE_ALT u8\"\\uf54f\"\n#define ICON_FA_STORE_ALT_SLASH u8\"\\uf970\"\n#define ICON_FA_STORE_SLASH u8\"\\uf971\"\n#define ICON_FA_STREAM u8\"\\uf550\"\n#define ICON_FA_STREET_VIEW u8\"\\uf21d\"\n#define ICON_FA_STRETCHER u8\"\\uf825\"\n#define ICON_FA_STRIKETHROUGH u8\"\\uf0cc\"\n#define ICON_FA_STROOPWAFEL u8\"\\uf551\"\n#define ICON_FA_SUBSCRIPT u8\"\\uf12c\"\n#define ICON_FA_SUBWAY u8\"\\uf239\"\n#define ICON_FA_SUITCASE u8\"\\uf0f2\"\n#define ICON_FA_SUITCASE_ROLLING u8\"\\uf5c1\"\n#define ICON_FA_SUN u8\"\\uf185\"\n#define ICON_FA_SUN_CLOUD u8\"\\uf763\"\n#define ICON_FA_SUN_DUST u8\"\\uf764\"\n#define ICON_FA_SUN_HAZE u8\"\\uf765\"\n#define ICON_FA_SUNGLASSES u8\"\\uf892\"\n#define ICON_FA_SUNRISE u8\"\\uf766\"\n#define ICON_FA_SUNSET u8\"\\uf767\"\n#define ICON_FA_SUPERSCRIPT u8\"\\uf12b\"\n#define ICON_FA_SURPRISE u8\"\\uf5c2\"\n#define ICON_FA_SWATCHBOOK u8\"\\uf5c3\"\n#define ICON_FA_SWIMMER u8\"\\uf5c4\"\n#define ICON_FA_SWIMMING_POOL u8\"\\uf5c5\"\n#define ICON_FA_SWORD u8\"\\uf71c\"\n#define ICON_FA_SWORD_LASER u8\"\\uf93b\"\n#define ICON_FA_SWORD_LASER_ALT u8\"\\uf93c\"\n#define ICON_FA_SWORDS u8\"\\uf71d\"\n#define ICON_FA_SWORDS_LASER u8\"\\uf93d\"\n#define ICON_FA_SYNAGOGUE u8\"\\uf69b\"\n#define ICON_FA_SYNC u8\"\\uf021\"\n#define ICON_FA_SYNC_ALT u8\"\\uf2f1\"\n#define ICON_FA_SYRINGE u8\"\\uf48e\"\n#define ICON_FA_TABLE u8\"\\uf0ce\"\n#define ICON_FA_TABLE_TENNIS u8\"\\uf45d\"\n#define ICON_FA_TABLET u8\"\\uf10a\"\n#define ICON_FA_TABLET_ALT u8\"\\uf3fa\"\n#define ICON_FA_TABLET_ANDROID u8\"\\uf3fb\"\n#define ICON_FA_TABLET_ANDROID_ALT u8\"\\uf3fc\"\n#define ICON_FA_TABLET_RUGGED u8\"\\uf48f\"\n#define ICON_FA_TABLETS u8\"\\uf490\"\n#define ICON_FA_TACHOMETER u8\"\\uf0e4\"\n#define ICON_FA_TACHOMETER_ALT u8\"\\uf3fd\"\n#define ICON_FA_TACHOMETER_ALT_AVERAGE u8\"\\uf624\"\n#define ICON_FA_TACHOMETER_ALT_FAST u8\"\\uf625\"\n#define ICON_FA_TACHOMETER_ALT_FASTEST u8\"\\uf626\"\n#define ICON_FA_TACHOMETER_ALT_SLOW u8\"\\uf627\"\n#define ICON_FA_TACHOMETER_ALT_SLOWEST u8\"\\uf628\"\n#define ICON_FA_TACHOMETER_AVERAGE u8\"\\uf629\"\n#define ICON_FA_TACHOMETER_FAST u8\"\\uf62a\"\n#define ICON_FA_TACHOMETER_FASTEST u8\"\\uf62b\"\n#define ICON_FA_TACHOMETER_SLOW u8\"\\uf62c\"\n#define ICON_FA_TACHOMETER_SLOWEST u8\"\\uf62d\"\n#define ICON_FA_TACO u8\"\\uf826\"\n#define ICON_FA_TAG u8\"\\uf02b\"\n#define ICON_FA_TAGS u8\"\\uf02c\"\n#define ICON_FA_TALLY u8\"\\uf69c\"\n#define ICON_FA_TANAKH u8\"\\uf827\"\n#define ICON_FA_TAPE u8\"\\uf4db\"\n#define ICON_FA_TASKS u8\"\\uf0ae\"\n#define ICON_FA_TASKS_ALT u8\"\\uf828\"\n#define ICON_FA_TAXI u8\"\\uf1ba\"\n#define ICON_FA_TEETH u8\"\\uf62e\"\n#define ICON_FA_TEETH_OPEN u8\"\\uf62f\"\n#define ICON_FA_TELESCOPE u8\"\\uf93e\"\n#define ICON_FA_TEMPERATURE_DOWN u8\"\\uf93f\"\n#define ICON_FA_TEMPERATURE_FRIGID u8\"\\uf768\"\n#define ICON_FA_TEMPERATURE_HIGH u8\"\\uf769\"\n#define ICON_FA_TEMPERATURE_HOT u8\"\\uf76a\"\n#define ICON_FA_TEMPERATURE_LOW u8\"\\uf76b\"\n#define ICON_FA_TEMPERATURE_UP u8\"\\uf940\"\n#define ICON_FA_TENGE u8\"\\uf7d7\"\n#define ICON_FA_TENNIS_BALL u8\"\\uf45e\"\n#define ICON_FA_TERMINAL u8\"\\uf120\"\n#define ICON_FA_TEXT u8\"\\uf893\"\n#define ICON_FA_TEXT_HEIGHT u8\"\\uf034\"\n#define ICON_FA_TEXT_SIZE u8\"\\uf894\"\n#define ICON_FA_TEXT_WIDTH u8\"\\uf035\"\n#define ICON_FA_TH u8\"\\uf00a\"\n#define ICON_FA_TH_LARGE u8\"\\uf009\"\n#define ICON_FA_TH_LIST u8\"\\uf00b\"\n#define ICON_FA_THEATER_MASKS u8\"\\uf630\"\n#define ICON_FA_THERMOMETER u8\"\\uf491\"\n#define ICON_FA_THERMOMETER_EMPTY u8\"\\uf2cb\"\n#define ICON_FA_THERMOMETER_FULL u8\"\\uf2c7\"\n#define ICON_FA_THERMOMETER_HALF u8\"\\uf2c9\"\n#define ICON_FA_THERMOMETER_QUARTER u8\"\\uf2ca\"\n#define ICON_FA_THERMOMETER_THREE_QUARTERS u8\"\\uf2c8\"\n#define ICON_FA_THETA u8\"\\uf69e\"\n#define ICON_FA_THUMBS_DOWN u8\"\\uf165\"\n#define ICON_FA_THUMBS_UP u8\"\\uf164\"\n#define ICON_FA_THUMBTACK u8\"\\uf08d\"\n#define ICON_FA_THUNDERSTORM u8\"\\uf76c\"\n#define ICON_FA_THUNDERSTORM_MOON u8\"\\uf76d\"\n#define ICON_FA_THUNDERSTORM_SUN u8\"\\uf76e\"\n#define ICON_FA_TICKET u8\"\\uf145\"\n#define ICON_FA_TICKET_ALT u8\"\\uf3ff\"\n#define ICON_FA_TILDE u8\"\\uf69f\"\n#define ICON_FA_TIMES u8\"\\uf00d\"\n#define ICON_FA_TIMES_CIRCLE u8\"\\uf057\"\n#define ICON_FA_TIMES_HEXAGON u8\"\\uf2ee\"\n#define ICON_FA_TIMES_OCTAGON u8\"\\uf2f0\"\n#define ICON_FA_TIMES_SQUARE u8\"\\uf2d3\"\n#define ICON_FA_TINT u8\"\\uf043\"\n#define ICON_FA_TINT_SLASH u8\"\\uf5c7\"\n#define ICON_FA_TIRE u8\"\\uf631\"\n#define ICON_FA_TIRE_FLAT u8\"\\uf632\"\n#define ICON_FA_TIRE_PRESSURE_WARNING u8\"\\uf633\"\n#define ICON_FA_TIRE_RUGGED u8\"\\uf634\"\n#define ICON_FA_TIRED u8\"\\uf5c8\"\n#define ICON_FA_TOGGLE_OFF u8\"\\uf204\"\n#define ICON_FA_TOGGLE_ON u8\"\\uf205\"\n#define ICON_FA_TOILET u8\"\\uf7d8\"\n#define ICON_FA_TOILET_PAPER u8\"\\uf71e\"\n#define ICON_FA_TOILET_PAPER_ALT u8\"\\uf71f\"\n#define ICON_FA_TOILET_PAPER_SLASH u8\"\\uf972\"\n#define ICON_FA_TOMBSTONE u8\"\\uf720\"\n#define ICON_FA_TOMBSTONE_ALT u8\"\\uf721\"\n#define ICON_FA_TOOLBOX u8\"\\uf552\"\n#define ICON_FA_TOOLS u8\"\\uf7d9\"\n#define ICON_FA_TOOTH u8\"\\uf5c9\"\n#define ICON_FA_TOOTHBRUSH u8\"\\uf635\"\n#define ICON_FA_TORAH u8\"\\uf6a0\"\n#define ICON_FA_TORII_GATE u8\"\\uf6a1\"\n#define ICON_FA_TORNADO u8\"\\uf76f\"\n#define ICON_FA_TRACTOR u8\"\\uf722\"\n#define ICON_FA_TRADEMARK u8\"\\uf25c\"\n#define ICON_FA_TRAFFIC_CONE u8\"\\uf636\"\n#define ICON_FA_TRAFFIC_LIGHT u8\"\\uf637\"\n#define ICON_FA_TRAFFIC_LIGHT_GO u8\"\\uf638\"\n#define ICON_FA_TRAFFIC_LIGHT_SLOW u8\"\\uf639\"\n#define ICON_FA_TRAFFIC_LIGHT_STOP u8\"\\uf63a\"\n#define ICON_FA_TRAILER u8\"\\uf941\"\n#define ICON_FA_TRAIN u8\"\\uf238\"\n#define ICON_FA_TRAM u8\"\\uf7da\"\n#define ICON_FA_TRANSGENDER u8\"\\uf224\"\n#define ICON_FA_TRANSGENDER_ALT u8\"\\uf225\"\n#define ICON_FA_TRANSPORTER u8\"\\uf942\"\n#define ICON_FA_TRANSPORTER_1 u8\"\\uf943\"\n#define ICON_FA_TRANSPORTER_2 u8\"\\uf944\"\n#define ICON_FA_TRANSPORTER_3 u8\"\\uf945\"\n#define ICON_FA_TRANSPORTER_EMPTY u8\"\\uf946\"\n#define ICON_FA_TRASH u8\"\\uf1f8\"\n#define ICON_FA_TRASH_ALT u8\"\\uf2ed\"\n#define ICON_FA_TRASH_RESTORE u8\"\\uf829\"\n#define ICON_FA_TRASH_RESTORE_ALT u8\"\\uf82a\"\n#define ICON_FA_TRASH_UNDO u8\"\\uf895\"\n#define ICON_FA_TRASH_UNDO_ALT u8\"\\uf896\"\n#define ICON_FA_TREASURE_CHEST u8\"\\uf723\"\n#define ICON_FA_TREE u8\"\\uf1bb\"\n#define ICON_FA_TREE_ALT u8\"\\uf400\"\n#define ICON_FA_TREE_CHRISTMAS u8\"\\uf7db\"\n#define ICON_FA_TREE_DECORATED u8\"\\uf7dc\"\n#define ICON_FA_TREE_LARGE u8\"\\uf7dd\"\n#define ICON_FA_TREE_PALM u8\"\\uf82b\"\n#define ICON_FA_TREES u8\"\\uf724\"\n#define ICON_FA_TRIANGLE u8\"\\uf2ec\"\n#define ICON_FA_TRIANGLE_MUSIC u8\"\\uf8e2\"\n#define ICON_FA_TROPHY u8\"\\uf091\"\n#define ICON_FA_TROPHY_ALT u8\"\\uf2eb\"\n#define ICON_FA_TRUCK u8\"\\uf0d1\"\n#define ICON_FA_TRUCK_CONTAINER u8\"\\uf4dc\"\n#define ICON_FA_TRUCK_COUCH u8\"\\uf4dd\"\n#define ICON_FA_TRUCK_LOADING u8\"\\uf4de\"\n#define ICON_FA_TRUCK_MONSTER u8\"\\uf63b\"\n#define ICON_FA_TRUCK_MOVING u8\"\\uf4df\"\n#define ICON_FA_TRUCK_PICKUP u8\"\\uf63c\"\n#define ICON_FA_TRUCK_PLOW u8\"\\uf7de\"\n#define ICON_FA_TRUCK_RAMP u8\"\\uf4e0\"\n#define ICON_FA_TRUMPET u8\"\\uf8e3\"\n#define ICON_FA_TSHIRT u8\"\\uf553\"\n#define ICON_FA_TTY u8\"\\uf1e4\"\n#define ICON_FA_TURKEY u8\"\\uf725\"\n#define ICON_FA_TURNTABLE u8\"\\uf8e4\"\n#define ICON_FA_TURTLE u8\"\\uf726\"\n#define ICON_FA_TV u8\"\\uf26c\"\n#define ICON_FA_TV_ALT u8\"\\uf8e5\"\n#define ICON_FA_TV_MUSIC u8\"\\uf8e6\"\n#define ICON_FA_TV_RETRO u8\"\\uf401\"\n#define ICON_FA_TYPEWRITER u8\"\\uf8e7\"\n#define ICON_FA_UFO u8\"\\uf947\"\n#define ICON_FA_UFO_BEAM u8\"\\uf948\"\n#define ICON_FA_UMBRELLA u8\"\\uf0e9\"\n#define ICON_FA_UMBRELLA_BEACH u8\"\\uf5ca\"\n#define ICON_FA_UNDERLINE u8\"\\uf0cd\"\n#define ICON_FA_UNDO u8\"\\uf0e2\"\n#define ICON_FA_UNDO_ALT u8\"\\uf2ea\"\n#define ICON_FA_UNICORN u8\"\\uf727\"\n#define ICON_FA_UNION u8\"\\uf6a2\"\n#define ICON_FA_UNIVERSAL_ACCESS u8\"\\uf29a\"\n#define ICON_FA_UNIVERSITY u8\"\\uf19c\"\n#define ICON_FA_UNLINK u8\"\\uf127\"\n#define ICON_FA_UNLOCK u8\"\\uf09c\"\n#define ICON_FA_UNLOCK_ALT u8\"\\uf13e\"\n#define ICON_FA_UPLOAD u8\"\\uf093\"\n#define ICON_FA_USB_DRIVE u8\"\\uf8e9\"\n#define ICON_FA_USD_CIRCLE u8\"\\uf2e8\"\n#define ICON_FA_USD_SQUARE u8\"\\uf2e9\"\n#define ICON_FA_USER u8\"\\uf007\"\n#define ICON_FA_USER_ALIEN u8\"\\uf94a\"\n#define ICON_FA_USER_ALT u8\"\\uf406\"\n#define ICON_FA_USER_ALT_SLASH u8\"\\uf4fa\"\n#define ICON_FA_USER_ASTRONAUT u8\"\\uf4fb\"\n#define ICON_FA_USER_CHART u8\"\\uf6a3\"\n#define ICON_FA_USER_CHECK u8\"\\uf4fc\"\n#define ICON_FA_USER_CIRCLE u8\"\\uf2bd\"\n#define ICON_FA_USER_CLOCK u8\"\\uf4fd\"\n#define ICON_FA_USER_COG u8\"\\uf4fe\"\n#define ICON_FA_USER_COWBOY u8\"\\uf8ea\"\n#define ICON_FA_USER_CROWN u8\"\\uf6a4\"\n#define ICON_FA_USER_EDIT u8\"\\uf4ff\"\n#define ICON_FA_USER_FRIENDS u8\"\\uf500\"\n#define ICON_FA_USER_GRADUATE u8\"\\uf501\"\n#define ICON_FA_USER_HARD_HAT u8\"\\uf82c\"\n#define ICON_FA_USER_HEADSET u8\"\\uf82d\"\n#define ICON_FA_USER_INJURED u8\"\\uf728\"\n#define ICON_FA_USER_LOCK u8\"\\uf502\"\n#define ICON_FA_USER_MD u8\"\\uf0f0\"\n#define ICON_FA_USER_MD_CHAT u8\"\\uf82e\"\n#define ICON_FA_USER_MINUS u8\"\\uf503\"\n#define ICON_FA_USER_MUSIC u8\"\\uf8eb\"\n#define ICON_FA_USER_NINJA u8\"\\uf504\"\n#define ICON_FA_USER_NURSE u8\"\\uf82f\"\n#define ICON_FA_USER_PLUS u8\"\\uf234\"\n#define ICON_FA_USER_ROBOT u8\"\\uf94b\"\n#define ICON_FA_USER_SECRET u8\"\\uf21b\"\n#define ICON_FA_USER_SHIELD u8\"\\uf505\"\n#define ICON_FA_USER_SLASH u8\"\\uf506\"\n#define ICON_FA_USER_TAG u8\"\\uf507\"\n#define ICON_FA_USER_TIE u8\"\\uf508\"\n#define ICON_FA_USER_TIMES u8\"\\uf235\"\n#define ICON_FA_USER_UNLOCK u8\"\\uf958\"\n#define ICON_FA_USER_VISOR u8\"\\uf94c\"\n#define ICON_FA_USERS u8\"\\uf0c0\"\n#define ICON_FA_USERS_CLASS u8\"\\uf63d\"\n#define ICON_FA_USERS_COG u8\"\\uf509\"\n#define ICON_FA_USERS_CROWN u8\"\\uf6a5\"\n#define ICON_FA_USERS_MEDICAL u8\"\\uf830\"\n#define ICON_FA_USERS_SLASH u8\"\\uf973\"\n#define ICON_FA_UTENSIL_FORK u8\"\\uf2e3\"\n#define ICON_FA_UTENSIL_KNIFE u8\"\\uf2e4\"\n#define ICON_FA_UTENSIL_SPOON u8\"\\uf2e5\"\n#define ICON_FA_UTENSILS u8\"\\uf2e7\"\n#define ICON_FA_UTENSILS_ALT u8\"\\uf2e6\"\n#define ICON_FA_VACUUM u8\"\\uf94d\"\n#define ICON_FA_VACUUM_ROBOT u8\"\\uf94e\"\n#define ICON_FA_VALUE_ABSOLUTE u8\"\\uf6a6\"\n#define ICON_FA_VECTOR_SQUARE u8\"\\uf5cb\"\n#define ICON_FA_VENUS u8\"\\uf221\"\n#define ICON_FA_VENUS_DOUBLE u8\"\\uf226\"\n#define ICON_FA_VENUS_MARS u8\"\\uf228\"\n#define ICON_FA_VHS u8\"\\uf8ec\"\n#define ICON_FA_VIAL u8\"\\uf492\"\n#define ICON_FA_VIALS u8\"\\uf493\"\n#define ICON_FA_VIDEO u8\"\\uf03d\"\n#define ICON_FA_VIDEO_PLUS u8\"\\uf4e1\"\n#define ICON_FA_VIDEO_SLASH u8\"\\uf4e2\"\n#define ICON_FA_VIHARA u8\"\\uf6a7\"\n#define ICON_FA_VIOLIN u8\"\\uf8ed\"\n#define ICON_FA_VIRUS u8\"\\uf974\"\n#define ICON_FA_VIRUS_SLASH u8\"\\uf975\"\n#define ICON_FA_VIRUSES u8\"\\uf976\"\n#define ICON_FA_VOICEMAIL u8\"\\uf897\"\n#define ICON_FA_VOLCANO u8\"\\uf770\"\n#define ICON_FA_VOLLEYBALL_BALL u8\"\\uf45f\"\n#define ICON_FA_VOLUME u8\"\\uf6a8\"\n#define ICON_FA_VOLUME_DOWN u8\"\\uf027\"\n#define ICON_FA_VOLUME_MUTE u8\"\\uf6a9\"\n#define ICON_FA_VOLUME_OFF u8\"\\uf026\"\n#define ICON_FA_VOLUME_SLASH u8\"\\uf2e2\"\n#define ICON_FA_VOLUME_UP u8\"\\uf028\"\n#define ICON_FA_VOTE_NAY u8\"\\uf771\"\n#define ICON_FA_VOTE_YEA u8\"\\uf772\"\n#define ICON_FA_VR_CARDBOARD u8\"\\uf729\"\n#define ICON_FA_WAGON_COVERED u8\"\\uf8ee\"\n#define ICON_FA_WALKER u8\"\\uf831\"\n#define ICON_FA_WALKIE_TALKIE u8\"\\uf8ef\"\n#define ICON_FA_WALKING u8\"\\uf554\"\n#define ICON_FA_WALLET u8\"\\uf555\"\n#define ICON_FA_WAND u8\"\\uf72a\"\n#define ICON_FA_WAND_MAGIC u8\"\\uf72b\"\n#define ICON_FA_WAREHOUSE u8\"\\uf494\"\n#define ICON_FA_WAREHOUSE_ALT u8\"\\uf495\"\n#define ICON_FA_WASHER u8\"\\uf898\"\n#define ICON_FA_WATCH u8\"\\uf2e1\"\n#define ICON_FA_WATCH_CALCULATOR u8\"\\uf8f0\"\n#define ICON_FA_WATCH_FITNESS u8\"\\uf63e\"\n#define ICON_FA_WATER u8\"\\uf773\"\n#define ICON_FA_WATER_LOWER u8\"\\uf774\"\n#define ICON_FA_WATER_RISE u8\"\\uf775\"\n#define ICON_FA_WAVE_SINE u8\"\\uf899\"\n#define ICON_FA_WAVE_SQUARE u8\"\\uf83e\"\n#define ICON_FA_WAVE_TRIANGLE u8\"\\uf89a\"\n#define ICON_FA_WAVEFORM u8\"\\uf8f1\"\n#define ICON_FA_WAVEFORM_PATH u8\"\\uf8f2\"\n#define ICON_FA_WEBCAM u8\"\\uf832\"\n#define ICON_FA_WEBCAM_SLASH u8\"\\uf833\"\n#define ICON_FA_WEIGHT u8\"\\uf496\"\n#define ICON_FA_WEIGHT_HANGING u8\"\\uf5cd\"\n#define ICON_FA_WHALE u8\"\\uf72c\"\n#define ICON_FA_WHEAT u8\"\\uf72d\"\n#define ICON_FA_WHEELCHAIR u8\"\\uf193\"\n#define ICON_FA_WHISTLE u8\"\\uf460\"\n#define ICON_FA_WIFI u8\"\\uf1eb\"\n#define ICON_FA_WIFI_1 u8\"\\uf6aa\"\n#define ICON_FA_WIFI_2 u8\"\\uf6ab\"\n#define ICON_FA_WIFI_SLASH u8\"\\uf6ac\"\n#define ICON_FA_WIND u8\"\\uf72e\"\n#define ICON_FA_WIND_TURBINE u8\"\\uf89b\"\n#define ICON_FA_WIND_WARNING u8\"\\uf776\"\n#define ICON_FA_WINDOW u8\"\\uf40e\"\n#define ICON_FA_WINDOW_ALT u8\"\\uf40f\"\n#define ICON_FA_WINDOW_CLOSE u8\"\\uf410\"\n#define ICON_FA_WINDOW_FRAME u8\"\\uf94f\"\n#define ICON_FA_WINDOW_FRAME_OPEN u8\"\\uf950\"\n#define ICON_FA_WINDOW_MAXIMIZE u8\"\\uf2d0\"\n#define ICON_FA_WINDOW_MINIMIZE u8\"\\uf2d1\"\n#define ICON_FA_WINDOW_RESTORE u8\"\\uf2d2\"\n#define ICON_FA_WINDSOCK u8\"\\uf777\"\n#define ICON_FA_WINE_BOTTLE u8\"\\uf72f\"\n#define ICON_FA_WINE_GLASS u8\"\\uf4e3\"\n#define ICON_FA_WINE_GLASS_ALT u8\"\\uf5ce\"\n#define ICON_FA_WON_SIGN u8\"\\uf159\"\n#define ICON_FA_WREATH u8\"\\uf7e2\"\n#define ICON_FA_WRENCH u8\"\\uf0ad\"\n#define ICON_FA_X_RAY u8\"\\uf497\"\n#define ICON_FA_YEN_SIGN u8\"\\uf157\"\n#define ICON_FA_YIN_YANG u8\"\\uf6ad\"\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/IconFontCppHeaders/IconsFontAwesome5ProBrands.h",
    "content": "// Generated by https://github.com/juliettef/IconFontCppHeaders script GenerateIconFontCppHeaders.py for language C++11\n// from icons.yml\n// for use with fa-brands-400.ttf\n#pragma once\n\n#define FONT_ICON_FILE_NAME_FAB \"fa-brands-400.ttf\"\n\n#define ICON_MIN_FAB 0xf081\n#define ICON_MAX_FAB 0xf97c\n#define ICON_FA_500PX u8\"\\uf26e\"\n#define ICON_FA_ACCESSIBLE_ICON u8\"\\uf368\"\n#define ICON_FA_ACCUSOFT u8\"\\uf369\"\n#define ICON_FA_ACQUISITIONS_INCORPORATED u8\"\\uf6af\"\n#define ICON_FA_ADN u8\"\\uf170\"\n#define ICON_FA_ADOBE u8\"\\uf778\"\n#define ICON_FA_ADVERSAL u8\"\\uf36a\"\n#define ICON_FA_AFFILIATETHEME u8\"\\uf36b\"\n#define ICON_FA_AIRBNB u8\"\\uf834\"\n#define ICON_FA_ALGOLIA u8\"\\uf36c\"\n#define ICON_FA_ALIPAY u8\"\\uf642\"\n#define ICON_FA_AMAZON u8\"\\uf270\"\n#define ICON_FA_AMAZON_PAY u8\"\\uf42c\"\n#define ICON_FA_AMILIA u8\"\\uf36d\"\n#define ICON_FA_ANDROID u8\"\\uf17b\"\n#define ICON_FA_ANGELLIST u8\"\\uf209\"\n#define ICON_FA_ANGRYCREATIVE u8\"\\uf36e\"\n#define ICON_FA_ANGULAR u8\"\\uf420\"\n#define ICON_FA_APP_STORE u8\"\\uf36f\"\n#define ICON_FA_APP_STORE_IOS u8\"\\uf370\"\n#define ICON_FA_APPER u8\"\\uf371\"\n#define ICON_FA_APPLE u8\"\\uf179\"\n#define ICON_FA_APPLE_PAY u8\"\\uf415\"\n#define ICON_FA_ARTSTATION u8\"\\uf77a\"\n#define ICON_FA_ASYMMETRIK u8\"\\uf372\"\n#define ICON_FA_ATLASSIAN u8\"\\uf77b\"\n#define ICON_FA_AUDIBLE u8\"\\uf373\"\n#define ICON_FA_AUTOPREFIXER u8\"\\uf41c\"\n#define ICON_FA_AVIANEX u8\"\\uf374\"\n#define ICON_FA_AVIATO u8\"\\uf421\"\n#define ICON_FA_AWS u8\"\\uf375\"\n#define ICON_FA_BANDCAMP u8\"\\uf2d5\"\n#define ICON_FA_BATTLE_NET u8\"\\uf835\"\n#define ICON_FA_BEHANCE u8\"\\uf1b4\"\n#define ICON_FA_BEHANCE_SQUARE u8\"\\uf1b5\"\n#define ICON_FA_BIMOBJECT u8\"\\uf378\"\n#define ICON_FA_BITBUCKET u8\"\\uf171\"\n#define ICON_FA_BITCOIN u8\"\\uf379\"\n#define ICON_FA_BITY u8\"\\uf37a\"\n#define ICON_FA_BLACK_TIE u8\"\\uf27e\"\n#define ICON_FA_BLACKBERRY u8\"\\uf37b\"\n#define ICON_FA_BLOGGER u8\"\\uf37c\"\n#define ICON_FA_BLOGGER_B u8\"\\uf37d\"\n#define ICON_FA_BLUETOOTH u8\"\\uf293\"\n#define ICON_FA_BLUETOOTH_B u8\"\\uf294\"\n#define ICON_FA_BOOTSTRAP u8\"\\uf836\"\n#define ICON_FA_BTC u8\"\\uf15a\"\n#define ICON_FA_BUFFER u8\"\\uf837\"\n#define ICON_FA_BUROMOBELEXPERTE u8\"\\uf37f\"\n#define ICON_FA_BUY_N_LARGE u8\"\\uf8a6\"\n#define ICON_FA_BUYSELLADS u8\"\\uf20d\"\n#define ICON_FA_CANADIAN_MAPLE_LEAF u8\"\\uf785\"\n#define ICON_FA_CC_AMAZON_PAY u8\"\\uf42d\"\n#define ICON_FA_CC_AMEX u8\"\\uf1f3\"\n#define ICON_FA_CC_APPLE_PAY u8\"\\uf416\"\n#define ICON_FA_CC_DINERS_CLUB u8\"\\uf24c\"\n#define ICON_FA_CC_DISCOVER u8\"\\uf1f2\"\n#define ICON_FA_CC_JCB u8\"\\uf24b\"\n#define ICON_FA_CC_MASTERCARD u8\"\\uf1f1\"\n#define ICON_FA_CC_PAYPAL u8\"\\uf1f4\"\n#define ICON_FA_CC_STRIPE u8\"\\uf1f5\"\n#define ICON_FA_CC_VISA u8\"\\uf1f0\"\n#define ICON_FA_CENTERCODE u8\"\\uf380\"\n#define ICON_FA_CENTOS u8\"\\uf789\"\n#define ICON_FA_CHROME u8\"\\uf268\"\n#define ICON_FA_CHROMECAST u8\"\\uf838\"\n#define ICON_FA_CLOUDSCALE u8\"\\uf383\"\n#define ICON_FA_CLOUDSMITH u8\"\\uf384\"\n#define ICON_FA_CLOUDVERSIFY u8\"\\uf385\"\n#define ICON_FA_CODEPEN u8\"\\uf1cb\"\n#define ICON_FA_CODIEPIE u8\"\\uf284\"\n#define ICON_FA_CONFLUENCE u8\"\\uf78d\"\n#define ICON_FA_CONNECTDEVELOP u8\"\\uf20e\"\n#define ICON_FA_CONTAO u8\"\\uf26d\"\n#define ICON_FA_COTTON_BUREAU u8\"\\uf89e\"\n#define ICON_FA_CPANEL u8\"\\uf388\"\n#define ICON_FA_CREATIVE_COMMONS u8\"\\uf25e\"\n#define ICON_FA_CREATIVE_COMMONS_BY u8\"\\uf4e7\"\n#define ICON_FA_CREATIVE_COMMONS_NC u8\"\\uf4e8\"\n#define ICON_FA_CREATIVE_COMMONS_NC_EU u8\"\\uf4e9\"\n#define ICON_FA_CREATIVE_COMMONS_NC_JP u8\"\\uf4ea\"\n#define ICON_FA_CREATIVE_COMMONS_ND u8\"\\uf4eb\"\n#define ICON_FA_CREATIVE_COMMONS_PD u8\"\\uf4ec\"\n#define ICON_FA_CREATIVE_COMMONS_PD_ALT u8\"\\uf4ed\"\n#define ICON_FA_CREATIVE_COMMONS_REMIX u8\"\\uf4ee\"\n#define ICON_FA_CREATIVE_COMMONS_SA u8\"\\uf4ef\"\n#define ICON_FA_CREATIVE_COMMONS_SAMPLING u8\"\\uf4f0\"\n#define ICON_FA_CREATIVE_COMMONS_SAMPLING_PLUS u8\"\\uf4f1\"\n#define ICON_FA_CREATIVE_COMMONS_SHARE u8\"\\uf4f2\"\n#define ICON_FA_CREATIVE_COMMONS_ZERO u8\"\\uf4f3\"\n#define ICON_FA_CRITICAL_ROLE u8\"\\uf6c9\"\n#define ICON_FA_CSS3 u8\"\\uf13c\"\n#define ICON_FA_CSS3_ALT u8\"\\uf38b\"\n#define ICON_FA_CUTTLEFISH u8\"\\uf38c\"\n#define ICON_FA_D_AND_D u8\"\\uf38d\"\n#define ICON_FA_D_AND_D_BEYOND u8\"\\uf6ca\"\n#define ICON_FA_DAILYMOTION u8\"\\uf952\"\n#define ICON_FA_DASHCUBE u8\"\\uf210\"\n#define ICON_FA_DEEZER u8\"\\uf977\"\n#define ICON_FA_DELICIOUS u8\"\\uf1a5\"\n#define ICON_FA_DEPLOYDOG u8\"\\uf38e\"\n#define ICON_FA_DESKPRO u8\"\\uf38f\"\n#define ICON_FA_DEV u8\"\\uf6cc\"\n#define ICON_FA_DEVIANTART u8\"\\uf1bd\"\n#define ICON_FA_DHL u8\"\\uf790\"\n#define ICON_FA_DIASPORA u8\"\\uf791\"\n#define ICON_FA_DIGG u8\"\\uf1a6\"\n#define ICON_FA_DIGITAL_OCEAN u8\"\\uf391\"\n#define ICON_FA_DISCORD u8\"\\uf392\"\n#define ICON_FA_DISCOURSE u8\"\\uf393\"\n#define ICON_FA_DOCHUB u8\"\\uf394\"\n#define ICON_FA_DOCKER u8\"\\uf395\"\n#define ICON_FA_DRAFT2DIGITAL u8\"\\uf396\"\n#define ICON_FA_DRIBBBLE u8\"\\uf17d\"\n#define ICON_FA_DRIBBBLE_SQUARE u8\"\\uf397\"\n#define ICON_FA_DROPBOX u8\"\\uf16b\"\n#define ICON_FA_DRUPAL u8\"\\uf1a9\"\n#define ICON_FA_DYALOG u8\"\\uf399\"\n#define ICON_FA_EARLYBIRDS u8\"\\uf39a\"\n#define ICON_FA_EBAY u8\"\\uf4f4\"\n#define ICON_FA_EDGE u8\"\\uf282\"\n#define ICON_FA_EDGE_LEGACY u8\"\\uf978\"\n#define ICON_FA_ELEMENTOR u8\"\\uf430\"\n#define ICON_FA_ELLO u8\"\\uf5f1\"\n#define ICON_FA_EMBER u8\"\\uf423\"\n#define ICON_FA_EMPIRE u8\"\\uf1d1\"\n#define ICON_FA_ENVIRA u8\"\\uf299\"\n#define ICON_FA_ERLANG u8\"\\uf39d\"\n#define ICON_FA_ETHEREUM u8\"\\uf42e\"\n#define ICON_FA_ETSY u8\"\\uf2d7\"\n#define ICON_FA_EVERNOTE u8\"\\uf839\"\n#define ICON_FA_EXPEDITEDSSL u8\"\\uf23e\"\n#define ICON_FA_FACEBOOK u8\"\\uf09a\"\n#define ICON_FA_FACEBOOK_F u8\"\\uf39e\"\n#define ICON_FA_FACEBOOK_MESSENGER u8\"\\uf39f\"\n#define ICON_FA_FACEBOOK_SQUARE u8\"\\uf082\"\n#define ICON_FA_FANTASY_FLIGHT_GAMES u8\"\\uf6dc\"\n#define ICON_FA_FEDEX u8\"\\uf797\"\n#define ICON_FA_FEDORA u8\"\\uf798\"\n#define ICON_FA_FIGMA u8\"\\uf799\"\n#define ICON_FA_FIREFOX u8\"\\uf269\"\n#define ICON_FA_FIREFOX_BROWSER u8\"\\uf907\"\n#define ICON_FA_FIRST_ORDER u8\"\\uf2b0\"\n#define ICON_FA_FIRST_ORDER_ALT u8\"\\uf50a\"\n#define ICON_FA_FIRSTDRAFT u8\"\\uf3a1\"\n#define ICON_FA_FLICKR u8\"\\uf16e\"\n#define ICON_FA_FLIPBOARD u8\"\\uf44d\"\n#define ICON_FA_FLY u8\"\\uf417\"\n#define ICON_FA_FONT_AWESOME u8\"\\uf2b4\"\n#define ICON_FA_FONT_AWESOME_ALT u8\"\\uf35c\"\n#define ICON_FA_FONT_AWESOME_FLAG u8\"\\uf425\"\n#define ICON_FA_FONT_AWESOME_LOGO_FULL u8\"\\uf4e6\"\n#define ICON_FA_FONTICONS u8\"\\uf280\"\n#define ICON_FA_FONTICONS_FI u8\"\\uf3a2\"\n#define ICON_FA_FORT_AWESOME u8\"\\uf286\"\n#define ICON_FA_FORT_AWESOME_ALT u8\"\\uf3a3\"\n#define ICON_FA_FORUMBEE u8\"\\uf211\"\n#define ICON_FA_FOURSQUARE u8\"\\uf180\"\n#define ICON_FA_FREE_CODE_CAMP u8\"\\uf2c5\"\n#define ICON_FA_FREEBSD u8\"\\uf3a4\"\n#define ICON_FA_FULCRUM u8\"\\uf50b\"\n#define ICON_FA_GALACTIC_REPUBLIC u8\"\\uf50c\"\n#define ICON_FA_GALACTIC_SENATE u8\"\\uf50d\"\n#define ICON_FA_GET_POCKET u8\"\\uf265\"\n#define ICON_FA_GG u8\"\\uf260\"\n#define ICON_FA_GG_CIRCLE u8\"\\uf261\"\n#define ICON_FA_GIT u8\"\\uf1d3\"\n#define ICON_FA_GIT_ALT u8\"\\uf841\"\n#define ICON_FA_GIT_SQUARE u8\"\\uf1d2\"\n#define ICON_FA_GITHUB u8\"\\uf09b\"\n#define ICON_FA_GITHUB_ALT u8\"\\uf113\"\n#define ICON_FA_GITHUB_SQUARE u8\"\\uf092\"\n#define ICON_FA_GITKRAKEN u8\"\\uf3a6\"\n#define ICON_FA_GITLAB u8\"\\uf296\"\n#define ICON_FA_GITTER u8\"\\uf426\"\n#define ICON_FA_GLIDE u8\"\\uf2a5\"\n#define ICON_FA_GLIDE_G u8\"\\uf2a6\"\n#define ICON_FA_GOFORE u8\"\\uf3a7\"\n#define ICON_FA_GOODREADS u8\"\\uf3a8\"\n#define ICON_FA_GOODREADS_G u8\"\\uf3a9\"\n#define ICON_FA_GOOGLE u8\"\\uf1a0\"\n#define ICON_FA_GOOGLE_DRIVE u8\"\\uf3aa\"\n#define ICON_FA_GOOGLE_PAY u8\"\\uf979\"\n#define ICON_FA_GOOGLE_PLAY u8\"\\uf3ab\"\n#define ICON_FA_GOOGLE_PLUS u8\"\\uf2b3\"\n#define ICON_FA_GOOGLE_PLUS_G u8\"\\uf0d5\"\n#define ICON_FA_GOOGLE_PLUS_SQUARE u8\"\\uf0d4\"\n#define ICON_FA_GOOGLE_WALLET u8\"\\uf1ee\"\n#define ICON_FA_GRATIPAY u8\"\\uf184\"\n#define ICON_FA_GRAV u8\"\\uf2d6\"\n#define ICON_FA_GRIPFIRE u8\"\\uf3ac\"\n#define ICON_FA_GRUNT u8\"\\uf3ad\"\n#define ICON_FA_GULP u8\"\\uf3ae\"\n#define ICON_FA_HACKER_NEWS u8\"\\uf1d4\"\n#define ICON_FA_HACKER_NEWS_SQUARE u8\"\\uf3af\"\n#define ICON_FA_HACKERRANK u8\"\\uf5f7\"\n#define ICON_FA_HIPS u8\"\\uf452\"\n#define ICON_FA_HIRE_A_HELPER u8\"\\uf3b0\"\n#define ICON_FA_HOOLI u8\"\\uf427\"\n#define ICON_FA_HORNBILL u8\"\\uf592\"\n#define ICON_FA_HOTJAR u8\"\\uf3b1\"\n#define ICON_FA_HOUZZ u8\"\\uf27c\"\n#define ICON_FA_HTML5 u8\"\\uf13b\"\n#define ICON_FA_HUBSPOT u8\"\\uf3b2\"\n#define ICON_FA_IDEAL u8\"\\uf913\"\n#define ICON_FA_IMDB u8\"\\uf2d8\"\n#define ICON_FA_INSTAGRAM u8\"\\uf16d\"\n#define ICON_FA_INSTAGRAM_SQUARE u8\"\\uf955\"\n#define ICON_FA_INTERCOM u8\"\\uf7af\"\n#define ICON_FA_INTERNET_EXPLORER u8\"\\uf26b\"\n#define ICON_FA_INVISION u8\"\\uf7b0\"\n#define ICON_FA_IOXHOST u8\"\\uf208\"\n#define ICON_FA_ITCH_IO u8\"\\uf83a\"\n#define ICON_FA_ITUNES u8\"\\uf3b4\"\n#define ICON_FA_ITUNES_NOTE u8\"\\uf3b5\"\n#define ICON_FA_JAVA u8\"\\uf4e4\"\n#define ICON_FA_JEDI_ORDER u8\"\\uf50e\"\n#define ICON_FA_JENKINS u8\"\\uf3b6\"\n#define ICON_FA_JIRA u8\"\\uf7b1\"\n#define ICON_FA_JOGET u8\"\\uf3b7\"\n#define ICON_FA_JOOMLA u8\"\\uf1aa\"\n#define ICON_FA_JS u8\"\\uf3b8\"\n#define ICON_FA_JS_SQUARE u8\"\\uf3b9\"\n#define ICON_FA_JSFIDDLE u8\"\\uf1cc\"\n#define ICON_FA_KAGGLE u8\"\\uf5fa\"\n#define ICON_FA_KEYBASE u8\"\\uf4f5\"\n#define ICON_FA_KEYCDN u8\"\\uf3ba\"\n#define ICON_FA_KICKSTARTER u8\"\\uf3bb\"\n#define ICON_FA_KICKSTARTER_K u8\"\\uf3bc\"\n#define ICON_FA_KORVUE u8\"\\uf42f\"\n#define ICON_FA_LARAVEL u8\"\\uf3bd\"\n#define ICON_FA_LASTFM u8\"\\uf202\"\n#define ICON_FA_LASTFM_SQUARE u8\"\\uf203\"\n#define ICON_FA_LEANPUB u8\"\\uf212\"\n#define ICON_FA_LESS u8\"\\uf41d\"\n#define ICON_FA_LINE u8\"\\uf3c0\"\n#define ICON_FA_LINKEDIN u8\"\\uf08c\"\n#define ICON_FA_LINKEDIN_IN u8\"\\uf0e1\"\n#define ICON_FA_LINODE u8\"\\uf2b8\"\n#define ICON_FA_LINUX u8\"\\uf17c\"\n#define ICON_FA_LYFT u8\"\\uf3c3\"\n#define ICON_FA_MAGENTO u8\"\\uf3c4\"\n#define ICON_FA_MAILCHIMP u8\"\\uf59e\"\n#define ICON_FA_MANDALORIAN u8\"\\uf50f\"\n#define ICON_FA_MARKDOWN u8\"\\uf60f\"\n#define ICON_FA_MASTODON u8\"\\uf4f6\"\n#define ICON_FA_MAXCDN u8\"\\uf136\"\n#define ICON_FA_MDB u8\"\\uf8ca\"\n#define ICON_FA_MEDAPPS u8\"\\uf3c6\"\n#define ICON_FA_MEDIUM u8\"\\uf23a\"\n#define ICON_FA_MEDIUM_M u8\"\\uf3c7\"\n#define ICON_FA_MEDRT u8\"\\uf3c8\"\n#define ICON_FA_MEETUP u8\"\\uf2e0\"\n#define ICON_FA_MEGAPORT u8\"\\uf5a3\"\n#define ICON_FA_MENDELEY u8\"\\uf7b3\"\n#define ICON_FA_MICROBLOG u8\"\\uf91a\"\n#define ICON_FA_MICROSOFT u8\"\\uf3ca\"\n#define ICON_FA_MIX u8\"\\uf3cb\"\n#define ICON_FA_MIXCLOUD u8\"\\uf289\"\n#define ICON_FA_MIXER u8\"\\uf956\"\n#define ICON_FA_MIZUNI u8\"\\uf3cc\"\n#define ICON_FA_MODX u8\"\\uf285\"\n#define ICON_FA_MONERO u8\"\\uf3d0\"\n#define ICON_FA_NAPSTER u8\"\\uf3d2\"\n#define ICON_FA_NEOS u8\"\\uf612\"\n#define ICON_FA_NIMBLR u8\"\\uf5a8\"\n#define ICON_FA_NODE u8\"\\uf419\"\n#define ICON_FA_NODE_JS u8\"\\uf3d3\"\n#define ICON_FA_NPM u8\"\\uf3d4\"\n#define ICON_FA_NS8 u8\"\\uf3d5\"\n#define ICON_FA_NUTRITIONIX u8\"\\uf3d6\"\n#define ICON_FA_ODNOKLASSNIKI u8\"\\uf263\"\n#define ICON_FA_ODNOKLASSNIKI_SQUARE u8\"\\uf264\"\n#define ICON_FA_OLD_REPUBLIC u8\"\\uf510\"\n#define ICON_FA_OPENCART u8\"\\uf23d\"\n#define ICON_FA_OPENID u8\"\\uf19b\"\n#define ICON_FA_OPERA u8\"\\uf26a\"\n#define ICON_FA_OPTIN_MONSTER u8\"\\uf23c\"\n#define ICON_FA_ORCID u8\"\\uf8d2\"\n#define ICON_FA_OSI u8\"\\uf41a\"\n#define ICON_FA_PAGE4 u8\"\\uf3d7\"\n#define ICON_FA_PAGELINES u8\"\\uf18c\"\n#define ICON_FA_PALFED u8\"\\uf3d8\"\n#define ICON_FA_PATREON u8\"\\uf3d9\"\n#define ICON_FA_PAYPAL u8\"\\uf1ed\"\n#define ICON_FA_PENNY_ARCADE u8\"\\uf704\"\n#define ICON_FA_PERISCOPE u8\"\\uf3da\"\n#define ICON_FA_PHABRICATOR u8\"\\uf3db\"\n#define ICON_FA_PHOENIX_FRAMEWORK u8\"\\uf3dc\"\n#define ICON_FA_PHOENIX_SQUADRON u8\"\\uf511\"\n#define ICON_FA_PHP u8\"\\uf457\"\n#define ICON_FA_PIED_PIPER u8\"\\uf2ae\"\n#define ICON_FA_PIED_PIPER_ALT u8\"\\uf1a8\"\n#define ICON_FA_PIED_PIPER_HAT u8\"\\uf4e5\"\n#define ICON_FA_PIED_PIPER_PP u8\"\\uf1a7\"\n#define ICON_FA_PIED_PIPER_SQUARE u8\"\\uf91e\"\n#define ICON_FA_PINTEREST u8\"\\uf0d2\"\n#define ICON_FA_PINTEREST_P u8\"\\uf231\"\n#define ICON_FA_PINTEREST_SQUARE u8\"\\uf0d3\"\n#define ICON_FA_PLAYSTATION u8\"\\uf3df\"\n#define ICON_FA_PRODUCT_HUNT u8\"\\uf288\"\n#define ICON_FA_PUSHED u8\"\\uf3e1\"\n#define ICON_FA_PYTHON u8\"\\uf3e2\"\n#define ICON_FA_QQ u8\"\\uf1d6\"\n#define ICON_FA_QUINSCAPE u8\"\\uf459\"\n#define ICON_FA_QUORA u8\"\\uf2c4\"\n#define ICON_FA_R_PROJECT u8\"\\uf4f7\"\n#define ICON_FA_RASPBERRY_PI u8\"\\uf7bb\"\n#define ICON_FA_RAVELRY u8\"\\uf2d9\"\n#define ICON_FA_REACT u8\"\\uf41b\"\n#define ICON_FA_REACTEUROPE u8\"\\uf75d\"\n#define ICON_FA_README u8\"\\uf4d5\"\n#define ICON_FA_REBEL u8\"\\uf1d0\"\n#define ICON_FA_RED_RIVER u8\"\\uf3e3\"\n#define ICON_FA_REDDIT u8\"\\uf1a1\"\n#define ICON_FA_REDDIT_ALIEN u8\"\\uf281\"\n#define ICON_FA_REDDIT_SQUARE u8\"\\uf1a2\"\n#define ICON_FA_REDHAT u8\"\\uf7bc\"\n#define ICON_FA_RENREN u8\"\\uf18b\"\n#define ICON_FA_REPLYD u8\"\\uf3e6\"\n#define ICON_FA_RESEARCHGATE u8\"\\uf4f8\"\n#define ICON_FA_RESOLVING u8\"\\uf3e7\"\n#define ICON_FA_REV u8\"\\uf5b2\"\n#define ICON_FA_ROCKETCHAT u8\"\\uf3e8\"\n#define ICON_FA_ROCKRMS u8\"\\uf3e9\"\n#define ICON_FA_RUST u8\"\\uf97a\"\n#define ICON_FA_SAFARI u8\"\\uf267\"\n#define ICON_FA_SALESFORCE u8\"\\uf83b\"\n#define ICON_FA_SASS u8\"\\uf41e\"\n#define ICON_FA_SCHLIX u8\"\\uf3ea\"\n#define ICON_FA_SCRIBD u8\"\\uf28a\"\n#define ICON_FA_SEARCHENGIN u8\"\\uf3eb\"\n#define ICON_FA_SELLCAST u8\"\\uf2da\"\n#define ICON_FA_SELLSY u8\"\\uf213\"\n#define ICON_FA_SERVICESTACK u8\"\\uf3ec\"\n#define ICON_FA_SHIRTSINBULK u8\"\\uf214\"\n#define ICON_FA_SHOPIFY u8\"\\uf957\"\n#define ICON_FA_SHOPWARE u8\"\\uf5b5\"\n#define ICON_FA_SIMPLYBUILT u8\"\\uf215\"\n#define ICON_FA_SISTRIX u8\"\\uf3ee\"\n#define ICON_FA_SITH u8\"\\uf512\"\n#define ICON_FA_SKETCH u8\"\\uf7c6\"\n#define ICON_FA_SKYATLAS u8\"\\uf216\"\n#define ICON_FA_SKYPE u8\"\\uf17e\"\n#define ICON_FA_SLACK u8\"\\uf198\"\n#define ICON_FA_SLACK_HASH u8\"\\uf3ef\"\n#define ICON_FA_SLIDESHARE u8\"\\uf1e7\"\n#define ICON_FA_SNAPCHAT u8\"\\uf2ab\"\n#define ICON_FA_SNAPCHAT_GHOST u8\"\\uf2ac\"\n#define ICON_FA_SNAPCHAT_SQUARE u8\"\\uf2ad\"\n#define ICON_FA_SOUNDCLOUD u8\"\\uf1be\"\n#define ICON_FA_SOURCETREE u8\"\\uf7d3\"\n#define ICON_FA_SPEAKAP u8\"\\uf3f3\"\n#define ICON_FA_SPEAKER_DECK u8\"\\uf83c\"\n#define ICON_FA_SPOTIFY u8\"\\uf1bc\"\n#define ICON_FA_SQUARESPACE u8\"\\uf5be\"\n#define ICON_FA_STACK_EXCHANGE u8\"\\uf18d\"\n#define ICON_FA_STACK_OVERFLOW u8\"\\uf16c\"\n#define ICON_FA_STACKPATH u8\"\\uf842\"\n#define ICON_FA_STAYLINKED u8\"\\uf3f5\"\n#define ICON_FA_STEAM u8\"\\uf1b6\"\n#define ICON_FA_STEAM_SQUARE u8\"\\uf1b7\"\n#define ICON_FA_STEAM_SYMBOL u8\"\\uf3f6\"\n#define ICON_FA_STICKER_MULE u8\"\\uf3f7\"\n#define ICON_FA_STRAVA u8\"\\uf428\"\n#define ICON_FA_STRIPE u8\"\\uf429\"\n#define ICON_FA_STRIPE_S u8\"\\uf42a\"\n#define ICON_FA_STUDIOVINARI u8\"\\uf3f8\"\n#define ICON_FA_STUMBLEUPON u8\"\\uf1a4\"\n#define ICON_FA_STUMBLEUPON_CIRCLE u8\"\\uf1a3\"\n#define ICON_FA_SUPERPOWERS u8\"\\uf2dd\"\n#define ICON_FA_SUPPLE u8\"\\uf3f9\"\n#define ICON_FA_SUSE u8\"\\uf7d6\"\n#define ICON_FA_SWIFT u8\"\\uf8e1\"\n#define ICON_FA_SYMFONY u8\"\\uf83d\"\n#define ICON_FA_TEAMSPEAK u8\"\\uf4f9\"\n#define ICON_FA_TELEGRAM u8\"\\uf2c6\"\n#define ICON_FA_TELEGRAM_PLANE u8\"\\uf3fe\"\n#define ICON_FA_TENCENT_WEIBO u8\"\\uf1d5\"\n#define ICON_FA_THE_RED_YETI u8\"\\uf69d\"\n#define ICON_FA_THEMECO u8\"\\uf5c6\"\n#define ICON_FA_THEMEISLE u8\"\\uf2b2\"\n#define ICON_FA_THINK_PEAKS u8\"\\uf731\"\n#define ICON_FA_TIKTOK u8\"\\uf97b\"\n#define ICON_FA_TRADE_FEDERATION u8\"\\uf513\"\n#define ICON_FA_TRELLO u8\"\\uf181\"\n#define ICON_FA_TRIPADVISOR u8\"\\uf262\"\n#define ICON_FA_TUMBLR u8\"\\uf173\"\n#define ICON_FA_TUMBLR_SQUARE u8\"\\uf174\"\n#define ICON_FA_TWITCH u8\"\\uf1e8\"\n#define ICON_FA_TWITTER u8\"\\uf099\"\n#define ICON_FA_TWITTER_SQUARE u8\"\\uf081\"\n#define ICON_FA_TYPO3 u8\"\\uf42b\"\n#define ICON_FA_UBER u8\"\\uf402\"\n#define ICON_FA_UBUNTU u8\"\\uf7df\"\n#define ICON_FA_UIKIT u8\"\\uf403\"\n#define ICON_FA_UMBRACO u8\"\\uf8e8\"\n#define ICON_FA_UNIREGISTRY u8\"\\uf404\"\n#define ICON_FA_UNITY u8\"\\uf949\"\n#define ICON_FA_UNSPLASH u8\"\\uf97c\"\n#define ICON_FA_UNTAPPD u8\"\\uf405\"\n#define ICON_FA_UPS u8\"\\uf7e0\"\n#define ICON_FA_USB u8\"\\uf287\"\n#define ICON_FA_USPS u8\"\\uf7e1\"\n#define ICON_FA_USSUNNAH u8\"\\uf407\"\n#define ICON_FA_VAADIN u8\"\\uf408\"\n#define ICON_FA_VIACOIN u8\"\\uf237\"\n#define ICON_FA_VIADEO u8\"\\uf2a9\"\n#define ICON_FA_VIADEO_SQUARE u8\"\\uf2aa\"\n#define ICON_FA_VIBER u8\"\\uf409\"\n#define ICON_FA_VIMEO u8\"\\uf40a\"\n#define ICON_FA_VIMEO_SQUARE u8\"\\uf194\"\n#define ICON_FA_VIMEO_V u8\"\\uf27d\"\n#define ICON_FA_VINE u8\"\\uf1ca\"\n#define ICON_FA_VK u8\"\\uf189\"\n#define ICON_FA_VNV u8\"\\uf40b\"\n#define ICON_FA_VUEJS u8\"\\uf41f\"\n#define ICON_FA_WAZE u8\"\\uf83f\"\n#define ICON_FA_WEEBLY u8\"\\uf5cc\"\n#define ICON_FA_WEIBO u8\"\\uf18a\"\n#define ICON_FA_WEIXIN u8\"\\uf1d7\"\n#define ICON_FA_WHATSAPP u8\"\\uf232\"\n#define ICON_FA_WHATSAPP_SQUARE u8\"\\uf40c\"\n#define ICON_FA_WHMCS u8\"\\uf40d\"\n#define ICON_FA_WIKIPEDIA_W u8\"\\uf266\"\n#define ICON_FA_WINDOWS u8\"\\uf17a\"\n#define ICON_FA_WIX u8\"\\uf5cf\"\n#define ICON_FA_WIZARDS_OF_THE_COAST u8\"\\uf730\"\n#define ICON_FA_WOLF_PACK_BATTALION u8\"\\uf514\"\n#define ICON_FA_WORDPRESS u8\"\\uf19a\"\n#define ICON_FA_WORDPRESS_SIMPLE u8\"\\uf411\"\n#define ICON_FA_WPBEGINNER u8\"\\uf297\"\n#define ICON_FA_WPEXPLORER u8\"\\uf2de\"\n#define ICON_FA_WPFORMS u8\"\\uf298\"\n#define ICON_FA_WPRESSR u8\"\\uf3e4\"\n#define ICON_FA_XBOX u8\"\\uf412\"\n#define ICON_FA_XING u8\"\\uf168\"\n#define ICON_FA_XING_SQUARE u8\"\\uf169\"\n#define ICON_FA_Y_COMBINATOR u8\"\\uf23b\"\n#define ICON_FA_YAHOO u8\"\\uf19e\"\n#define ICON_FA_YAMMER u8\"\\uf840\"\n#define ICON_FA_YANDEX u8\"\\uf413\"\n#define ICON_FA_YANDEX_INTERNATIONAL u8\"\\uf414\"\n#define ICON_FA_YARN u8\"\\uf7e3\"\n#define ICON_FA_YELP u8\"\\uf1e9\"\n#define ICON_FA_YOAST u8\"\\uf2b1\"\n#define ICON_FA_YOUTUBE u8\"\\uf167\"\n#define ICON_FA_YOUTUBE_SQUARE u8\"\\uf431\"\n#define ICON_FA_ZHIHU u8\"\\uf63f\"\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/IconFontCppHeaders/IconsFontaudio.h",
    "content": "// Generated by https://github.com/juliettef/IconFontCppHeaders script GenerateIconFontCppHeaders.py for language C++11\n// from https://raw.githubusercontent.com/fefanto/fontaudio/master/font/fontaudio.css\n// for use with https://github.com/fefanto/fontaudio/raw/master/font/fontaudio.ttf\n#pragma once\n\n#define FONT_ICON_FILE_NAME_FAD \"fontaudio.ttf\"\n\n#define ICON_MIN_FAD 0xf101\n#define ICON_MAX_FAD 0xf19b\n#define ICON_FAD_ADR u8\"\\uf101\"\n#define ICON_FAD_ADSR u8\"\\uf102\"\n#define ICON_FAD_AHDSR u8\"\\uf103\"\n#define ICON_FAD_AR u8\"\\uf104\"\n#define ICON_FAD_ARMRECORDING u8\"\\uf105\"\n#define ICON_FAD_ARPCHORD u8\"\\uf106\"\n#define ICON_FAD_ARPDOWN u8\"\\uf107\"\n#define ICON_FAD_ARPDOWNANDUP u8\"\\uf108\"\n#define ICON_FAD_ARPDOWNUP u8\"\\uf109\"\n#define ICON_FAD_ARPPLAYORDER u8\"\\uf10a\"\n#define ICON_FAD_ARPRANDOM u8\"\\uf10b\"\n#define ICON_FAD_ARPUP u8\"\\uf10c\"\n#define ICON_FAD_ARPUPANDOWN u8\"\\uf10d\"\n#define ICON_FAD_ARPUPDOWN u8\"\\uf10e\"\n#define ICON_FAD_ARROWS_HORZ u8\"\\uf10f\"\n#define ICON_FAD_ARROWS_VERT u8\"\\uf110\"\n#define ICON_FAD_AUTOMATION_2P u8\"\\uf111\"\n#define ICON_FAD_AUTOMATION_3P u8\"\\uf112\"\n#define ICON_FAD_AUTOMATION_4P u8\"\\uf113\"\n#define ICON_FAD_BACKWARD u8\"\\uf114\"\n#define ICON_FAD_BLUETOOTH u8\"\\uf115\"\n#define ICON_FAD_CARET_DOWN u8\"\\uf116\"\n#define ICON_FAD_CARET_LEFT u8\"\\uf117\"\n#define ICON_FAD_CARET_RIGHT u8\"\\uf118\"\n#define ICON_FAD_CARET_UP u8\"\\uf119\"\n#define ICON_FAD_CLOSE u8\"\\uf11a\"\n#define ICON_FAD_COPY u8\"\\uf11b\"\n#define ICON_FAD_CPU u8\"\\uf11c\"\n#define ICON_FAD_CUTTER u8\"\\uf11d\"\n#define ICON_FAD_DIGITAL_COLON u8\"\\uf11e\"\n#define ICON_FAD_DIGITAL_DOT u8\"\\uf11f\"\n#define ICON_FAD_DIGITAL0 u8\"\\uf120\"\n#define ICON_FAD_DIGITAL1 u8\"\\uf121\"\n#define ICON_FAD_DIGITAL2 u8\"\\uf122\"\n#define ICON_FAD_DIGITAL3 u8\"\\uf123\"\n#define ICON_FAD_DIGITAL4 u8\"\\uf124\"\n#define ICON_FAD_DIGITAL5 u8\"\\uf125\"\n#define ICON_FAD_DIGITAL6 u8\"\\uf126\"\n#define ICON_FAD_DIGITAL7 u8\"\\uf127\"\n#define ICON_FAD_DIGITAL8 u8\"\\uf128\"\n#define ICON_FAD_DIGITAL9 u8\"\\uf129\"\n#define ICON_FAD_DISKIO u8\"\\uf12a\"\n#define ICON_FAD_DRUMPAD u8\"\\uf12b\"\n#define ICON_FAD_DUPLICATE u8\"\\uf12c\"\n#define ICON_FAD_ERASER u8\"\\uf12d\"\n#define ICON_FAD_FFWD u8\"\\uf12e\"\n#define ICON_FAD_FILTER_BANDPASS u8\"\\uf12f\"\n#define ICON_FAD_FILTER_BELL u8\"\\uf130\"\n#define ICON_FAD_FILTER_BYPASS u8\"\\uf131\"\n#define ICON_FAD_FILTER_HIGHPASS u8\"\\uf132\"\n#define ICON_FAD_FILTER_LOWPASS u8\"\\uf133\"\n#define ICON_FAD_FILTER_NOTCH u8\"\\uf134\"\n#define ICON_FAD_FILTER_REZ_HIGHPASS u8\"\\uf135\"\n#define ICON_FAD_FILTER_REZ_LOWPASS u8\"\\uf136\"\n#define ICON_FAD_FILTER_SHELVING_HI u8\"\\uf137\"\n#define ICON_FAD_FILTER_SHELVING_LO u8\"\\uf138\"\n#define ICON_FAD_FOLDBACK u8\"\\uf139\"\n#define ICON_FAD_FORWARD u8\"\\uf13a\"\n#define ICON_FAD_H_EXPAND u8\"\\uf13b\"\n#define ICON_FAD_HARDCLIP u8\"\\uf13c\"\n#define ICON_FAD_HARDCLIPCURVE u8\"\\uf13d\"\n#define ICON_FAD_HEADPHONES u8\"\\uf13e\"\n#define ICON_FAD_KEYBOARD u8\"\\uf13f\"\n#define ICON_FAD_LOCK u8\"\\uf140\"\n#define ICON_FAD_LOGO_AAX u8\"\\uf141\"\n#define ICON_FAD_LOGO_ABLETONLINK u8\"\\uf142\"\n#define ICON_FAD_LOGO_AU u8\"\\uf143\"\n#define ICON_FAD_LOGO_AUDACITY u8\"\\uf144\"\n#define ICON_FAD_LOGO_AUDIOBUS u8\"\\uf145\"\n#define ICON_FAD_LOGO_CUBASE u8\"\\uf146\"\n#define ICON_FAD_LOGO_FL u8\"\\uf147\"\n#define ICON_FAD_LOGO_JUCE u8\"\\uf148\"\n#define ICON_FAD_LOGO_LADSPA u8\"\\uf149\"\n#define ICON_FAD_LOGO_LIVE u8\"\\uf14a\"\n#define ICON_FAD_LOGO_LV2 u8\"\\uf14b\"\n#define ICON_FAD_LOGO_PROTOOLS u8\"\\uf14c\"\n#define ICON_FAD_LOGO_RACKEXT u8\"\\uf14d\"\n#define ICON_FAD_LOGO_REAPER u8\"\\uf14e\"\n#define ICON_FAD_LOGO_REASON u8\"\\uf14f\"\n#define ICON_FAD_LOGO_REWIRE u8\"\\uf150\"\n#define ICON_FAD_LOGO_STUDIOONE u8\"\\uf151\"\n#define ICON_FAD_LOGO_TRACKTION u8\"\\uf152\"\n#define ICON_FAD_LOGO_VST u8\"\\uf153\"\n#define ICON_FAD_LOGO_WAVEFORM u8\"\\uf154\"\n#define ICON_FAD_LOOP u8\"\\uf155\"\n#define ICON_FAD_METRONOME u8\"\\uf156\"\n#define ICON_FAD_MICROPHONE u8\"\\uf157\"\n#define ICON_FAD_MIDIPLUG u8\"\\uf158\"\n#define ICON_FAD_MODRANDOM u8\"\\uf159\"\n#define ICON_FAD_MODSAWDOWN u8\"\\uf15a\"\n#define ICON_FAD_MODSAWUP u8\"\\uf15b\"\n#define ICON_FAD_MODSH u8\"\\uf15c\"\n#define ICON_FAD_MODSINE u8\"\\uf15d\"\n#define ICON_FAD_MODSQUARE u8\"\\uf15e\"\n#define ICON_FAD_MODTRI u8\"\\uf15f\"\n#define ICON_FAD_MODULARPLUG u8\"\\uf160\"\n#define ICON_FAD_MONO u8\"\\uf161\"\n#define ICON_FAD_MUTE u8\"\\uf162\"\n#define ICON_FAD_NEXT u8\"\\uf163\"\n#define ICON_FAD_OPEN u8\"\\uf164\"\n#define ICON_FAD_PASTE u8\"\\uf165\"\n#define ICON_FAD_PAUSE u8\"\\uf166\"\n#define ICON_FAD_PEN u8\"\\uf167\"\n#define ICON_FAD_PHASE u8\"\\uf168\"\n#define ICON_FAD_PLAY u8\"\\uf169\"\n#define ICON_FAD_POINTER u8\"\\uf16a\"\n#define ICON_FAD_POWERSWITCH u8\"\\uf16b\"\n#define ICON_FAD_PRESET_A u8\"\\uf16c\"\n#define ICON_FAD_PRESET_AB u8\"\\uf16d\"\n#define ICON_FAD_PRESET_B u8\"\\uf16e\"\n#define ICON_FAD_PRESET_BA u8\"\\uf16f\"\n#define ICON_FAD_PREV u8\"\\uf170\"\n#define ICON_FAD_PUNCH_IN u8\"\\uf171\"\n#define ICON_FAD_PUNCH_OUT u8\"\\uf172\"\n#define ICON_FAD_RAM u8\"\\uf173\"\n#define ICON_FAD_RANDOM_1DICE u8\"\\uf174\"\n#define ICON_FAD_RANDOM_2DICE u8\"\\uf175\"\n#define ICON_FAD_RECORD u8\"\\uf176\"\n#define ICON_FAD_REDO u8\"\\uf177\"\n#define ICON_FAD_REPEAT_ONE u8\"\\uf178\"\n#define ICON_FAD_REPEAT u8\"\\uf179\"\n#define ICON_FAD_REW u8\"\\uf17a\"\n#define ICON_FAD_ROUNDSWITCH_OFF u8\"\\uf17b\"\n#define ICON_FAD_ROUNDSWITCH_ON u8\"\\uf17c\"\n#define ICON_FAD_SAVE u8\"\\uf17d\"\n#define ICON_FAD_SAVEAS u8\"\\uf17e\"\n#define ICON_FAD_SCISSORS u8\"\\uf17f\"\n#define ICON_FAD_SHUFFLE u8\"\\uf180\"\n#define ICON_FAD_SLIDER_ROUND_1 u8\"\\uf181\"\n#define ICON_FAD_SLIDER_ROUND_2 u8\"\\uf182\"\n#define ICON_FAD_SLIDER_ROUND_3 u8\"\\uf183\"\n#define ICON_FAD_SLIDERHANDLE_1 u8\"\\uf184\"\n#define ICON_FAD_SLIDERHANDLE_2 u8\"\\uf185\"\n#define ICON_FAD_SOFTCLIP u8\"\\uf186\"\n#define ICON_FAD_SOFTCLIPCURVE u8\"\\uf187\"\n#define ICON_FAD_SOLO u8\"\\uf188\"\n#define ICON_FAD_SPEAKER u8\"\\uf189\"\n#define ICON_FAD_SQUARESWITCH_OFF u8\"\\uf18a\"\n#define ICON_FAD_SQUARESWITCH_ON u8\"\\uf18b\"\n#define ICON_FAD_STEREO u8\"\\uf18c\"\n#define ICON_FAD_STOP u8\"\\uf18d\"\n#define ICON_FAD_THUNDERBOLT u8\"\\uf18e\"\n#define ICON_FAD_TIMESELECT u8\"\\uf18f\"\n#define ICON_FAD_UNDO u8\"\\uf190\"\n#define ICON_FAD_UNLOCK u8\"\\uf191\"\n#define ICON_FAD_USB u8\"\\uf192\"\n#define ICON_FAD_V_EXPAND u8\"\\uf193\"\n#define ICON_FAD_VROUNDSWITCH_OFF u8\"\\uf194\"\n#define ICON_FAD_VROUNDSWITCH_ON u8\"\\uf195\"\n#define ICON_FAD_VSQUARESWITCH_OFF u8\"\\uf196\"\n#define ICON_FAD_VSQUARESWITCH_ON u8\"\\uf197\"\n#define ICON_FAD_WAVEFORM u8\"\\uf198\"\n#define ICON_FAD_XLRPLUG u8\"\\uf199\"\n#define ICON_FAD_ZOOMIN u8\"\\uf19a\"\n#define ICON_FAD_ZOOMOUT u8\"\\uf19b\"\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/IconFontCppHeaders/IconsKenney.h",
    "content": "// Generated by https://github.com/juliettef/IconFontCppHeaders script GenerateIconFontCppHeaders.py for language C++11\n// from https://raw.githubusercontent.com/nicodinh/kenney-icon-font/master/css/kenney-icons.css\n// for use with https://github.com/nicodinh/kenney-icon-font/blob/master/fonts/kenney-icon-font.ttf\n#pragma once\n\n#define FONT_ICON_FILE_NAME_KI \"kenney-icon-font.ttf\"\n\n#define ICON_MIN_KI 0xe900\n#define ICON_MAX_KI 0xe9e3\n#define ICON_KI_HOME u8\"\\ue900\"\n#define ICON_KI_ADJUST u8\"\\ue901\"\n#define ICON_KI_WRENCH u8\"\\ue902\"\n#define ICON_KI_COG u8\"\\ue903\"\n#define ICON_KI_OFF u8\"\\ue904\"\n#define ICON_KI_EXPAND u8\"\\ue905\"\n#define ICON_KI_REDUCE u8\"\\ue906\"\n#define ICON_KI_MOVIE u8\"\\ue907\"\n#define ICON_KI_FLAP u8\"\\ue908\"\n#define ICON_KI_SHOPPING_CART u8\"\\ue909\"\n#define ICON_KI_SHOPPING_CASE u8\"\\ue90a\"\n#define ICON_KI_EXTERNAL u8\"\\ue90b\"\n#define ICON_KI_NETWORK u8\"\\ue90c\"\n#define ICON_KI_CHECK u8\"\\ue90d\"\n#define ICON_KI_TIMES u8\"\\ue90e\"\n#define ICON_KI_TIMES_CIRCLE u8\"\\ue90f\"\n#define ICON_KI_PLUS u8\"\\ue910\"\n#define ICON_KI_PLUS_CIRCLE u8\"\\ue911\"\n#define ICON_KI_MINUS u8\"\\ue912\"\n#define ICON_KI_MINUS_CIRCLE u8\"\\ue913\"\n#define ICON_KI_INFO u8\"\\ue914\"\n#define ICON_KI_INFO_CIRCLE u8\"\\ue915\"\n#define ICON_KI_QUESTION u8\"\\ue916\"\n#define ICON_KI_QUESTION_CIRCLE u8\"\\ue917\"\n#define ICON_KI_EXLAMATION u8\"\\ue918\"\n#define ICON_KI_EXCLAMATION_CIRCLE u8\"\\ue919\"\n#define ICON_KI_EXCLAMATION_TRIANGLE u8\"\\ue91a\"\n#define ICON_KI_PAINT_BRUSH u8\"\\ue91b\"\n#define ICON_KI_PENCIL u8\"\\ue91c\"\n#define ICON_KI_CHECKBOX u8\"\\ue91d\"\n#define ICON_KI_CHECKBOX_CHECKED u8\"\\ue91e\"\n#define ICON_KI_RADIO u8\"\\ue91f\"\n#define ICON_KI_RADIO_CHECKED u8\"\\ue920\"\n#define ICON_KI_SORT_VERTICAL u8\"\\ue921\"\n#define ICON_KI_SORT_HORIZONTAL u8\"\\ue922\"\n#define ICON_KI_GRID u8\"\\ue923\"\n#define ICON_KI_LIST u8\"\\ue924\"\n#define ICON_KI_ROWS u8\"\\ue925\"\n#define ICON_KI_CELLS u8\"\\ue926\"\n#define ICON_KI_SIGNAL_LOW u8\"\\ue927\"\n#define ICON_KI_SIGNAL_MEDIUM u8\"\\ue928\"\n#define ICON_KI_SIGNAL_HIGH u8\"\\ue929\"\n#define ICON_KI_TRASH u8\"\\ue92a\"\n#define ICON_KI_TRASH_ALT u8\"\\ue92b\"\n#define ICON_KI_RELOAD_INVERSE u8\"\\ue92c\"\n#define ICON_KI_RELOAD u8\"\\ue92d\"\n#define ICON_KI_TOP u8\"\\ue92e\"\n#define ICON_KI_BOTTOM u8\"\\ue92f\"\n#define ICON_KI_UPLOAD u8\"\\ue930\"\n#define ICON_KI_DOWNLOAD u8\"\\ue931\"\n#define ICON_KI_CLOUD u8\"\\ue932\"\n#define ICON_KI_CLOUD_UPLOAD u8\"\\ue933\"\n#define ICON_KI_CLOUD_DOWNLOAD u8\"\\ue934\"\n#define ICON_KI_SEARCH u8\"\\ue935\"\n#define ICON_KI_SEARCH_PLUS u8\"\\ue936\"\n#define ICON_KI_SEARCH_MINUS u8\"\\ue937\"\n#define ICON_KI_SEARCH_EQUAL u8\"\\ue938\"\n#define ICON_KI_LOCK u8\"\\ue939\"\n#define ICON_KI_UNLOCK u8\"\\ue93a\"\n#define ICON_KI_USER u8\"\\ue93b\"\n#define ICON_KI_USERS u8\"\\ue93c\"\n#define ICON_KI_USERS_ALT u8\"\\ue93d\"\n#define ICON_KI_SIGN_IN u8\"\\ue93e\"\n#define ICON_KI_SIGN_IN_INVERSE u8\"\\ue93f\"\n#define ICON_KI_SIGN_OUT u8\"\\ue940\"\n#define ICON_KI_SIGN_OUT_INVERSE u8\"\\ue941\"\n#define ICON_KI_ARROW_TOP u8\"\\ue942\"\n#define ICON_KI_ARROW_RIGHT u8\"\\ue943\"\n#define ICON_KI_ARROW_BOTTOM u8\"\\ue944\"\n#define ICON_KI_ARROW_LEFT u8\"\\ue945\"\n#define ICON_KI_ARROW_TOP_LEFT u8\"\\ue946\"\n#define ICON_KI_ARROW_TOP_RIGHT u8\"\\ue947\"\n#define ICON_KI_ARROW_BOTTOM_RIGHT u8\"\\ue948\"\n#define ICON_KI_ARROW_BOTTOM_LEFT u8\"\\ue949\"\n#define ICON_KI_CARET_TOP u8\"\\ue94a\"\n#define ICON_KI_CARET_RIGHT u8\"\\ue94b\"\n#define ICON_KI_CARET_BOTTOM u8\"\\ue94c\"\n#define ICON_KI_CARET_LEFT u8\"\\ue94d\"\n#define ICON_KI_NEXT_ALT u8\"\\ue94e\"\n#define ICON_KI_NEXT u8\"\\ue94f\"\n#define ICON_KI_PREVIOUS u8\"\\ue950\"\n#define ICON_KI_PREVIOUS_ALT u8\"\\ue951\"\n#define ICON_KI_FILL u8\"\\ue952\"\n#define ICON_KI_ERASER u8\"\\ue953\"\n#define ICON_KI_SAVE u8\"\\ue954\"\n#define ICON_KI_STEP_BACKWARD u8\"\\ue955\"\n#define ICON_KI_BACKWARD u8\"\\ue956\"\n#define ICON_KI_PAUSE u8\"\\ue957\"\n#define ICON_KI_FORWARD u8\"\\ue958\"\n#define ICON_KI_STEP_FORWARD u8\"\\ue959\"\n#define ICON_KI_STOP u8\"\\ue95a\"\n#define ICON_KI_REC u8\"\\ue95b\"\n#define ICON_KI_CURSOR u8\"\\ue95c\"\n#define ICON_KI_POINTER u8\"\\ue95d\"\n#define ICON_KI_EXIT u8\"\\ue95e\"\n#define ICON_KI_FIGURE u8\"\\ue95f\"\n#define ICON_KI_CAR u8\"\\ue960\"\n#define ICON_KI_COIN u8\"\\ue961\"\n#define ICON_KI_KEY u8\"\\ue962\"\n#define ICON_KI_CUB u8\"\\ue963\"\n#define ICON_KI_DIAMOND u8\"\\ue964\"\n#define ICON_KI_BADGE u8\"\\ue965\"\n#define ICON_KI_BADGE_ALT u8\"\\ue966\"\n#define ICON_KI_PODIUM u8\"\\ue967\"\n#define ICON_KI_PODIUM_ALT u8\"\\ue968\"\n#define ICON_KI_FLAG u8\"\\ue969\"\n#define ICON_KI_FIST u8\"\\ue96a\"\n#define ICON_KI_FIST_CIRCLE u8\"\\ue96b\"\n#define ICON_KI_HEART u8\"\\ue96c\"\n#define ICON_KI_HEART_HALF u8\"\\ue96d\"\n#define ICON_KI_HEART_HALF_O u8\"\\ue96e\"\n#define ICON_KI_HEART_O u8\"\\ue96f\"\n#define ICON_KI_STAR u8\"\\ue970\"\n#define ICON_KI_STAR_HALF u8\"\\ue971\"\n#define ICON_KI_STAR_HALF_O u8\"\\ue972\"\n#define ICON_KI_STAR_O u8\"\\ue973\"\n#define ICON_KI_BUTTON_B u8\"\\ue974\"\n#define ICON_KI_MUSIC_ON u8\"\\ue975\"\n#define ICON_KI_MUSIC_OFF u8\"\\ue976\"\n#define ICON_KI_SOUND_ON u8\"\\ue977\"\n#define ICON_KI_SOUND_OFF u8\"\\ue978\"\n#define ICON_KI_SOUND_OFF_ALT u8\"\\ue979\"\n#define ICON_KI_ROBOT u8\"\\ue97a\"\n#define ICON_KI_COMPUTER u8\"\\ue97b\"\n#define ICON_KI_TABLET u8\"\\ue97c\"\n#define ICON_KI_SMARTPHONE u8\"\\ue97d\"\n#define ICON_KI_DEVICE u8\"\\ue97e\"\n#define ICON_KI_DEVICE_TILT_LEFT u8\"\\ue97f\"\n#define ICON_KI_DEVICE_TILT_RIGHT u8\"\\ue980\"\n#define ICON_KI_GAMEPAD u8\"\\ue981\"\n#define ICON_KI_GAMEPAD_ALT u8\"\\ue982\"\n#define ICON_KI_GAMEPAD_TILT_LEFT u8\"\\ue983\"\n#define ICON_KI_GAMEPAD_TILT_RIGHT u8\"\\ue984\"\n#define ICON_KI_PLAYER_ONE u8\"\\ue985\"\n#define ICON_KI_PLAYER_TWO u8\"\\ue986\"\n#define ICON_KI_PLAYER_THREE u8\"\\ue987\"\n#define ICON_KI_PLAYER_FOUR u8\"\\ue988\"\n#define ICON_KI_JOYSTICK u8\"\\ue989\"\n#define ICON_KI_JOYSTICK_ALT u8\"\\ue98a\"\n#define ICON_KI_JOYSTICK_LEFT u8\"\\ue98b\"\n#define ICON_KI_JOYSTICK_RIGHT u8\"\\ue98c\"\n#define ICON_KI_MOUSE_ALT u8\"\\ue98d\"\n#define ICON_KI_MOUSE u8\"\\ue98e\"\n#define ICON_KI_MOUSE_LEFT_BUTTON u8\"\\ue98f\"\n#define ICON_KI_MOUSE_RIGHT_BUTTON u8\"\\ue990\"\n#define ICON_KI_BUTTON_ONE u8\"\\ue991\"\n#define ICON_KI_BUTTON_TWO u8\"\\ue992\"\n#define ICON_KI_BUTTON_THREE u8\"\\ue993\"\n#define ICON_KI_BUTTON_A u8\"\\ue994\"\n#define ICON_KI_BUTTON_X u8\"\\ue995\"\n#define ICON_KI_BUTON_Y u8\"\\ue996\"\n#define ICON_KI_BUTTON_TIMES u8\"\\ue997\"\n#define ICON_KI_BUTTON_SQUARE u8\"\\ue998\"\n#define ICON_KI_BUTTON_CIRCLE u8\"\\ue999\"\n#define ICON_KI_BUTTON_TRIANGLE u8\"\\ue99a\"\n#define ICON_KI_BUTTON_LEFT u8\"\\ue99b\"\n#define ICON_KI_BUTTON_L u8\"\\ue99c\"\n#define ICON_KI_BUTTON_L1 u8\"\\ue99d\"\n#define ICON_KI_BUTTON_L2 u8\"\\ue99e\"\n#define ICON_KI_BUTTON_LB u8\"\\ue99f\"\n#define ICON_KI_BUTTON_LT u8\"\\ue9a0\"\n#define ICON_KI_BUTTON_RT u8\"\\ue9a1\"\n#define ICON_KI_BUTTON_RB u8\"\\ue9a2\"\n#define ICON_KI_BUTTON_R2 u8\"\\ue9a3\"\n#define ICON_KI_BUTTON_R1 u8\"\\ue9a4\"\n#define ICON_KI_BUTTON_R u8\"\\ue9a5\"\n#define ICON_KI_BUTTON_RIGHT u8\"\\ue9a6\"\n#define ICON_KI_BUTTON_EMPTY u8\"\\ue9a7\"\n#define ICON_KI_BUTTON_START u8\"\\ue9a8\"\n#define ICON_KI_BUTTON_SELECT u8\"\\ue9a9\"\n#define ICON_KI_DPAD u8\"\\ue9aa\"\n#define ICON_KI_DPAD_ALT u8\"\\ue9ab\"\n#define ICON_KI_DPAD_TOP u8\"\\ue9ac\"\n#define ICON_KI_DPAD_RIGHT u8\"\\ue9ad\"\n#define ICON_KI_DPAD_BOTTOM u8\"\\ue9ae\"\n#define ICON_KI_DPAD_LEFT u8\"\\ue9af\"\n#define ICON_KI_KEY_LARGE u8\"\\ue9b0\"\n#define ICON_KI_KEY_LARGE_3D u8\"\\ue9b1\"\n#define ICON_KI_KEY_SMALL u8\"\\ue9b2\"\n#define ICON_KI_KEY_SMALL_3D u8\"\\ue9b3\"\n#define ICON_KI_STICK_LEFT_TOP u8\"\\ue9b4\"\n#define ICON_KI_STICK_LEFT_SIDE u8\"\\ue9b5\"\n#define ICON_KI_STICK_RIGHT_SIDE u8\"\\ue9b6\"\n#define ICON_KI_STICK_RIGHT_TOP u8\"\\ue9b7\"\n#define ICON_KI_STICK_SIDE u8\"\\ue9b8\"\n#define ICON_KI_STICK_TILT_LEFT u8\"\\ue9b9\"\n#define ICON_KI_STICK_TILT_RIGHT u8\"\\ue9ba\"\n#define ICON_KI_MOVE_BL u8\"\\ue9bb\"\n#define ICON_KI_MOVE_BR u8\"\\ue9bc\"\n#define ICON_KI_MOVE_BT u8\"\\ue9bd\"\n#define ICON_KI_MOVE_BT_ALT u8\"\\ue9be\"\n#define ICON_KI_MOVE_LB u8\"\\ue9bf\"\n#define ICON_KI_MOVE_LR u8\"\\ue9c0\"\n#define ICON_KI_MOVE_LR_ALT u8\"\\ue9c1\"\n#define ICON_KI_MOVE_LT u8\"\\ue9c2\"\n#define ICON_KI_MOVE_RB u8\"\\ue9c3\"\n#define ICON_KI_MOVE_RL u8\"\\ue9c4\"\n#define ICON_KI_MOVE_RL_ALT u8\"\\ue9c5\"\n#define ICON_KI_MOVE_RT u8\"\\ue9c6\"\n#define ICON_KI_MOVE_TB u8\"\\ue9c7\"\n#define ICON_KI_MOVE_TB_ALT u8\"\\ue9c8\"\n#define ICON_KI_MOVE_TL u8\"\\ue9c9\"\n#define ICON_KI_MOVE_TR u8\"\\ue9ca\"\n#define ICON_KI_STICK_MOVE_BL u8\"\\ue9cb\"\n#define ICON_KI_STICK_MOVE_BR u8\"\\ue9cc\"\n#define ICON_KI_STICK_MOVE_BT u8\"\\ue9cd\"\n#define ICON_KI_STICK_MOVE_BT_ALT u8\"\\ue9ce\"\n#define ICON_KI_STICK_MOVE_LB u8\"\\ue9cf\"\n#define ICON_KI_STICK_MOVE_LR u8\"\\ue9d0\"\n#define ICON_KI_STICK_MOVE_LR_ALT u8\"\\ue9d1\"\n#define ICON_KI_STICK_MOVE_LT u8\"\\ue9d2\"\n#define ICON_KI_STICK_MOVE_RB u8\"\\ue9d3\"\n#define ICON_KI_STICK_MOVE_RL u8\"\\ue9d4\"\n#define ICON_KI_STICK_MOVE_RL_ALT u8\"\\ue9d5\"\n#define ICON_KI_STICK_MOVE_RT u8\"\\ue9d6\"\n#define ICON_KI_STICK_MOVE_TB u8\"\\ue9d7\"\n#define ICON_KI_STICK_MOVE_TB_ALT u8\"\\ue9d8\"\n#define ICON_KI_STICK_MOVE_TL u8\"\\ue9d9\"\n#define ICON_KI_STICK_MOVE_TR u8\"\\ue9da\"\n#define ICON_KI_GITHUB u8\"\\ue9db\"\n#define ICON_KI_GITHUB_ALT u8\"\\ue9dc\"\n#define ICON_KI_TWITTER u8\"\\ue9dd\"\n#define ICON_KI_FACEBOOK u8\"\\ue9de\"\n#define ICON_KI_GOOGLE_PLUS u8\"\\ue9df\"\n#define ICON_KI_YOUTUBE u8\"\\ue9e2\"\n#define ICON_KI_WE_HEART u8\"\\ue9e3\"\n#define ICON_KI_WOLFCMS u8\"\\ue9e0\"\n#define ICON_KI_WOLFCMS_ALT u8\"\\ue9e1\"\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/IconFontCppHeaders/IconsMaterialDesign.h",
    "content": "// Generated by https://github.com/juliettef/IconFontCppHeaders script GenerateIconFontCppHeaders.py for language C++11\n// from https://raw.githubusercontent.com/google/material-design-icons/master/iconfont/codepoints\n// for use with https://github.com/google/material-design-icons/blob/master/iconfont/MaterialIcons-Regular.ttf\n#pragma once\n\n#define FONT_ICON_FILE_NAME_MD \"MaterialIcons-Regular.ttf\"\n\n#define ICON_MIN_MD 0xe000\n#define ICON_MAX_MD 0xeb4c\n#define ICON_MD_3D_ROTATION u8\"\\ue84d\"\n#define ICON_MD_AC_UNIT u8\"\\ueb3b\"\n#define ICON_MD_ACCESS_ALARM u8\"\\ue190\"\n#define ICON_MD_ACCESS_ALARMS u8\"\\ue191\"\n#define ICON_MD_ACCESS_TIME u8\"\\ue192\"\n#define ICON_MD_ACCESSIBILITY u8\"\\ue84e\"\n#define ICON_MD_ACCESSIBLE u8\"\\ue914\"\n#define ICON_MD_ACCOUNT_BALANCE u8\"\\ue84f\"\n#define ICON_MD_ACCOUNT_BALANCE_WALLET u8\"\\ue850\"\n#define ICON_MD_ACCOUNT_BOX u8\"\\ue851\"\n#define ICON_MD_ACCOUNT_CIRCLE u8\"\\ue853\"\n#define ICON_MD_ADB u8\"\\ue60e\"\n#define ICON_MD_ADD u8\"\\ue145\"\n#define ICON_MD_ADD_A_PHOTO u8\"\\ue439\"\n#define ICON_MD_ADD_ALARM u8\"\\ue193\"\n#define ICON_MD_ADD_ALERT u8\"\\ue003\"\n#define ICON_MD_ADD_BOX u8\"\\ue146\"\n#define ICON_MD_ADD_CIRCLE u8\"\\ue147\"\n#define ICON_MD_ADD_CIRCLE_OUTLINE u8\"\\ue148\"\n#define ICON_MD_ADD_LOCATION u8\"\\ue567\"\n#define ICON_MD_ADD_SHOPPING_CART u8\"\\ue854\"\n#define ICON_MD_ADD_TO_PHOTOS u8\"\\ue39d\"\n#define ICON_MD_ADD_TO_QUEUE u8\"\\ue05c\"\n#define ICON_MD_ADJUST u8\"\\ue39e\"\n#define ICON_MD_AIRLINE_SEAT_FLAT u8\"\\ue630\"\n#define ICON_MD_AIRLINE_SEAT_FLAT_ANGLED u8\"\\ue631\"\n#define ICON_MD_AIRLINE_SEAT_INDIVIDUAL_SUITE u8\"\\ue632\"\n#define ICON_MD_AIRLINE_SEAT_LEGROOM_EXTRA u8\"\\ue633\"\n#define ICON_MD_AIRLINE_SEAT_LEGROOM_NORMAL u8\"\\ue634\"\n#define ICON_MD_AIRLINE_SEAT_LEGROOM_REDUCED u8\"\\ue635\"\n#define ICON_MD_AIRLINE_SEAT_RECLINE_EXTRA u8\"\\ue636\"\n#define ICON_MD_AIRLINE_SEAT_RECLINE_NORMAL u8\"\\ue637\"\n#define ICON_MD_AIRPLANEMODE_ACTIVE u8\"\\ue195\"\n#define ICON_MD_AIRPLANEMODE_INACTIVE u8\"\\ue194\"\n#define ICON_MD_AIRPLAY u8\"\\ue055\"\n#define ICON_MD_AIRPORT_SHUTTLE u8\"\\ueb3c\"\n#define ICON_MD_ALARM u8\"\\ue855\"\n#define ICON_MD_ALARM_ADD u8\"\\ue856\"\n#define ICON_MD_ALARM_OFF u8\"\\ue857\"\n#define ICON_MD_ALARM_ON u8\"\\ue858\"\n#define ICON_MD_ALBUM u8\"\\ue019\"\n#define ICON_MD_ALL_INCLUSIVE u8\"\\ueb3d\"\n#define ICON_MD_ALL_OUT u8\"\\ue90b\"\n#define ICON_MD_ANDROID u8\"\\ue859\"\n#define ICON_MD_ANNOUNCEMENT u8\"\\ue85a\"\n#define ICON_MD_APPS u8\"\\ue5c3\"\n#define ICON_MD_ARCHIVE u8\"\\ue149\"\n#define ICON_MD_ARROW_BACK u8\"\\ue5c4\"\n#define ICON_MD_ARROW_DOWNWARD u8\"\\ue5db\"\n#define ICON_MD_ARROW_DROP_DOWN u8\"\\ue5c5\"\n#define ICON_MD_ARROW_DROP_DOWN_CIRCLE u8\"\\ue5c6\"\n#define ICON_MD_ARROW_DROP_UP u8\"\\ue5c7\"\n#define ICON_MD_ARROW_FORWARD u8\"\\ue5c8\"\n#define ICON_MD_ARROW_UPWARD u8\"\\ue5d8\"\n#define ICON_MD_ART_TRACK u8\"\\ue060\"\n#define ICON_MD_ASPECT_RATIO u8\"\\ue85b\"\n#define ICON_MD_ASSESSMENT u8\"\\ue85c\"\n#define ICON_MD_ASSIGNMENT u8\"\\ue85d\"\n#define ICON_MD_ASSIGNMENT_IND u8\"\\ue85e\"\n#define ICON_MD_ASSIGNMENT_LATE u8\"\\ue85f\"\n#define ICON_MD_ASSIGNMENT_RETURN u8\"\\ue860\"\n#define ICON_MD_ASSIGNMENT_RETURNED u8\"\\ue861\"\n#define ICON_MD_ASSIGNMENT_TURNED_IN u8\"\\ue862\"\n#define ICON_MD_ASSISTANT u8\"\\ue39f\"\n#define ICON_MD_ASSISTANT_PHOTO u8\"\\ue3a0\"\n#define ICON_MD_ATTACH_FILE u8\"\\ue226\"\n#define ICON_MD_ATTACH_MONEY u8\"\\ue227\"\n#define ICON_MD_ATTACHMENT u8\"\\ue2bc\"\n#define ICON_MD_AUDIOTRACK u8\"\\ue3a1\"\n#define ICON_MD_AUTORENEW u8\"\\ue863\"\n#define ICON_MD_AV_TIMER u8\"\\ue01b\"\n#define ICON_MD_BACKSPACE u8\"\\ue14a\"\n#define ICON_MD_BACKUP u8\"\\ue864\"\n#define ICON_MD_BATTERY_ALERT u8\"\\ue19c\"\n#define ICON_MD_BATTERY_CHARGING_FULL u8\"\\ue1a3\"\n#define ICON_MD_BATTERY_FULL u8\"\\ue1a4\"\n#define ICON_MD_BATTERY_STD u8\"\\ue1a5\"\n#define ICON_MD_BATTERY_UNKNOWN u8\"\\ue1a6\"\n#define ICON_MD_BEACH_ACCESS u8\"\\ueb3e\"\n#define ICON_MD_BEENHERE u8\"\\ue52d\"\n#define ICON_MD_BLOCK u8\"\\ue14b\"\n#define ICON_MD_BLUETOOTH u8\"\\ue1a7\"\n#define ICON_MD_BLUETOOTH_AUDIO u8\"\\ue60f\"\n#define ICON_MD_BLUETOOTH_CONNECTED u8\"\\ue1a8\"\n#define ICON_MD_BLUETOOTH_DISABLED u8\"\\ue1a9\"\n#define ICON_MD_BLUETOOTH_SEARCHING u8\"\\ue1aa\"\n#define ICON_MD_BLUR_CIRCULAR u8\"\\ue3a2\"\n#define ICON_MD_BLUR_LINEAR u8\"\\ue3a3\"\n#define ICON_MD_BLUR_OFF u8\"\\ue3a4\"\n#define ICON_MD_BLUR_ON u8\"\\ue3a5\"\n#define ICON_MD_BOOK u8\"\\ue865\"\n#define ICON_MD_BOOKMARK u8\"\\ue866\"\n#define ICON_MD_BOOKMARK_BORDER u8\"\\ue867\"\n#define ICON_MD_BORDER_ALL u8\"\\ue228\"\n#define ICON_MD_BORDER_BOTTOM u8\"\\ue229\"\n#define ICON_MD_BORDER_CLEAR u8\"\\ue22a\"\n#define ICON_MD_BORDER_COLOR u8\"\\ue22b\"\n#define ICON_MD_BORDER_HORIZONTAL u8\"\\ue22c\"\n#define ICON_MD_BORDER_INNER u8\"\\ue22d\"\n#define ICON_MD_BORDER_LEFT u8\"\\ue22e\"\n#define ICON_MD_BORDER_OUTER u8\"\\ue22f\"\n#define ICON_MD_BORDER_RIGHT u8\"\\ue230\"\n#define ICON_MD_BORDER_STYLE u8\"\\ue231\"\n#define ICON_MD_BORDER_TOP u8\"\\ue232\"\n#define ICON_MD_BORDER_VERTICAL u8\"\\ue233\"\n#define ICON_MD_BRANDING_WATERMARK u8\"\\ue06b\"\n#define ICON_MD_BRIGHTNESS_1 u8\"\\ue3a6\"\n#define ICON_MD_BRIGHTNESS_2 u8\"\\ue3a7\"\n#define ICON_MD_BRIGHTNESS_3 u8\"\\ue3a8\"\n#define ICON_MD_BRIGHTNESS_4 u8\"\\ue3a9\"\n#define ICON_MD_BRIGHTNESS_5 u8\"\\ue3aa\"\n#define ICON_MD_BRIGHTNESS_6 u8\"\\ue3ab\"\n#define ICON_MD_BRIGHTNESS_7 u8\"\\ue3ac\"\n#define ICON_MD_BRIGHTNESS_AUTO u8\"\\ue1ab\"\n#define ICON_MD_BRIGHTNESS_HIGH u8\"\\ue1ac\"\n#define ICON_MD_BRIGHTNESS_LOW u8\"\\ue1ad\"\n#define ICON_MD_BRIGHTNESS_MEDIUM u8\"\\ue1ae\"\n#define ICON_MD_BROKEN_IMAGE u8\"\\ue3ad\"\n#define ICON_MD_BRUSH u8\"\\ue3ae\"\n#define ICON_MD_BUBBLE_CHART u8\"\\ue6dd\"\n#define ICON_MD_BUG_REPORT u8\"\\ue868\"\n#define ICON_MD_BUILD u8\"\\ue869\"\n#define ICON_MD_BURST_MODE u8\"\\ue43c\"\n#define ICON_MD_BUSINESS u8\"\\ue0af\"\n#define ICON_MD_BUSINESS_CENTER u8\"\\ueb3f\"\n#define ICON_MD_CACHED u8\"\\ue86a\"\n#define ICON_MD_CAKE u8\"\\ue7e9\"\n#define ICON_MD_CALL u8\"\\ue0b0\"\n#define ICON_MD_CALL_END u8\"\\ue0b1\"\n#define ICON_MD_CALL_MADE u8\"\\ue0b2\"\n#define ICON_MD_CALL_MERGE u8\"\\ue0b3\"\n#define ICON_MD_CALL_MISSED u8\"\\ue0b4\"\n#define ICON_MD_CALL_MISSED_OUTGOING u8\"\\ue0e4\"\n#define ICON_MD_CALL_RECEIVED u8\"\\ue0b5\"\n#define ICON_MD_CALL_SPLIT u8\"\\ue0b6\"\n#define ICON_MD_CALL_TO_ACTION u8\"\\ue06c\"\n#define ICON_MD_CAMERA u8\"\\ue3af\"\n#define ICON_MD_CAMERA_ALT u8\"\\ue3b0\"\n#define ICON_MD_CAMERA_ENHANCE u8\"\\ue8fc\"\n#define ICON_MD_CAMERA_FRONT u8\"\\ue3b1\"\n#define ICON_MD_CAMERA_REAR u8\"\\ue3b2\"\n#define ICON_MD_CAMERA_ROLL u8\"\\ue3b3\"\n#define ICON_MD_CANCEL u8\"\\ue5c9\"\n#define ICON_MD_CARD_GIFTCARD u8\"\\ue8f6\"\n#define ICON_MD_CARD_MEMBERSHIP u8\"\\ue8f7\"\n#define ICON_MD_CARD_TRAVEL u8\"\\ue8f8\"\n#define ICON_MD_CASINO u8\"\\ueb40\"\n#define ICON_MD_CAST u8\"\\ue307\"\n#define ICON_MD_CAST_CONNECTED u8\"\\ue308\"\n#define ICON_MD_CENTER_FOCUS_STRONG u8\"\\ue3b4\"\n#define ICON_MD_CENTER_FOCUS_WEAK u8\"\\ue3b5\"\n#define ICON_MD_CHANGE_HISTORY u8\"\\ue86b\"\n#define ICON_MD_CHAT u8\"\\ue0b7\"\n#define ICON_MD_CHAT_BUBBLE u8\"\\ue0ca\"\n#define ICON_MD_CHAT_BUBBLE_OUTLINE u8\"\\ue0cb\"\n#define ICON_MD_CHECK u8\"\\ue5ca\"\n#define ICON_MD_CHECK_BOX u8\"\\ue834\"\n#define ICON_MD_CHECK_BOX_OUTLINE_BLANK u8\"\\ue835\"\n#define ICON_MD_CHECK_CIRCLE u8\"\\ue86c\"\n#define ICON_MD_CHEVRON_LEFT u8\"\\ue5cb\"\n#define ICON_MD_CHEVRON_RIGHT u8\"\\ue5cc\"\n#define ICON_MD_CHILD_CARE u8\"\\ueb41\"\n#define ICON_MD_CHILD_FRIENDLY u8\"\\ueb42\"\n#define ICON_MD_CHROME_READER_MODE u8\"\\ue86d\"\n#define ICON_MD_CLASS u8\"\\ue86e\"\n#define ICON_MD_CLEAR u8\"\\ue14c\"\n#define ICON_MD_CLEAR_ALL u8\"\\ue0b8\"\n#define ICON_MD_CLOSE u8\"\\ue5cd\"\n#define ICON_MD_CLOSED_CAPTION u8\"\\ue01c\"\n#define ICON_MD_CLOUD u8\"\\ue2bd\"\n#define ICON_MD_CLOUD_CIRCLE u8\"\\ue2be\"\n#define ICON_MD_CLOUD_DONE u8\"\\ue2bf\"\n#define ICON_MD_CLOUD_DOWNLOAD u8\"\\ue2c0\"\n#define ICON_MD_CLOUD_OFF u8\"\\ue2c1\"\n#define ICON_MD_CLOUD_QUEUE u8\"\\ue2c2\"\n#define ICON_MD_CLOUD_UPLOAD u8\"\\ue2c3\"\n#define ICON_MD_CODE u8\"\\ue86f\"\n#define ICON_MD_COLLECTIONS u8\"\\ue3b6\"\n#define ICON_MD_COLLECTIONS_BOOKMARK u8\"\\ue431\"\n#define ICON_MD_COLOR_LENS u8\"\\ue3b7\"\n#define ICON_MD_COLORIZE u8\"\\ue3b8\"\n#define ICON_MD_COMMENT u8\"\\ue0b9\"\n#define ICON_MD_COMPARE u8\"\\ue3b9\"\n#define ICON_MD_COMPARE_ARROWS u8\"\\ue915\"\n#define ICON_MD_COMPUTER u8\"\\ue30a\"\n#define ICON_MD_CONFIRMATION_NUMBER u8\"\\ue638\"\n#define ICON_MD_CONTACT_MAIL u8\"\\ue0d0\"\n#define ICON_MD_CONTACT_PHONE u8\"\\ue0cf\"\n#define ICON_MD_CONTACTS u8\"\\ue0ba\"\n#define ICON_MD_CONTENT_COPY u8\"\\ue14d\"\n#define ICON_MD_CONTENT_CUT u8\"\\ue14e\"\n#define ICON_MD_CONTENT_PASTE u8\"\\ue14f\"\n#define ICON_MD_CONTROL_POINT u8\"\\ue3ba\"\n#define ICON_MD_CONTROL_POINT_DUPLICATE u8\"\\ue3bb\"\n#define ICON_MD_COPYRIGHT u8\"\\ue90c\"\n#define ICON_MD_CREATE u8\"\\ue150\"\n#define ICON_MD_CREATE_NEW_FOLDER u8\"\\ue2cc\"\n#define ICON_MD_CREDIT_CARD u8\"\\ue870\"\n#define ICON_MD_CROP u8\"\\ue3be\"\n#define ICON_MD_CROP_16_9 u8\"\\ue3bc\"\n#define ICON_MD_CROP_3_2 u8\"\\ue3bd\"\n#define ICON_MD_CROP_5_4 u8\"\\ue3bf\"\n#define ICON_MD_CROP_7_5 u8\"\\ue3c0\"\n#define ICON_MD_CROP_DIN u8\"\\ue3c1\"\n#define ICON_MD_CROP_FREE u8\"\\ue3c2\"\n#define ICON_MD_CROP_LANDSCAPE u8\"\\ue3c3\"\n#define ICON_MD_CROP_ORIGINAL u8\"\\ue3c4\"\n#define ICON_MD_CROP_PORTRAIT u8\"\\ue3c5\"\n#define ICON_MD_CROP_ROTATE u8\"\\ue437\"\n#define ICON_MD_CROP_SQUARE u8\"\\ue3c6\"\n#define ICON_MD_DASHBOARD u8\"\\ue871\"\n#define ICON_MD_DATA_USAGE u8\"\\ue1af\"\n#define ICON_MD_DATE_RANGE u8\"\\ue916\"\n#define ICON_MD_DEHAZE u8\"\\ue3c7\"\n#define ICON_MD_DELETE u8\"\\ue872\"\n#define ICON_MD_DELETE_FOREVER u8\"\\ue92b\"\n#define ICON_MD_DELETE_SWEEP u8\"\\ue16c\"\n#define ICON_MD_DESCRIPTION u8\"\\ue873\"\n#define ICON_MD_DESKTOP_MAC u8\"\\ue30b\"\n#define ICON_MD_DESKTOP_WINDOWS u8\"\\ue30c\"\n#define ICON_MD_DETAILS u8\"\\ue3c8\"\n#define ICON_MD_DEVELOPER_BOARD u8\"\\ue30d\"\n#define ICON_MD_DEVELOPER_MODE u8\"\\ue1b0\"\n#define ICON_MD_DEVICE_HUB u8\"\\ue335\"\n#define ICON_MD_DEVICES u8\"\\ue1b1\"\n#define ICON_MD_DEVICES_OTHER u8\"\\ue337\"\n#define ICON_MD_DIALER_SIP u8\"\\ue0bb\"\n#define ICON_MD_DIALPAD u8\"\\ue0bc\"\n#define ICON_MD_DIRECTIONS u8\"\\ue52e\"\n#define ICON_MD_DIRECTIONS_BIKE u8\"\\ue52f\"\n#define ICON_MD_DIRECTIONS_BOAT u8\"\\ue532\"\n#define ICON_MD_DIRECTIONS_BUS u8\"\\ue530\"\n#define ICON_MD_DIRECTIONS_CAR u8\"\\ue531\"\n#define ICON_MD_DIRECTIONS_RAILWAY u8\"\\ue534\"\n#define ICON_MD_DIRECTIONS_RUN u8\"\\ue566\"\n#define ICON_MD_DIRECTIONS_SUBWAY u8\"\\ue533\"\n#define ICON_MD_DIRECTIONS_TRANSIT u8\"\\ue535\"\n#define ICON_MD_DIRECTIONS_WALK u8\"\\ue536\"\n#define ICON_MD_DISC_FULL u8\"\\ue610\"\n#define ICON_MD_DNS u8\"\\ue875\"\n#define ICON_MD_DO_NOT_DISTURB u8\"\\ue612\"\n#define ICON_MD_DO_NOT_DISTURB_ALT u8\"\\ue611\"\n#define ICON_MD_DO_NOT_DISTURB_OFF u8\"\\ue643\"\n#define ICON_MD_DO_NOT_DISTURB_ON u8\"\\ue644\"\n#define ICON_MD_DOCK u8\"\\ue30e\"\n#define ICON_MD_DOMAIN u8\"\\ue7ee\"\n#define ICON_MD_DONE u8\"\\ue876\"\n#define ICON_MD_DONE_ALL u8\"\\ue877\"\n#define ICON_MD_DONUT_LARGE u8\"\\ue917\"\n#define ICON_MD_DONUT_SMALL u8\"\\ue918\"\n#define ICON_MD_DRAFTS u8\"\\ue151\"\n#define ICON_MD_DRAG_HANDLE u8\"\\ue25d\"\n#define ICON_MD_DRIVE_ETA u8\"\\ue613\"\n#define ICON_MD_DVR u8\"\\ue1b2\"\n#define ICON_MD_EDIT u8\"\\ue3c9\"\n#define ICON_MD_EDIT_LOCATION u8\"\\ue568\"\n#define ICON_MD_EJECT u8\"\\ue8fb\"\n#define ICON_MD_EMAIL u8\"\\ue0be\"\n#define ICON_MD_ENHANCED_ENCRYPTION u8\"\\ue63f\"\n#define ICON_MD_EQUALIZER u8\"\\ue01d\"\n#define ICON_MD_ERROR u8\"\\ue000\"\n#define ICON_MD_ERROR_OUTLINE u8\"\\ue001\"\n#define ICON_MD_EURO_SYMBOL u8\"\\ue926\"\n#define ICON_MD_EV_STATION u8\"\\ue56d\"\n#define ICON_MD_EVENT u8\"\\ue878\"\n#define ICON_MD_EVENT_AVAILABLE u8\"\\ue614\"\n#define ICON_MD_EVENT_BUSY u8\"\\ue615\"\n#define ICON_MD_EVENT_NOTE u8\"\\ue616\"\n#define ICON_MD_EVENT_SEAT u8\"\\ue903\"\n#define ICON_MD_EXIT_TO_APP u8\"\\ue879\"\n#define ICON_MD_EXPAND_LESS u8\"\\ue5ce\"\n#define ICON_MD_EXPAND_MORE u8\"\\ue5cf\"\n#define ICON_MD_EXPLICIT u8\"\\ue01e\"\n#define ICON_MD_EXPLORE u8\"\\ue87a\"\n#define ICON_MD_EXPOSURE u8\"\\ue3ca\"\n#define ICON_MD_EXPOSURE_NEG_1 u8\"\\ue3cb\"\n#define ICON_MD_EXPOSURE_NEG_2 u8\"\\ue3cc\"\n#define ICON_MD_EXPOSURE_PLUS_1 u8\"\\ue3cd\"\n#define ICON_MD_EXPOSURE_PLUS_2 u8\"\\ue3ce\"\n#define ICON_MD_EXPOSURE_ZERO u8\"\\ue3cf\"\n#define ICON_MD_EXTENSION u8\"\\ue87b\"\n#define ICON_MD_FACE u8\"\\ue87c\"\n#define ICON_MD_FAST_FORWARD u8\"\\ue01f\"\n#define ICON_MD_FAST_REWIND u8\"\\ue020\"\n#define ICON_MD_FAVORITE u8\"\\ue87d\"\n#define ICON_MD_FAVORITE_BORDER u8\"\\ue87e\"\n#define ICON_MD_FEATURED_PLAY_LIST u8\"\\ue06d\"\n#define ICON_MD_FEATURED_VIDEO u8\"\\ue06e\"\n#define ICON_MD_FEEDBACK u8\"\\ue87f\"\n#define ICON_MD_FIBER_DVR u8\"\\ue05d\"\n#define ICON_MD_FIBER_MANUAL_RECORD u8\"\\ue061\"\n#define ICON_MD_FIBER_NEW u8\"\\ue05e\"\n#define ICON_MD_FIBER_PIN u8\"\\ue06a\"\n#define ICON_MD_FIBER_SMART_RECORD u8\"\\ue062\"\n#define ICON_MD_FILE_DOWNLOAD u8\"\\ue2c4\"\n#define ICON_MD_FILE_UPLOAD u8\"\\ue2c6\"\n#define ICON_MD_FILTER u8\"\\ue3d3\"\n#define ICON_MD_FILTER_1 u8\"\\ue3d0\"\n#define ICON_MD_FILTER_2 u8\"\\ue3d1\"\n#define ICON_MD_FILTER_3 u8\"\\ue3d2\"\n#define ICON_MD_FILTER_4 u8\"\\ue3d4\"\n#define ICON_MD_FILTER_5 u8\"\\ue3d5\"\n#define ICON_MD_FILTER_6 u8\"\\ue3d6\"\n#define ICON_MD_FILTER_7 u8\"\\ue3d7\"\n#define ICON_MD_FILTER_8 u8\"\\ue3d8\"\n#define ICON_MD_FILTER_9 u8\"\\ue3d9\"\n#define ICON_MD_FILTER_9_PLUS u8\"\\ue3da\"\n#define ICON_MD_FILTER_B_AND_W u8\"\\ue3db\"\n#define ICON_MD_FILTER_CENTER_FOCUS u8\"\\ue3dc\"\n#define ICON_MD_FILTER_DRAMA u8\"\\ue3dd\"\n#define ICON_MD_FILTER_FRAMES u8\"\\ue3de\"\n#define ICON_MD_FILTER_HDR u8\"\\ue3df\"\n#define ICON_MD_FILTER_LIST u8\"\\ue152\"\n#define ICON_MD_FILTER_NONE u8\"\\ue3e0\"\n#define ICON_MD_FILTER_TILT_SHIFT u8\"\\ue3e2\"\n#define ICON_MD_FILTER_VINTAGE u8\"\\ue3e3\"\n#define ICON_MD_FIND_IN_PAGE u8\"\\ue880\"\n#define ICON_MD_FIND_REPLACE u8\"\\ue881\"\n#define ICON_MD_FINGERPRINT u8\"\\ue90d\"\n#define ICON_MD_FIRST_PAGE u8\"\\ue5dc\"\n#define ICON_MD_FITNESS_CENTER u8\"\\ueb43\"\n#define ICON_MD_FLAG u8\"\\ue153\"\n#define ICON_MD_FLARE u8\"\\ue3e4\"\n#define ICON_MD_FLASH_AUTO u8\"\\ue3e5\"\n#define ICON_MD_FLASH_OFF u8\"\\ue3e6\"\n#define ICON_MD_FLASH_ON u8\"\\ue3e7\"\n#define ICON_MD_FLIGHT u8\"\\ue539\"\n#define ICON_MD_FLIGHT_LAND u8\"\\ue904\"\n#define ICON_MD_FLIGHT_TAKEOFF u8\"\\ue905\"\n#define ICON_MD_FLIP u8\"\\ue3e8\"\n#define ICON_MD_FLIP_TO_BACK u8\"\\ue882\"\n#define ICON_MD_FLIP_TO_FRONT u8\"\\ue883\"\n#define ICON_MD_FOLDER u8\"\\ue2c7\"\n#define ICON_MD_FOLDER_OPEN u8\"\\ue2c8\"\n#define ICON_MD_FOLDER_SHARED u8\"\\ue2c9\"\n#define ICON_MD_FOLDER_SPECIAL u8\"\\ue617\"\n#define ICON_MD_FONT_DOWNLOAD u8\"\\ue167\"\n#define ICON_MD_FORMAT_ALIGN_CENTER u8\"\\ue234\"\n#define ICON_MD_FORMAT_ALIGN_JUSTIFY u8\"\\ue235\"\n#define ICON_MD_FORMAT_ALIGN_LEFT u8\"\\ue236\"\n#define ICON_MD_FORMAT_ALIGN_RIGHT u8\"\\ue237\"\n#define ICON_MD_FORMAT_BOLD u8\"\\ue238\"\n#define ICON_MD_FORMAT_CLEAR u8\"\\ue239\"\n#define ICON_MD_FORMAT_COLOR_FILL u8\"\\ue23a\"\n#define ICON_MD_FORMAT_COLOR_RESET u8\"\\ue23b\"\n#define ICON_MD_FORMAT_COLOR_TEXT u8\"\\ue23c\"\n#define ICON_MD_FORMAT_INDENT_DECREASE u8\"\\ue23d\"\n#define ICON_MD_FORMAT_INDENT_INCREASE u8\"\\ue23e\"\n#define ICON_MD_FORMAT_ITALIC u8\"\\ue23f\"\n#define ICON_MD_FORMAT_LINE_SPACING u8\"\\ue240\"\n#define ICON_MD_FORMAT_LIST_BULLETED u8\"\\ue241\"\n#define ICON_MD_FORMAT_LIST_NUMBERED u8\"\\ue242\"\n#define ICON_MD_FORMAT_PAINT u8\"\\ue243\"\n#define ICON_MD_FORMAT_QUOTE u8\"\\ue244\"\n#define ICON_MD_FORMAT_SHAPES u8\"\\ue25e\"\n#define ICON_MD_FORMAT_SIZE u8\"\\ue245\"\n#define ICON_MD_FORMAT_STRIKETHROUGH u8\"\\ue246\"\n#define ICON_MD_FORMAT_TEXTDIRECTION_L_TO_R u8\"\\ue247\"\n#define ICON_MD_FORMAT_TEXTDIRECTION_R_TO_L u8\"\\ue248\"\n#define ICON_MD_FORMAT_UNDERLINED u8\"\\ue249\"\n#define ICON_MD_FORUM u8\"\\ue0bf\"\n#define ICON_MD_FORWARD u8\"\\ue154\"\n#define ICON_MD_FORWARD_10 u8\"\\ue056\"\n#define ICON_MD_FORWARD_30 u8\"\\ue057\"\n#define ICON_MD_FORWARD_5 u8\"\\ue058\"\n#define ICON_MD_FREE_BREAKFAST u8\"\\ueb44\"\n#define ICON_MD_FULLSCREEN u8\"\\ue5d0\"\n#define ICON_MD_FULLSCREEN_EXIT u8\"\\ue5d1\"\n#define ICON_MD_FUNCTIONS u8\"\\ue24a\"\n#define ICON_MD_G_TRANSLATE u8\"\\ue927\"\n#define ICON_MD_GAMEPAD u8\"\\ue30f\"\n#define ICON_MD_GAMES u8\"\\ue021\"\n#define ICON_MD_GAVEL u8\"\\ue90e\"\n#define ICON_MD_GESTURE u8\"\\ue155\"\n#define ICON_MD_GET_APP u8\"\\ue884\"\n#define ICON_MD_GIF u8\"\\ue908\"\n#define ICON_MD_GOLF_COURSE u8\"\\ueb45\"\n#define ICON_MD_GPS_FIXED u8\"\\ue1b3\"\n#define ICON_MD_GPS_NOT_FIXED u8\"\\ue1b4\"\n#define ICON_MD_GPS_OFF u8\"\\ue1b5\"\n#define ICON_MD_GRADE u8\"\\ue885\"\n#define ICON_MD_GRADIENT u8\"\\ue3e9\"\n#define ICON_MD_GRAIN u8\"\\ue3ea\"\n#define ICON_MD_GRAPHIC_EQ u8\"\\ue1b8\"\n#define ICON_MD_GRID_OFF u8\"\\ue3eb\"\n#define ICON_MD_GRID_ON u8\"\\ue3ec\"\n#define ICON_MD_GROUP u8\"\\ue7ef\"\n#define ICON_MD_GROUP_ADD u8\"\\ue7f0\"\n#define ICON_MD_GROUP_WORK u8\"\\ue886\"\n#define ICON_MD_HD u8\"\\ue052\"\n#define ICON_MD_HDR_OFF u8\"\\ue3ed\"\n#define ICON_MD_HDR_ON u8\"\\ue3ee\"\n#define ICON_MD_HDR_STRONG u8\"\\ue3f1\"\n#define ICON_MD_HDR_WEAK u8\"\\ue3f2\"\n#define ICON_MD_HEADSET u8\"\\ue310\"\n#define ICON_MD_HEADSET_MIC u8\"\\ue311\"\n#define ICON_MD_HEALING u8\"\\ue3f3\"\n#define ICON_MD_HEARING u8\"\\ue023\"\n#define ICON_MD_HELP u8\"\\ue887\"\n#define ICON_MD_HELP_OUTLINE u8\"\\ue8fd\"\n#define ICON_MD_HIGH_QUALITY u8\"\\ue024\"\n#define ICON_MD_HIGHLIGHT u8\"\\ue25f\"\n#define ICON_MD_HIGHLIGHT_OFF u8\"\\ue888\"\n#define ICON_MD_HISTORY u8\"\\ue889\"\n#define ICON_MD_HOME u8\"\\ue88a\"\n#define ICON_MD_HOT_TUB u8\"\\ueb46\"\n#define ICON_MD_HOTEL u8\"\\ue53a\"\n#define ICON_MD_HOURGLASS_EMPTY u8\"\\ue88b\"\n#define ICON_MD_HOURGLASS_FULL u8\"\\ue88c\"\n#define ICON_MD_HTTP u8\"\\ue902\"\n#define ICON_MD_HTTPS u8\"\\ue88d\"\n#define ICON_MD_IMAGE u8\"\\ue3f4\"\n#define ICON_MD_IMAGE_ASPECT_RATIO u8\"\\ue3f5\"\n#define ICON_MD_IMPORT_CONTACTS u8\"\\ue0e0\"\n#define ICON_MD_IMPORT_EXPORT u8\"\\ue0c3\"\n#define ICON_MD_IMPORTANT_DEVICES u8\"\\ue912\"\n#define ICON_MD_INBOX u8\"\\ue156\"\n#define ICON_MD_INDETERMINATE_CHECK_BOX u8\"\\ue909\"\n#define ICON_MD_INFO u8\"\\ue88e\"\n#define ICON_MD_INFO_OUTLINE u8\"\\ue88f\"\n#define ICON_MD_INPUT u8\"\\ue890\"\n#define ICON_MD_INSERT_CHART u8\"\\ue24b\"\n#define ICON_MD_INSERT_COMMENT u8\"\\ue24c\"\n#define ICON_MD_INSERT_DRIVE_FILE u8\"\\ue24d\"\n#define ICON_MD_INSERT_EMOTICON u8\"\\ue24e\"\n#define ICON_MD_INSERT_INVITATION u8\"\\ue24f\"\n#define ICON_MD_INSERT_LINK u8\"\\ue250\"\n#define ICON_MD_INSERT_PHOTO u8\"\\ue251\"\n#define ICON_MD_INVERT_COLORS u8\"\\ue891\"\n#define ICON_MD_INVERT_COLORS_OFF u8\"\\ue0c4\"\n#define ICON_MD_ISO u8\"\\ue3f6\"\n#define ICON_MD_KEYBOARD u8\"\\ue312\"\n#define ICON_MD_KEYBOARD_ARROW_DOWN u8\"\\ue313\"\n#define ICON_MD_KEYBOARD_ARROW_LEFT u8\"\\ue314\"\n#define ICON_MD_KEYBOARD_ARROW_RIGHT u8\"\\ue315\"\n#define ICON_MD_KEYBOARD_ARROW_UP u8\"\\ue316\"\n#define ICON_MD_KEYBOARD_BACKSPACE u8\"\\ue317\"\n#define ICON_MD_KEYBOARD_CAPSLOCK u8\"\\ue318\"\n#define ICON_MD_KEYBOARD_HIDE u8\"\\ue31a\"\n#define ICON_MD_KEYBOARD_RETURN u8\"\\ue31b\"\n#define ICON_MD_KEYBOARD_TAB u8\"\\ue31c\"\n#define ICON_MD_KEYBOARD_VOICE u8\"\\ue31d\"\n#define ICON_MD_KITCHEN u8\"\\ueb47\"\n#define ICON_MD_LABEL u8\"\\ue892\"\n#define ICON_MD_LABEL_OUTLINE u8\"\\ue893\"\n#define ICON_MD_LANDSCAPE u8\"\\ue3f7\"\n#define ICON_MD_LANGUAGE u8\"\\ue894\"\n#define ICON_MD_LAPTOP u8\"\\ue31e\"\n#define ICON_MD_LAPTOP_CHROMEBOOK u8\"\\ue31f\"\n#define ICON_MD_LAPTOP_MAC u8\"\\ue320\"\n#define ICON_MD_LAPTOP_WINDOWS u8\"\\ue321\"\n#define ICON_MD_LAST_PAGE u8\"\\ue5dd\"\n#define ICON_MD_LAUNCH u8\"\\ue895\"\n#define ICON_MD_LAYERS u8\"\\ue53b\"\n#define ICON_MD_LAYERS_CLEAR u8\"\\ue53c\"\n#define ICON_MD_LEAK_ADD u8\"\\ue3f8\"\n#define ICON_MD_LEAK_REMOVE u8\"\\ue3f9\"\n#define ICON_MD_LENS u8\"\\ue3fa\"\n#define ICON_MD_LIBRARY_ADD u8\"\\ue02e\"\n#define ICON_MD_LIBRARY_BOOKS u8\"\\ue02f\"\n#define ICON_MD_LIBRARY_MUSIC u8\"\\ue030\"\n#define ICON_MD_LIGHTBULB_OUTLINE u8\"\\ue90f\"\n#define ICON_MD_LINE_STYLE u8\"\\ue919\"\n#define ICON_MD_LINE_WEIGHT u8\"\\ue91a\"\n#define ICON_MD_LINEAR_SCALE u8\"\\ue260\"\n#define ICON_MD_LINK u8\"\\ue157\"\n#define ICON_MD_LINKED_CAMERA u8\"\\ue438\"\n#define ICON_MD_LIST u8\"\\ue896\"\n#define ICON_MD_LIVE_HELP u8\"\\ue0c6\"\n#define ICON_MD_LIVE_TV u8\"\\ue639\"\n#define ICON_MD_LOCAL_ACTIVITY u8\"\\ue53f\"\n#define ICON_MD_LOCAL_AIRPORT u8\"\\ue53d\"\n#define ICON_MD_LOCAL_ATM u8\"\\ue53e\"\n#define ICON_MD_LOCAL_BAR u8\"\\ue540\"\n#define ICON_MD_LOCAL_CAFE u8\"\\ue541\"\n#define ICON_MD_LOCAL_CAR_WASH u8\"\\ue542\"\n#define ICON_MD_LOCAL_CONVENIENCE_STORE u8\"\\ue543\"\n#define ICON_MD_LOCAL_DINING u8\"\\ue556\"\n#define ICON_MD_LOCAL_DRINK u8\"\\ue544\"\n#define ICON_MD_LOCAL_FLORIST u8\"\\ue545\"\n#define ICON_MD_LOCAL_GAS_STATION u8\"\\ue546\"\n#define ICON_MD_LOCAL_GROCERY_STORE u8\"\\ue547\"\n#define ICON_MD_LOCAL_HOSPITAL u8\"\\ue548\"\n#define ICON_MD_LOCAL_HOTEL u8\"\\ue549\"\n#define ICON_MD_LOCAL_LAUNDRY_SERVICE u8\"\\ue54a\"\n#define ICON_MD_LOCAL_LIBRARY u8\"\\ue54b\"\n#define ICON_MD_LOCAL_MALL u8\"\\ue54c\"\n#define ICON_MD_LOCAL_MOVIES u8\"\\ue54d\"\n#define ICON_MD_LOCAL_OFFER u8\"\\ue54e\"\n#define ICON_MD_LOCAL_PARKING u8\"\\ue54f\"\n#define ICON_MD_LOCAL_PHARMACY u8\"\\ue550\"\n#define ICON_MD_LOCAL_PHONE u8\"\\ue551\"\n#define ICON_MD_LOCAL_PIZZA u8\"\\ue552\"\n#define ICON_MD_LOCAL_PLAY u8\"\\ue553\"\n#define ICON_MD_LOCAL_POST_OFFICE u8\"\\ue554\"\n#define ICON_MD_LOCAL_PRINTSHOP u8\"\\ue555\"\n#define ICON_MD_LOCAL_SEE u8\"\\ue557\"\n#define ICON_MD_LOCAL_SHIPPING u8\"\\ue558\"\n#define ICON_MD_LOCAL_TAXI u8\"\\ue559\"\n#define ICON_MD_LOCATION_CITY u8\"\\ue7f1\"\n#define ICON_MD_LOCATION_DISABLED u8\"\\ue1b6\"\n#define ICON_MD_LOCATION_OFF u8\"\\ue0c7\"\n#define ICON_MD_LOCATION_ON u8\"\\ue0c8\"\n#define ICON_MD_LOCATION_SEARCHING u8\"\\ue1b7\"\n#define ICON_MD_LOCK u8\"\\ue897\"\n#define ICON_MD_LOCK_OPEN u8\"\\ue898\"\n#define ICON_MD_LOCK_OUTLINE u8\"\\ue899\"\n#define ICON_MD_LOOKS u8\"\\ue3fc\"\n#define ICON_MD_LOOKS_3 u8\"\\ue3fb\"\n#define ICON_MD_LOOKS_4 u8\"\\ue3fd\"\n#define ICON_MD_LOOKS_5 u8\"\\ue3fe\"\n#define ICON_MD_LOOKS_6 u8\"\\ue3ff\"\n#define ICON_MD_LOOKS_ONE u8\"\\ue400\"\n#define ICON_MD_LOOKS_TWO u8\"\\ue401\"\n#define ICON_MD_LOOP u8\"\\ue028\"\n#define ICON_MD_LOUPE u8\"\\ue402\"\n#define ICON_MD_LOW_PRIORITY u8\"\\ue16d\"\n#define ICON_MD_LOYALTY u8\"\\ue89a\"\n#define ICON_MD_MAIL u8\"\\ue158\"\n#define ICON_MD_MAIL_OUTLINE u8\"\\ue0e1\"\n#define ICON_MD_MAP u8\"\\ue55b\"\n#define ICON_MD_MARKUNREAD u8\"\\ue159\"\n#define ICON_MD_MARKUNREAD_MAILBOX u8\"\\ue89b\"\n#define ICON_MD_MEMORY u8\"\\ue322\"\n#define ICON_MD_MENU u8\"\\ue5d2\"\n#define ICON_MD_MERGE_TYPE u8\"\\ue252\"\n#define ICON_MD_MESSAGE u8\"\\ue0c9\"\n#define ICON_MD_MIC u8\"\\ue029\"\n#define ICON_MD_MIC_NONE u8\"\\ue02a\"\n#define ICON_MD_MIC_OFF u8\"\\ue02b\"\n#define ICON_MD_MMS u8\"\\ue618\"\n#define ICON_MD_MODE_COMMENT u8\"\\ue253\"\n#define ICON_MD_MODE_EDIT u8\"\\ue254\"\n#define ICON_MD_MONETIZATION_ON u8\"\\ue263\"\n#define ICON_MD_MONEY_OFF u8\"\\ue25c\"\n#define ICON_MD_MONOCHROME_PHOTOS u8\"\\ue403\"\n#define ICON_MD_MOOD u8\"\\ue7f2\"\n#define ICON_MD_MOOD_BAD u8\"\\ue7f3\"\n#define ICON_MD_MORE u8\"\\ue619\"\n#define ICON_MD_MORE_HORIZ u8\"\\ue5d3\"\n#define ICON_MD_MORE_VERT u8\"\\ue5d4\"\n#define ICON_MD_MOTORCYCLE u8\"\\ue91b\"\n#define ICON_MD_MOUSE u8\"\\ue323\"\n#define ICON_MD_MOVE_TO_INBOX u8\"\\ue168\"\n#define ICON_MD_MOVIE u8\"\\ue02c\"\n#define ICON_MD_MOVIE_CREATION u8\"\\ue404\"\n#define ICON_MD_MOVIE_FILTER u8\"\\ue43a\"\n#define ICON_MD_MULTILINE_CHART u8\"\\ue6df\"\n#define ICON_MD_MUSIC_NOTE u8\"\\ue405\"\n#define ICON_MD_MUSIC_VIDEO u8\"\\ue063\"\n#define ICON_MD_MY_LOCATION u8\"\\ue55c\"\n#define ICON_MD_NATURE u8\"\\ue406\"\n#define ICON_MD_NATURE_PEOPLE u8\"\\ue407\"\n#define ICON_MD_NAVIGATE_BEFORE u8\"\\ue408\"\n#define ICON_MD_NAVIGATE_NEXT u8\"\\ue409\"\n#define ICON_MD_NAVIGATION u8\"\\ue55d\"\n#define ICON_MD_NEAR_ME u8\"\\ue569\"\n#define ICON_MD_NETWORK_CELL u8\"\\ue1b9\"\n#define ICON_MD_NETWORK_CHECK u8\"\\ue640\"\n#define ICON_MD_NETWORK_LOCKED u8\"\\ue61a\"\n#define ICON_MD_NETWORK_WIFI u8\"\\ue1ba\"\n#define ICON_MD_NEW_RELEASES u8\"\\ue031\"\n#define ICON_MD_NEXT_WEEK u8\"\\ue16a\"\n#define ICON_MD_NFC u8\"\\ue1bb\"\n#define ICON_MD_NO_ENCRYPTION u8\"\\ue641\"\n#define ICON_MD_NO_SIM u8\"\\ue0cc\"\n#define ICON_MD_NOT_INTERESTED u8\"\\ue033\"\n#define ICON_MD_NOTE u8\"\\ue06f\"\n#define ICON_MD_NOTE_ADD u8\"\\ue89c\"\n#define ICON_MD_NOTIFICATIONS u8\"\\ue7f4\"\n#define ICON_MD_NOTIFICATIONS_ACTIVE u8\"\\ue7f7\"\n#define ICON_MD_NOTIFICATIONS_NONE u8\"\\ue7f5\"\n#define ICON_MD_NOTIFICATIONS_OFF u8\"\\ue7f6\"\n#define ICON_MD_NOTIFICATIONS_PAUSED u8\"\\ue7f8\"\n#define ICON_MD_OFFLINE_PIN u8\"\\ue90a\"\n#define ICON_MD_ONDEMAND_VIDEO u8\"\\ue63a\"\n#define ICON_MD_OPACITY u8\"\\ue91c\"\n#define ICON_MD_OPEN_IN_BROWSER u8\"\\ue89d\"\n#define ICON_MD_OPEN_IN_NEW u8\"\\ue89e\"\n#define ICON_MD_OPEN_WITH u8\"\\ue89f\"\n#define ICON_MD_PAGES u8\"\\ue7f9\"\n#define ICON_MD_PAGEVIEW u8\"\\ue8a0\"\n#define ICON_MD_PALETTE u8\"\\ue40a\"\n#define ICON_MD_PAN_TOOL u8\"\\ue925\"\n#define ICON_MD_PANORAMA u8\"\\ue40b\"\n#define ICON_MD_PANORAMA_FISH_EYE u8\"\\ue40c\"\n#define ICON_MD_PANORAMA_HORIZONTAL u8\"\\ue40d\"\n#define ICON_MD_PANORAMA_VERTICAL u8\"\\ue40e\"\n#define ICON_MD_PANORAMA_WIDE_ANGLE u8\"\\ue40f\"\n#define ICON_MD_PARTY_MODE u8\"\\ue7fa\"\n#define ICON_MD_PAUSE u8\"\\ue034\"\n#define ICON_MD_PAUSE_CIRCLE_FILLED u8\"\\ue035\"\n#define ICON_MD_PAUSE_CIRCLE_OUTLINE u8\"\\ue036\"\n#define ICON_MD_PAYMENT u8\"\\ue8a1\"\n#define ICON_MD_PEOPLE u8\"\\ue7fb\"\n#define ICON_MD_PEOPLE_OUTLINE u8\"\\ue7fc\"\n#define ICON_MD_PERM_CAMERA_MIC u8\"\\ue8a2\"\n#define ICON_MD_PERM_CONTACT_CALENDAR u8\"\\ue8a3\"\n#define ICON_MD_PERM_DATA_SETTING u8\"\\ue8a4\"\n#define ICON_MD_PERM_DEVICE_INFORMATION u8\"\\ue8a5\"\n#define ICON_MD_PERM_IDENTITY u8\"\\ue8a6\"\n#define ICON_MD_PERM_MEDIA u8\"\\ue8a7\"\n#define ICON_MD_PERM_PHONE_MSG u8\"\\ue8a8\"\n#define ICON_MD_PERM_SCAN_WIFI u8\"\\ue8a9\"\n#define ICON_MD_PERSON u8\"\\ue7fd\"\n#define ICON_MD_PERSON_ADD u8\"\\ue7fe\"\n#define ICON_MD_PERSON_OUTLINE u8\"\\ue7ff\"\n#define ICON_MD_PERSON_PIN u8\"\\ue55a\"\n#define ICON_MD_PERSON_PIN_CIRCLE u8\"\\ue56a\"\n#define ICON_MD_PERSONAL_VIDEO u8\"\\ue63b\"\n#define ICON_MD_PETS u8\"\\ue91d\"\n#define ICON_MD_PHONE u8\"\\ue0cd\"\n#define ICON_MD_PHONE_ANDROID u8\"\\ue324\"\n#define ICON_MD_PHONE_BLUETOOTH_SPEAKER u8\"\\ue61b\"\n#define ICON_MD_PHONE_FORWARDED u8\"\\ue61c\"\n#define ICON_MD_PHONE_IN_TALK u8\"\\ue61d\"\n#define ICON_MD_PHONE_IPHONE u8\"\\ue325\"\n#define ICON_MD_PHONE_LOCKED u8\"\\ue61e\"\n#define ICON_MD_PHONE_MISSED u8\"\\ue61f\"\n#define ICON_MD_PHONE_PAUSED u8\"\\ue620\"\n#define ICON_MD_PHONELINK u8\"\\ue326\"\n#define ICON_MD_PHONELINK_ERASE u8\"\\ue0db\"\n#define ICON_MD_PHONELINK_LOCK u8\"\\ue0dc\"\n#define ICON_MD_PHONELINK_OFF u8\"\\ue327\"\n#define ICON_MD_PHONELINK_RING u8\"\\ue0dd\"\n#define ICON_MD_PHONELINK_SETUP u8\"\\ue0de\"\n#define ICON_MD_PHOTO u8\"\\ue410\"\n#define ICON_MD_PHOTO_ALBUM u8\"\\ue411\"\n#define ICON_MD_PHOTO_CAMERA u8\"\\ue412\"\n#define ICON_MD_PHOTO_FILTER u8\"\\ue43b\"\n#define ICON_MD_PHOTO_LIBRARY u8\"\\ue413\"\n#define ICON_MD_PHOTO_SIZE_SELECT_ACTUAL u8\"\\ue432\"\n#define ICON_MD_PHOTO_SIZE_SELECT_LARGE u8\"\\ue433\"\n#define ICON_MD_PHOTO_SIZE_SELECT_SMALL u8\"\\ue434\"\n#define ICON_MD_PICTURE_AS_PDF u8\"\\ue415\"\n#define ICON_MD_PICTURE_IN_PICTURE u8\"\\ue8aa\"\n#define ICON_MD_PICTURE_IN_PICTURE_ALT u8\"\\ue911\"\n#define ICON_MD_PIE_CHART u8\"\\ue6c4\"\n#define ICON_MD_PIE_CHART_OUTLINED u8\"\\ue6c5\"\n#define ICON_MD_PIN_DROP u8\"\\ue55e\"\n#define ICON_MD_PLACE u8\"\\ue55f\"\n#define ICON_MD_PLAY_ARROW u8\"\\ue037\"\n#define ICON_MD_PLAY_CIRCLE_FILLED u8\"\\ue038\"\n#define ICON_MD_PLAY_CIRCLE_OUTLINE u8\"\\ue039\"\n#define ICON_MD_PLAY_FOR_WORK u8\"\\ue906\"\n#define ICON_MD_PLAYLIST_ADD u8\"\\ue03b\"\n#define ICON_MD_PLAYLIST_ADD_CHECK u8\"\\ue065\"\n#define ICON_MD_PLAYLIST_PLAY u8\"\\ue05f\"\n#define ICON_MD_PLUS_ONE u8\"\\ue800\"\n#define ICON_MD_POLL u8\"\\ue801\"\n#define ICON_MD_POLYMER u8\"\\ue8ab\"\n#define ICON_MD_POOL u8\"\\ueb48\"\n#define ICON_MD_PORTABLE_WIFI_OFF u8\"\\ue0ce\"\n#define ICON_MD_PORTRAIT u8\"\\ue416\"\n#define ICON_MD_POWER u8\"\\ue63c\"\n#define ICON_MD_POWER_INPUT u8\"\\ue336\"\n#define ICON_MD_POWER_SETTINGS_NEW u8\"\\ue8ac\"\n#define ICON_MD_PREGNANT_WOMAN u8\"\\ue91e\"\n#define ICON_MD_PRESENT_TO_ALL u8\"\\ue0df\"\n#define ICON_MD_PRINT u8\"\\ue8ad\"\n#define ICON_MD_PRIORITY_HIGH u8\"\\ue645\"\n#define ICON_MD_PUBLIC u8\"\\ue80b\"\n#define ICON_MD_PUBLISH u8\"\\ue255\"\n#define ICON_MD_QUERY_BUILDER u8\"\\ue8ae\"\n#define ICON_MD_QUESTION_ANSWER u8\"\\ue8af\"\n#define ICON_MD_QUEUE u8\"\\ue03c\"\n#define ICON_MD_QUEUE_MUSIC u8\"\\ue03d\"\n#define ICON_MD_QUEUE_PLAY_NEXT u8\"\\ue066\"\n#define ICON_MD_RADIO u8\"\\ue03e\"\n#define ICON_MD_RADIO_BUTTON_CHECKED u8\"\\ue837\"\n#define ICON_MD_RADIO_BUTTON_UNCHECKED u8\"\\ue836\"\n#define ICON_MD_RATE_REVIEW u8\"\\ue560\"\n#define ICON_MD_RECEIPT u8\"\\ue8b0\"\n#define ICON_MD_RECENT_ACTORS u8\"\\ue03f\"\n#define ICON_MD_RECORD_VOICE_OVER u8\"\\ue91f\"\n#define ICON_MD_REDEEM u8\"\\ue8b1\"\n#define ICON_MD_REDO u8\"\\ue15a\"\n#define ICON_MD_REFRESH u8\"\\ue5d5\"\n#define ICON_MD_REMOVE u8\"\\ue15b\"\n#define ICON_MD_REMOVE_CIRCLE u8\"\\ue15c\"\n#define ICON_MD_REMOVE_CIRCLE_OUTLINE u8\"\\ue15d\"\n#define ICON_MD_REMOVE_FROM_QUEUE u8\"\\ue067\"\n#define ICON_MD_REMOVE_RED_EYE u8\"\\ue417\"\n#define ICON_MD_REMOVE_SHOPPING_CART u8\"\\ue928\"\n#define ICON_MD_REORDER u8\"\\ue8fe\"\n#define ICON_MD_REPEAT u8\"\\ue040\"\n#define ICON_MD_REPEAT_ONE u8\"\\ue041\"\n#define ICON_MD_REPLAY u8\"\\ue042\"\n#define ICON_MD_REPLAY_10 u8\"\\ue059\"\n#define ICON_MD_REPLAY_30 u8\"\\ue05a\"\n#define ICON_MD_REPLAY_5 u8\"\\ue05b\"\n#define ICON_MD_REPLY u8\"\\ue15e\"\n#define ICON_MD_REPLY_ALL u8\"\\ue15f\"\n#define ICON_MD_REPORT u8\"\\ue160\"\n#define ICON_MD_REPORT_PROBLEM u8\"\\ue8b2\"\n#define ICON_MD_RESTAURANT u8\"\\ue56c\"\n#define ICON_MD_RESTAURANT_MENU u8\"\\ue561\"\n#define ICON_MD_RESTORE u8\"\\ue8b3\"\n#define ICON_MD_RESTORE_PAGE u8\"\\ue929\"\n#define ICON_MD_RING_VOLUME u8\"\\ue0d1\"\n#define ICON_MD_ROOM u8\"\\ue8b4\"\n#define ICON_MD_ROOM_SERVICE u8\"\\ueb49\"\n#define ICON_MD_ROTATE_90_DEGREES_CCW u8\"\\ue418\"\n#define ICON_MD_ROTATE_LEFT u8\"\\ue419\"\n#define ICON_MD_ROTATE_RIGHT u8\"\\ue41a\"\n#define ICON_MD_ROUNDED_CORNER u8\"\\ue920\"\n#define ICON_MD_ROUTER u8\"\\ue328\"\n#define ICON_MD_ROWING u8\"\\ue921\"\n#define ICON_MD_RSS_FEED u8\"\\ue0e5\"\n#define ICON_MD_RV_HOOKUP u8\"\\ue642\"\n#define ICON_MD_SATELLITE u8\"\\ue562\"\n#define ICON_MD_SAVE u8\"\\ue161\"\n#define ICON_MD_SCANNER u8\"\\ue329\"\n#define ICON_MD_SCHEDULE u8\"\\ue8b5\"\n#define ICON_MD_SCHOOL u8\"\\ue80c\"\n#define ICON_MD_SCREEN_LOCK_LANDSCAPE u8\"\\ue1be\"\n#define ICON_MD_SCREEN_LOCK_PORTRAIT u8\"\\ue1bf\"\n#define ICON_MD_SCREEN_LOCK_ROTATION u8\"\\ue1c0\"\n#define ICON_MD_SCREEN_ROTATION u8\"\\ue1c1\"\n#define ICON_MD_SCREEN_SHARE u8\"\\ue0e2\"\n#define ICON_MD_SD_CARD u8\"\\ue623\"\n#define ICON_MD_SD_STORAGE u8\"\\ue1c2\"\n#define ICON_MD_SEARCH u8\"\\ue8b6\"\n#define ICON_MD_SECURITY u8\"\\ue32a\"\n#define ICON_MD_SELECT_ALL u8\"\\ue162\"\n#define ICON_MD_SEND u8\"\\ue163\"\n#define ICON_MD_SENTIMENT_DISSATISFIED u8\"\\ue811\"\n#define ICON_MD_SENTIMENT_NEUTRAL u8\"\\ue812\"\n#define ICON_MD_SENTIMENT_SATISFIED u8\"\\ue813\"\n#define ICON_MD_SENTIMENT_VERY_DISSATISFIED u8\"\\ue814\"\n#define ICON_MD_SENTIMENT_VERY_SATISFIED u8\"\\ue815\"\n#define ICON_MD_SETTINGS u8\"\\ue8b8\"\n#define ICON_MD_SETTINGS_APPLICATIONS u8\"\\ue8b9\"\n#define ICON_MD_SETTINGS_BACKUP_RESTORE u8\"\\ue8ba\"\n#define ICON_MD_SETTINGS_BLUETOOTH u8\"\\ue8bb\"\n#define ICON_MD_SETTINGS_BRIGHTNESS u8\"\\ue8bd\"\n#define ICON_MD_SETTINGS_CELL u8\"\\ue8bc\"\n#define ICON_MD_SETTINGS_ETHERNET u8\"\\ue8be\"\n#define ICON_MD_SETTINGS_INPUT_ANTENNA u8\"\\ue8bf\"\n#define ICON_MD_SETTINGS_INPUT_COMPONENT u8\"\\ue8c0\"\n#define ICON_MD_SETTINGS_INPUT_COMPOSITE u8\"\\ue8c1\"\n#define ICON_MD_SETTINGS_INPUT_HDMI u8\"\\ue8c2\"\n#define ICON_MD_SETTINGS_INPUT_SVIDEO u8\"\\ue8c3\"\n#define ICON_MD_SETTINGS_OVERSCAN u8\"\\ue8c4\"\n#define ICON_MD_SETTINGS_PHONE u8\"\\ue8c5\"\n#define ICON_MD_SETTINGS_POWER u8\"\\ue8c6\"\n#define ICON_MD_SETTINGS_REMOTE u8\"\\ue8c7\"\n#define ICON_MD_SETTINGS_SYSTEM_DAYDREAM u8\"\\ue1c3\"\n#define ICON_MD_SETTINGS_VOICE u8\"\\ue8c8\"\n#define ICON_MD_SHARE u8\"\\ue80d\"\n#define ICON_MD_SHOP u8\"\\ue8c9\"\n#define ICON_MD_SHOP_TWO u8\"\\ue8ca\"\n#define ICON_MD_SHOPPING_BASKET u8\"\\ue8cb\"\n#define ICON_MD_SHOPPING_CART u8\"\\ue8cc\"\n#define ICON_MD_SHORT_TEXT u8\"\\ue261\"\n#define ICON_MD_SHOW_CHART u8\"\\ue6e1\"\n#define ICON_MD_SHUFFLE u8\"\\ue043\"\n#define ICON_MD_SIGNAL_CELLULAR_4_BAR u8\"\\ue1c8\"\n#define ICON_MD_SIGNAL_CELLULAR_CONNECTED_NO_INTERNET_4_BAR u8\"\\ue1cd\"\n#define ICON_MD_SIGNAL_CELLULAR_NO_SIM u8\"\\ue1ce\"\n#define ICON_MD_SIGNAL_CELLULAR_NULL u8\"\\ue1cf\"\n#define ICON_MD_SIGNAL_CELLULAR_OFF u8\"\\ue1d0\"\n#define ICON_MD_SIGNAL_WIFI_4_BAR u8\"\\ue1d8\"\n#define ICON_MD_SIGNAL_WIFI_4_BAR_LOCK u8\"\\ue1d9\"\n#define ICON_MD_SIGNAL_WIFI_OFF u8\"\\ue1da\"\n#define ICON_MD_SIM_CARD u8\"\\ue32b\"\n#define ICON_MD_SIM_CARD_ALERT u8\"\\ue624\"\n#define ICON_MD_SKIP_NEXT u8\"\\ue044\"\n#define ICON_MD_SKIP_PREVIOUS u8\"\\ue045\"\n#define ICON_MD_SLIDESHOW u8\"\\ue41b\"\n#define ICON_MD_SLOW_MOTION_VIDEO u8\"\\ue068\"\n#define ICON_MD_SMARTPHONE u8\"\\ue32c\"\n#define ICON_MD_SMOKE_FREE u8\"\\ueb4a\"\n#define ICON_MD_SMOKING_ROOMS u8\"\\ueb4b\"\n#define ICON_MD_SMS u8\"\\ue625\"\n#define ICON_MD_SMS_FAILED u8\"\\ue626\"\n#define ICON_MD_SNOOZE u8\"\\ue046\"\n#define ICON_MD_SORT u8\"\\ue164\"\n#define ICON_MD_SORT_BY_ALPHA u8\"\\ue053\"\n#define ICON_MD_SPA u8\"\\ueb4c\"\n#define ICON_MD_SPACE_BAR u8\"\\ue256\"\n#define ICON_MD_SPEAKER u8\"\\ue32d\"\n#define ICON_MD_SPEAKER_GROUP u8\"\\ue32e\"\n#define ICON_MD_SPEAKER_NOTES u8\"\\ue8cd\"\n#define ICON_MD_SPEAKER_NOTES_OFF u8\"\\ue92a\"\n#define ICON_MD_SPEAKER_PHONE u8\"\\ue0d2\"\n#define ICON_MD_SPELLCHECK u8\"\\ue8ce\"\n#define ICON_MD_STAR u8\"\\ue838\"\n#define ICON_MD_STAR_BORDER u8\"\\ue83a\"\n#define ICON_MD_STAR_HALF u8\"\\ue839\"\n#define ICON_MD_STARS u8\"\\ue8d0\"\n#define ICON_MD_STAY_CURRENT_LANDSCAPE u8\"\\ue0d3\"\n#define ICON_MD_STAY_CURRENT_PORTRAIT u8\"\\ue0d4\"\n#define ICON_MD_STAY_PRIMARY_LANDSCAPE u8\"\\ue0d5\"\n#define ICON_MD_STAY_PRIMARY_PORTRAIT u8\"\\ue0d6\"\n#define ICON_MD_STOP u8\"\\ue047\"\n#define ICON_MD_STOP_SCREEN_SHARE u8\"\\ue0e3\"\n#define ICON_MD_STORAGE u8\"\\ue1db\"\n#define ICON_MD_STORE u8\"\\ue8d1\"\n#define ICON_MD_STORE_MALL_DIRECTORY u8\"\\ue563\"\n#define ICON_MD_STRAIGHTEN u8\"\\ue41c\"\n#define ICON_MD_STREETVIEW u8\"\\ue56e\"\n#define ICON_MD_STRIKETHROUGH_S u8\"\\ue257\"\n#define ICON_MD_STYLE u8\"\\ue41d\"\n#define ICON_MD_SUBDIRECTORY_ARROW_LEFT u8\"\\ue5d9\"\n#define ICON_MD_SUBDIRECTORY_ARROW_RIGHT u8\"\\ue5da\"\n#define ICON_MD_SUBJECT u8\"\\ue8d2\"\n#define ICON_MD_SUBSCRIPTIONS u8\"\\ue064\"\n#define ICON_MD_SUBTITLES u8\"\\ue048\"\n#define ICON_MD_SUBWAY u8\"\\ue56f\"\n#define ICON_MD_SUPERVISOR_ACCOUNT u8\"\\ue8d3\"\n#define ICON_MD_SURROUND_SOUND u8\"\\ue049\"\n#define ICON_MD_SWAP_CALLS u8\"\\ue0d7\"\n#define ICON_MD_SWAP_HORIZ u8\"\\ue8d4\"\n#define ICON_MD_SWAP_VERT u8\"\\ue8d5\"\n#define ICON_MD_SWAP_VERTICAL_CIRCLE u8\"\\ue8d6\"\n#define ICON_MD_SWITCH_CAMERA u8\"\\ue41e\"\n#define ICON_MD_SWITCH_VIDEO u8\"\\ue41f\"\n#define ICON_MD_SYNC u8\"\\ue627\"\n#define ICON_MD_SYNC_DISABLED u8\"\\ue628\"\n#define ICON_MD_SYNC_PROBLEM u8\"\\ue629\"\n#define ICON_MD_SYSTEM_UPDATE u8\"\\ue62a\"\n#define ICON_MD_SYSTEM_UPDATE_ALT u8\"\\ue8d7\"\n#define ICON_MD_TAB u8\"\\ue8d8\"\n#define ICON_MD_TAB_UNSELECTED u8\"\\ue8d9\"\n#define ICON_MD_TABLET u8\"\\ue32f\"\n#define ICON_MD_TABLET_ANDROID u8\"\\ue330\"\n#define ICON_MD_TABLET_MAC u8\"\\ue331\"\n#define ICON_MD_TAG_FACES u8\"\\ue420\"\n#define ICON_MD_TAP_AND_PLAY u8\"\\ue62b\"\n#define ICON_MD_TERRAIN u8\"\\ue564\"\n#define ICON_MD_TEXT_FIELDS u8\"\\ue262\"\n#define ICON_MD_TEXT_FORMAT u8\"\\ue165\"\n#define ICON_MD_TEXTSMS u8\"\\ue0d8\"\n#define ICON_MD_TEXTURE u8\"\\ue421\"\n#define ICON_MD_THEATERS u8\"\\ue8da\"\n#define ICON_MD_THUMB_DOWN u8\"\\ue8db\"\n#define ICON_MD_THUMB_UP u8\"\\ue8dc\"\n#define ICON_MD_THUMBS_UP_DOWN u8\"\\ue8dd\"\n#define ICON_MD_TIME_TO_LEAVE u8\"\\ue62c\"\n#define ICON_MD_TIMELAPSE u8\"\\ue422\"\n#define ICON_MD_TIMELINE u8\"\\ue922\"\n#define ICON_MD_TIMER u8\"\\ue425\"\n#define ICON_MD_TIMER_10 u8\"\\ue423\"\n#define ICON_MD_TIMER_3 u8\"\\ue424\"\n#define ICON_MD_TIMER_OFF u8\"\\ue426\"\n#define ICON_MD_TITLE u8\"\\ue264\"\n#define ICON_MD_TOC u8\"\\ue8de\"\n#define ICON_MD_TODAY u8\"\\ue8df\"\n#define ICON_MD_TOLL u8\"\\ue8e0\"\n#define ICON_MD_TONALITY u8\"\\ue427\"\n#define ICON_MD_TOUCH_APP u8\"\\ue913\"\n#define ICON_MD_TOYS u8\"\\ue332\"\n#define ICON_MD_TRACK_CHANGES u8\"\\ue8e1\"\n#define ICON_MD_TRAFFIC u8\"\\ue565\"\n#define ICON_MD_TRAIN u8\"\\ue570\"\n#define ICON_MD_TRAM u8\"\\ue571\"\n#define ICON_MD_TRANSFER_WITHIN_A_STATION u8\"\\ue572\"\n#define ICON_MD_TRANSFORM u8\"\\ue428\"\n#define ICON_MD_TRANSLATE u8\"\\ue8e2\"\n#define ICON_MD_TRENDING_DOWN u8\"\\ue8e3\"\n#define ICON_MD_TRENDING_FLAT u8\"\\ue8e4\"\n#define ICON_MD_TRENDING_UP u8\"\\ue8e5\"\n#define ICON_MD_TUNE u8\"\\ue429\"\n#define ICON_MD_TURNED_IN u8\"\\ue8e6\"\n#define ICON_MD_TURNED_IN_NOT u8\"\\ue8e7\"\n#define ICON_MD_TV u8\"\\ue333\"\n#define ICON_MD_UNARCHIVE u8\"\\ue169\"\n#define ICON_MD_UNDO u8\"\\ue166\"\n#define ICON_MD_UNFOLD_LESS u8\"\\ue5d6\"\n#define ICON_MD_UNFOLD_MORE u8\"\\ue5d7\"\n#define ICON_MD_UPDATE u8\"\\ue923\"\n#define ICON_MD_USB u8\"\\ue1e0\"\n#define ICON_MD_VERIFIED_USER u8\"\\ue8e8\"\n#define ICON_MD_VERTICAL_ALIGN_BOTTOM u8\"\\ue258\"\n#define ICON_MD_VERTICAL_ALIGN_CENTER u8\"\\ue259\"\n#define ICON_MD_VERTICAL_ALIGN_TOP u8\"\\ue25a\"\n#define ICON_MD_VIBRATION u8\"\\ue62d\"\n#define ICON_MD_VIDEO_CALL u8\"\\ue070\"\n#define ICON_MD_VIDEO_LABEL u8\"\\ue071\"\n#define ICON_MD_VIDEO_LIBRARY u8\"\\ue04a\"\n#define ICON_MD_VIDEOCAM u8\"\\ue04b\"\n#define ICON_MD_VIDEOCAM_OFF u8\"\\ue04c\"\n#define ICON_MD_VIDEOGAME_ASSET u8\"\\ue338\"\n#define ICON_MD_VIEW_AGENDA u8\"\\ue8e9\"\n#define ICON_MD_VIEW_ARRAY u8\"\\ue8ea\"\n#define ICON_MD_VIEW_CAROUSEL u8\"\\ue8eb\"\n#define ICON_MD_VIEW_COLUMN u8\"\\ue8ec\"\n#define ICON_MD_VIEW_COMFY u8\"\\ue42a\"\n#define ICON_MD_VIEW_COMPACT u8\"\\ue42b\"\n#define ICON_MD_VIEW_DAY u8\"\\ue8ed\"\n#define ICON_MD_VIEW_HEADLINE u8\"\\ue8ee\"\n#define ICON_MD_VIEW_LIST u8\"\\ue8ef\"\n#define ICON_MD_VIEW_MODULE u8\"\\ue8f0\"\n#define ICON_MD_VIEW_QUILT u8\"\\ue8f1\"\n#define ICON_MD_VIEW_STREAM u8\"\\ue8f2\"\n#define ICON_MD_VIEW_WEEK u8\"\\ue8f3\"\n#define ICON_MD_VIGNETTE u8\"\\ue435\"\n#define ICON_MD_VISIBILITY u8\"\\ue8f4\"\n#define ICON_MD_VISIBILITY_OFF u8\"\\ue8f5\"\n#define ICON_MD_VOICE_CHAT u8\"\\ue62e\"\n#define ICON_MD_VOICEMAIL u8\"\\ue0d9\"\n#define ICON_MD_VOLUME_DOWN u8\"\\ue04d\"\n#define ICON_MD_VOLUME_MUTE u8\"\\ue04e\"\n#define ICON_MD_VOLUME_OFF u8\"\\ue04f\"\n#define ICON_MD_VOLUME_UP u8\"\\ue050\"\n#define ICON_MD_VPN_KEY u8\"\\ue0da\"\n#define ICON_MD_VPN_LOCK u8\"\\ue62f\"\n#define ICON_MD_WALLPAPER u8\"\\ue1bc\"\n#define ICON_MD_WARNING u8\"\\ue002\"\n#define ICON_MD_WATCH u8\"\\ue334\"\n#define ICON_MD_WATCH_LATER u8\"\\ue924\"\n#define ICON_MD_WB_AUTO u8\"\\ue42c\"\n#define ICON_MD_WB_CLOUDY u8\"\\ue42d\"\n#define ICON_MD_WB_INCANDESCENT u8\"\\ue42e\"\n#define ICON_MD_WB_IRIDESCENT u8\"\\ue436\"\n#define ICON_MD_WB_SUNNY u8\"\\ue430\"\n#define ICON_MD_WC u8\"\\ue63d\"\n#define ICON_MD_WEB u8\"\\ue051\"\n#define ICON_MD_WEB_ASSET u8\"\\ue069\"\n#define ICON_MD_WEEKEND u8\"\\ue16b\"\n#define ICON_MD_WHATSHOT u8\"\\ue80e\"\n#define ICON_MD_WIDGETS u8\"\\ue1bd\"\n#define ICON_MD_WIFI u8\"\\ue63e\"\n#define ICON_MD_WIFI_LOCK u8\"\\ue1e1\"\n#define ICON_MD_WIFI_TETHERING u8\"\\ue1e2\"\n#define ICON_MD_WORK u8\"\\ue8f9\"\n#define ICON_MD_WRAP_TEXT u8\"\\ue25b\"\n#define ICON_MD_YOUTUBE_SEARCHED_FOR u8\"\\ue8fa\"\n#define ICON_MD_ZOOM_IN u8\"\\ue8ff\"\n#define ICON_MD_ZOOM_OUT u8\"\\ue900\"\n#define ICON_MD_ZOOM_OUT_MAP u8\"\\ue56b\"\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/ImGuiColorTextEdit/.gitignore",
    "content": "# Prerequisites\n*.d\n\n# Compiled Object files\n*.slo\n*.lo\n*.o\n*.obj\n\n# Precompiled Headers\n*.gch\n*.pch\n\n# Compiled Dynamic libraries\n*.so\n*.dylib\n*.dll\n\n# Fortran module files\n*.mod\n*.smod\n\n# Compiled Static libraries\n*.lai\n*.la\n*.a\n*.lib\n\n# Executables\n*.exe\n*.out\n*.app\nTextEditor.cpp.bak\n*.bak\nSave/TextEditor.h\nSave/TextEditor.cpp\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/ImGuiColorTextEdit/CONTRIBUTING",
    "content": "# Contributing\nPull requests are welcome, feel free to contribute if you have implemented something which might be useful for the general audience of this little piece of software. Apparently, it became kind of a community project now. :)\n\nWhem contributing, please follow the following guidelines. I will keep it updated as we bump into something which worth doing better.\n- Try to follow the same coding and naming conventions you find in the source already. I know that everyone has its own preference/taste in coding, but please keep the source consistent in style.\n- Please submit to the 'dev' branch first for testing, and it will be merged to 'main' if it seems to work fine. I would like try keep 'master' in a good working condition, as more and more people are using it.\n- Please send your submissions in small, well defined requests, i. e. do not accumulate many unrelated changes in one large pull request. Keep your submissions as small as possible, it will make everyone's life easier.\n- Avoid using ImGui internal since it would make the source fragile against internal changes in ImGui.\n- Try to keep the perormance high within the render function. Try to avoid doing anything which leads to memory allocations (like using temporary std::string, std::vector variables), or complex algorithm. If you really have to, try to amortise it between frames.\n\nThank you. :)\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/ImGuiColorTextEdit/LICENSE",
    "content": "MIT License\n\nCopyright (c) 2017 BalazsJako\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/ImGuiColorTextEdit/README.md",
    "content": "# ImGuiColorTextEdit\nSyntax highlighting text editor for ImGui\n\n![Screenshot](https://github.com/BalazsJako/ImGuiColorTextEdit/wiki/ImGuiTextEdit.png \"Screenshot\")\n\nDemo project: https://github.com/BalazsJako/ColorTextEditorDemo\n\nThis started as my attempt to write a relatively simple widget which provides text editing functionality with syntax highlighting. Now there are other contributors who provide valuable additions.\n\nWhile it relies on Omar Cornut's https://github.com/ocornut/imgui, it does not follow the \"pure\" one widget - one function approach. Since the editor has to maintain a relatively complex and large internal state, it did not seem to be practical to try and enforce fully immediate mode. It stores its internal state in an object instance which is reused across frames.\n\nThe code is (still) work in progress, please report if you find any issues.\n\n# Main features\n - approximates typical code editor look and feel (essential mouse/keyboard commands work - I mean, the commands _I_ normally use :))\n - undo/redo\n - UTF-8 support\n - works with both fixed and variable-width fonts\n - extensible syntax highlighting for multiple languages\n - identifier declarations: a small piece of description can be associated with an identifier. The editor displays it in a tooltip when the mouse cursor is hovered over the identifier\n - error markers: the user can specify a list of error messages together the line of occurence, the editor will highligh the lines with red backround and display error message in a tooltip when the mouse cursor is hovered over the line\n - large files: there is no explicit limit set on file size or number of lines (below 2GB, performance is not affected when large files are loaded (except syntax coloring, see below)\n - color palette support: you can switch between different color palettes, or even define your own\n - whitespace indicators (TAB, space)\n \n# Known issues\n - syntax highligthing of most languages - except C/C++ - is based on std::regex, which is diasppointingly slow. Because of that, the highlighting process is amortized between multiple frames. C/C++ has a hand-written tokenizer which is much faster. \n \nPlease post your screenshots if you find this little piece of software useful. :)\n\n# Contribute\n\nIf you want to contribute, please refer to CONTRIBUTE file.\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/ImGuiColorTextEdit/TextEditor.cpp",
    "content": "#include <algorithm>\n#include <chrono>\n#include <string>\n#include <regex>\n#include <cmath>\n\n#include \"TextEditor.h\"\n\n#define IMGUI_DEFINE_MATH_OPERATORS\n#include \"imgui/imgui.h\" // for imGui::GetCurrentWindow()\n\n// TODO\n// - multiline comments vs single-line: latter is blocking start of a ML\n\ntemplate<class InputIt1, class InputIt2, class BinaryPredicate>\nbool equals(InputIt1 first1, InputIt1 last1,\n\tInputIt2 first2, InputIt2 last2, BinaryPredicate p)\n{\n\tfor (; first1 != last1 && first2 != last2; ++first1, ++first2)\n\t{\n\t\tif (!p(*first1, *first2))\n\t\t\treturn false;\n\t}\n\treturn first1 == last1 && first2 == last2;\n}\n\nTextEditor::TextEditor()\n\t: mLineSpacing(1.0f)\n\t, mUndoIndex(0)\n\t, mTabSize(4)\n\t, mOverwrite(false)\n\t, mReadOnly(false)\n\t, mWithinRender(false)\n\t, mScrollToCursor(false)\n\t, mScrollToTop(false)\n\t, mTextChanged(false)\n\t, mColorizerEnabled(true)\n\t, mTextStart(20.0f)\n\t, mLeftMargin(10)\n\t, mCursorPositionChanged(false)\n\t, mColorRangeMin(0)\n\t, mColorRangeMax(0)\n\t, mSelectionMode(SelectionMode::Normal)\n\t, mCheckComments(true)\n\t, mLastClick(-1.0f)\n\t, mHandleKeyboardInputs(true)\n\t, mHandleMouseInputs(true)\n\t, mIgnoreImGuiChild(false)\n\t, mShowWhitespaces(true)\n\t, mStartTime(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count())\n{\n\tSetPalette(GetDarkPalette());\n\tSetLanguageDefinition(LanguageDefinition::HLSL());\n\tmLines.push_back(Line());\n}\n\nTextEditor::~TextEditor()\n{\n}\n\nvoid TextEditor::SetLanguageDefinition(const LanguageDefinition & aLanguageDef)\n{\n\tmLanguageDefinition = aLanguageDef;\n\tmRegexList.clear();\n\n\tfor (auto& r : mLanguageDefinition.mTokenRegexStrings)\n\t\tmRegexList.push_back(std::make_pair(std::regex(r.first, std::regex_constants::optimize), r.second));\n\n\tColorize();\n}\n\nvoid TextEditor::SetPalette(const Palette & aValue)\n{\n\tmPaletteBase = aValue;\n}\n\nstd::string TextEditor::GetText(const Coordinates & aStart, const Coordinates & aEnd) const\n{\n\tstd::string result;\n\n\tauto lstart = aStart.mLine;\n\tauto lend = aEnd.mLine;\n\tauto istart = GetCharacterIndex(aStart);\n\tauto iend = GetCharacterIndex(aEnd);\n\tsize_t s = 0;\n\n\tfor (size_t i = lstart; i < lend; i++)\n\t\ts += mLines[i].size();\n\n\tresult.reserve(s + s / 8);\n\n\twhile (istart < iend || lstart < lend)\n\t{\n\t\tif (lstart >= (int)mLines.size())\n\t\t\tbreak;\n\n\t\tauto& line = mLines[lstart];\n\t\tif (istart < (int)line.size())\n\t\t{\n\t\t\tresult += line[istart].mChar;\n\t\t\tistart++;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tistart = 0;\n\t\t\t++lstart;\n\t\t\tresult += '\\n';\n\t\t}\n\t}\n\n\treturn result;\n}\n\nTextEditor::Coordinates TextEditor::GetActualCursorCoordinates() const\n{\n\treturn SanitizeCoordinates(mState.mCursorPosition);\n}\n\nTextEditor::Coordinates TextEditor::SanitizeCoordinates(const Coordinates & aValue) const\n{\n\tauto line = aValue.mLine;\n\tauto column = aValue.mColumn;\n\tif (line >= (int)mLines.size())\n\t{\n\t\tif (mLines.empty())\n\t\t{\n\t\t\tline = 0;\n\t\t\tcolumn = 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tline = (int)mLines.size() - 1;\n\t\t\tcolumn = GetLineMaxColumn(line);\n\t\t}\n\t\treturn Coordinates(line, column);\n\t}\n\telse\n\t{\n\t\tcolumn = mLines.empty() ? 0 : std::min(column, GetLineMaxColumn(line));\n\t\treturn Coordinates(line, column);\n\t}\n}\n\n// https://en.wikipedia.org/wiki/UTF-8\n// We assume that the char is a standalone character (<128) or a leading byte of an UTF-8 code sequence (non-10xxxxxx code)\nstatic int UTF8CharLength(TextEditor::Char c)\n{\n\tif ((c & 0xFE) == 0xFC)\n\t\treturn 6;\n\tif ((c & 0xFC) == 0xF8)\n\t\treturn 5;\n\tif ((c & 0xF8) == 0xF0)\n\t\treturn 4;\n\telse if ((c & 0xF0) == 0xE0)\n\t\treturn 3;\n\telse if ((c & 0xE0) == 0xC0)\n\t\treturn 2;\n\treturn 1;\n}\n\n// \"Borrowed\" from ImGui source\nstatic inline int ImTextCharToUtf8(char* buf, int buf_size, unsigned int c)\n{\n\tif (c < 0x80)\n\t{\n\t\tbuf[0] = (char)c;\n\t\treturn 1;\n\t}\n\tif (c < 0x800)\n\t{\n\t\tif (buf_size < 2) return 0;\n\t\tbuf[0] = (char)(0xc0 + (c >> 6));\n\t\tbuf[1] = (char)(0x80 + (c & 0x3f));\n\t\treturn 2;\n\t}\n\tif (c >= 0xdc00 && c < 0xe000)\n\t{\n\t\treturn 0;\n\t}\n\tif (c >= 0xd800 && c < 0xdc00)\n\t{\n\t\tif (buf_size < 4) return 0;\n\t\tbuf[0] = (char)(0xf0 + (c >> 18));\n\t\tbuf[1] = (char)(0x80 + ((c >> 12) & 0x3f));\n\t\tbuf[2] = (char)(0x80 + ((c >> 6) & 0x3f));\n\t\tbuf[3] = (char)(0x80 + ((c) & 0x3f));\n\t\treturn 4;\n\t}\n\t//else if (c < 0x10000)\n\t{\n\t\tif (buf_size < 3) return 0;\n\t\tbuf[0] = (char)(0xe0 + (c >> 12));\n\t\tbuf[1] = (char)(0x80 + ((c >> 6) & 0x3f));\n\t\tbuf[2] = (char)(0x80 + ((c) & 0x3f));\n\t\treturn 3;\n\t}\n}\n\nvoid TextEditor::Advance(Coordinates & aCoordinates) const\n{\n\tif (aCoordinates.mLine < (int)mLines.size())\n\t{\n\t\tauto& line = mLines[aCoordinates.mLine];\n\t\tauto cindex = GetCharacterIndex(aCoordinates);\n\n\t\tif (cindex + 1 < (int)line.size())\n\t\t{\n\t\t\tauto delta = UTF8CharLength(line[cindex].mChar);\n\t\t\tcindex = std::min(cindex + delta, (int)line.size() - 1);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t++aCoordinates.mLine;\n\t\t\tcindex = 0;\n\t\t}\n\t\taCoordinates.mColumn = GetCharacterColumn(aCoordinates.mLine, cindex);\n\t}\n}\n\nvoid TextEditor::DeleteRange(const Coordinates & aStart, const Coordinates & aEnd)\n{\n\tassert(aEnd >= aStart);\n\tassert(!mReadOnly);\n\n\t//printf(\"D(%d.%d)-(%d.%d)\\n\", aStart.mLine, aStart.mColumn, aEnd.mLine, aEnd.mColumn);\n\n\tif (aEnd == aStart)\n\t\treturn;\n\n\tauto start = GetCharacterIndex(aStart);\n\tauto end = GetCharacterIndex(aEnd);\n\n\tif (aStart.mLine == aEnd.mLine)\n\t{\n\t\tauto& line = mLines[aStart.mLine];\n\t\tauto n = GetLineMaxColumn(aStart.mLine);\n\t\tif (aEnd.mColumn >= n)\n\t\t\tline.erase(line.begin() + start, line.end());\n\t\telse\n\t\t\tline.erase(line.begin() + start, line.begin() + end);\n\t}\n\telse\n\t{\n\t\tauto& firstLine = mLines[aStart.mLine];\n\t\tauto& lastLine = mLines[aEnd.mLine];\n\n\t\tfirstLine.erase(firstLine.begin() + start, firstLine.end());\n\t\tlastLine.erase(lastLine.begin(), lastLine.begin() + end);\n\n\t\tif (aStart.mLine < aEnd.mLine)\n\t\t\tfirstLine.insert(firstLine.end(), lastLine.begin(), lastLine.end());\n\n\t\tif (aStart.mLine < aEnd.mLine)\n\t\t\tRemoveLine(aStart.mLine + 1, aEnd.mLine + 1);\n\t}\n\n\tmTextChanged = true;\n}\n\nint TextEditor::InsertTextAt(Coordinates& /* inout */ aWhere, const char * aValue)\n{\n\tassert(!mReadOnly);\n\n\tint cindex = GetCharacterIndex(aWhere);\n\tint totalLines = 0;\n\twhile (*aValue != '\\0')\n\t{\n\t\tassert(!mLines.empty());\n\n\t\tif (*aValue == '\\r')\n\t\t{\n\t\t\t// skip\n\t\t\t++aValue;\n\t\t}\n\t\telse if (*aValue == '\\n')\n\t\t{\n\t\t\tif (cindex < (int)mLines[aWhere.mLine].size())\n\t\t\t{\n\t\t\t\tauto& newLine = InsertLine(aWhere.mLine + 1);\n\t\t\t\tauto& line = mLines[aWhere.mLine];\n\t\t\t\tnewLine.insert(newLine.begin(), line.begin() + cindex, line.end());\n\t\t\t\tline.erase(line.begin() + cindex, line.end());\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tInsertLine(aWhere.mLine + 1);\n\t\t\t}\n\t\t\t++aWhere.mLine;\n\t\t\taWhere.mColumn = 0;\n\t\t\tcindex = 0;\n\t\t\t++totalLines;\n\t\t\t++aValue;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tauto& line = mLines[aWhere.mLine];\n\t\t\tauto d = UTF8CharLength(*aValue);\n\t\t\twhile (d-- > 0 && *aValue != '\\0')\n\t\t\t\tline.insert(line.begin() + cindex++, Glyph(*aValue++, PaletteIndex::Default));\n\t\t\t++aWhere.mColumn;\n\t\t}\n\n\t\tmTextChanged = true;\n\t}\n\n\treturn totalLines;\n}\n\nvoid TextEditor::AddUndo(UndoRecord& aValue)\n{\n\tassert(!mReadOnly);\n\t//printf(\"AddUndo: (@%d.%d) +\\'%s' [%d.%d .. %d.%d], -\\'%s', [%d.%d .. %d.%d] (@%d.%d)\\n\",\n\t//\taValue.mBefore.mCursorPosition.mLine, aValue.mBefore.mCursorPosition.mColumn,\n\t//\taValue.mAdded.c_str(), aValue.mAddedStart.mLine, aValue.mAddedStart.mColumn, aValue.mAddedEnd.mLine, aValue.mAddedEnd.mColumn,\n\t//\taValue.mRemoved.c_str(), aValue.mRemovedStart.mLine, aValue.mRemovedStart.mColumn, aValue.mRemovedEnd.mLine, aValue.mRemovedEnd.mColumn,\n\t//\taValue.mAfter.mCursorPosition.mLine, aValue.mAfter.mCursorPosition.mColumn\n\t//\t);\n\n\tmUndoBuffer.resize((size_t)(mUndoIndex + 1));\n\tmUndoBuffer.back() = aValue;\n\t++mUndoIndex;\n}\n\nTextEditor::Coordinates TextEditor::ScreenPosToCoordinates(const ImVec2& aPosition) const\n{\n\tImVec2 origin = ImGui::GetCursorScreenPos();\n\tImVec2 local(aPosition.x - origin.x, aPosition.y - origin.y);\n\n\tint lineNo = std::max(0, (int)floor(local.y / mCharAdvance.y));\n\n\tint columnCoord = 0;\n\n\tif (lineNo >= 0 && lineNo < (int)mLines.size())\n\t{\n\t\tauto& line = mLines.at(lineNo);\n\n\t\tint columnIndex = 0;\n\t\tfloat columnX = 0.0f;\n\n\t\twhile ((size_t)columnIndex < line.size())\n\t\t{\n\t\t\tfloat columnWidth = 0.0f;\n\n\t\t\tif (line[columnIndex].mChar == '\\t')\n\t\t\t{\n\t\t\t\tfloat spaceSize = ImGui::GetFont()->CalcTextSizeA(ImGui::GetFontSize(), FLT_MAX, -1.0f, \" \").x;\n\t\t\t\tfloat oldX = columnX;\n\t\t\t\tfloat newColumnX = (1.0f + std::floor((1.0f + columnX) / (float(mTabSize) * spaceSize))) * (float(mTabSize) * spaceSize);\n\t\t\t\tcolumnWidth = newColumnX - oldX;\n\t\t\t\tif (mTextStart + columnX + columnWidth * 0.5f > local.x)\n\t\t\t\t\tbreak;\n\t\t\t\tcolumnX = newColumnX;\n\t\t\t\tcolumnCoord = (columnCoord / mTabSize) * mTabSize + mTabSize;\n\t\t\t\tcolumnIndex++;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tchar buf[7];\n\t\t\t\tauto d = UTF8CharLength(line[columnIndex].mChar);\n\t\t\t\tint i = 0;\n\t\t\t\twhile (i < 6 && d-- > 0)\n\t\t\t\t\tbuf[i++] = line[columnIndex++].mChar;\n\t\t\t\tbuf[i] = '\\0';\n\t\t\t\tcolumnWidth = ImGui::GetFont()->CalcTextSizeA(ImGui::GetFontSize(), FLT_MAX, -1.0f, buf).x;\n\t\t\t\tif (mTextStart + columnX + columnWidth * 0.5f > local.x)\n\t\t\t\t\tbreak;\n\t\t\t\tcolumnX += columnWidth;\n\t\t\t\tcolumnCoord++;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn SanitizeCoordinates(Coordinates(lineNo, columnCoord));\n}\n\nTextEditor::Coordinates TextEditor::FindWordStart(const Coordinates & aFrom) const\n{\n\tCoordinates at = aFrom;\n\tif (at.mLine >= (int)mLines.size())\n\t\treturn at;\n\n\tauto& line = mLines[at.mLine];\n\tauto cindex = GetCharacterIndex(at);\n\n\tif (cindex >= (int)line.size())\n\t\treturn at;\n\n\twhile (cindex > 0 && isspace(line[cindex].mChar))\n\t\t--cindex;\n\n\tauto cstart = (PaletteIndex)line[cindex].mColorIndex;\n\twhile (cindex > 0)\n\t{\n\t\tauto c = line[cindex].mChar;\n\t\tif ((c & 0xC0) != 0x80)\t// not UTF code sequence 10xxxxxx\n\t\t{\n\t\t\tif (c <= 32 && isspace(c))\n\t\t\t{\n\t\t\t\tcindex++;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (cstart != (PaletteIndex)line[size_t(cindex - 1)].mColorIndex)\n\t\t\t\tbreak;\n\t\t}\n\t\t--cindex;\n\t}\n\treturn Coordinates(at.mLine, GetCharacterColumn(at.mLine, cindex));\n}\n\nTextEditor::Coordinates TextEditor::FindWordEnd(const Coordinates & aFrom) const\n{\n\tCoordinates at = aFrom;\n\tif (at.mLine >= (int)mLines.size())\n\t\treturn at;\n\n\tauto& line = mLines[at.mLine];\n\tauto cindex = GetCharacterIndex(at);\n\n\tif (cindex >= (int)line.size())\n\t\treturn at;\n\n\tbool prevspace = (bool)isspace(line[cindex].mChar);\n\tauto cstart = (PaletteIndex)line[cindex].mColorIndex;\n\twhile (cindex < (int)line.size())\n\t{\n\t\tauto c = line[cindex].mChar;\n\t\tauto d = UTF8CharLength(c);\n\t\tif (cstart != (PaletteIndex)line[cindex].mColorIndex)\n\t\t\tbreak;\n\n\t\tif (prevspace != !!isspace(c))\n\t\t{\n\t\t\tif (isspace(c))\n\t\t\t\twhile (cindex < (int)line.size() && isspace(line[cindex].mChar))\n\t\t\t\t\t++cindex;\n\t\t\tbreak;\n\t\t}\n\t\tcindex += d;\n\t}\n\treturn Coordinates(aFrom.mLine, GetCharacterColumn(aFrom.mLine, cindex));\n}\n\nTextEditor::Coordinates TextEditor::FindNextWord(const Coordinates & aFrom) const\n{\n\tCoordinates at = aFrom;\n\tif (at.mLine >= (int)mLines.size())\n\t\treturn at;\n\n\t// skip to the next non-word character\n\tauto cindex = GetCharacterIndex(aFrom);\n\tbool isword = false;\n\tbool skip = false;\n\tif (cindex < (int)mLines[at.mLine].size())\n\t{\n\t\tauto& line = mLines[at.mLine];\n\t\tisword = isalnum(line[cindex].mChar);\n\t\tskip = isword;\n\t}\n\n\twhile (!isword || skip)\n\t{\n\t\tif (at.mLine >= mLines.size())\n\t\t{\n\t\t\tauto l = std::max(0, (int) mLines.size() - 1);\n\t\t\treturn Coordinates(l, GetLineMaxColumn(l));\n\t\t}\n\n\t\tauto& line = mLines[at.mLine];\n\t\tif (cindex < (int)line.size())\n\t\t{\n\t\t\tisword = isalnum(line[cindex].mChar);\n\n\t\t\tif (isword && !skip)\n\t\t\t\treturn Coordinates(at.mLine, GetCharacterColumn(at.mLine, cindex));\n\n\t\t\tif (!isword)\n\t\t\t\tskip = false;\n\n\t\t\tcindex++;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcindex = 0;\n\t\t\t++at.mLine;\n\t\t\tskip = false;\n\t\t\tisword = false;\n\t\t}\n\t}\n\n\treturn at;\n}\n\nint TextEditor::GetCharacterIndex(const Coordinates& aCoordinates) const\n{\n\tif (aCoordinates.mLine >= mLines.size())\n\t\treturn -1;\n\tauto& line = mLines[aCoordinates.mLine];\n\tint c = 0;\n\tint i = 0;\n\tfor (; i < line.size() && c < aCoordinates.mColumn;)\n\t{\n\t\tif (line[i].mChar == '\\t')\n\t\t\tc = (c / mTabSize) * mTabSize + mTabSize;\n\t\telse\n\t\t\t++c;\n\t\ti += UTF8CharLength(line[i].mChar);\n\t}\n\treturn i;\n}\n\nint TextEditor::GetCharacterColumn(int aLine, int aIndex) const\n{\n\tif (aLine >= mLines.size())\n\t\treturn 0;\n\tauto& line = mLines[aLine];\n\tint col = 0;\n\tint i = 0;\n\twhile (i < aIndex && i < (int)line.size())\n\t{\n\t\tauto c = line[i].mChar;\n\t\ti += UTF8CharLength(c);\n\t\tif (c == '\\t')\n\t\t\tcol = (col / mTabSize) * mTabSize + mTabSize;\n\t\telse\n\t\t\tcol++;\n\t}\n\treturn col;\n}\n\nint TextEditor::GetLineCharacterCount(int aLine) const\n{\n\tif (aLine >= mLines.size())\n\t\treturn 0;\n\tauto& line = mLines[aLine];\n\tint c = 0;\n\tfor (unsigned i = 0; i < line.size(); c++)\n\t\ti += UTF8CharLength(line[i].mChar);\n\treturn c;\n}\n\nint TextEditor::GetLineMaxColumn(int aLine) const\n{\n\tif (aLine >= mLines.size())\n\t\treturn 0;\n\tauto& line = mLines[aLine];\n\tint col = 0;\n\tfor (unsigned i = 0; i < line.size(); )\n\t{\n\t\tauto c = line[i].mChar;\n\t\tif (c == '\\t')\n\t\t\tcol = (col / mTabSize) * mTabSize + mTabSize;\n\t\telse\n\t\t\tcol++;\n\t\ti += UTF8CharLength(c);\n\t}\n\treturn col;\n}\n\nbool TextEditor::IsOnWordBoundary(const Coordinates & aAt) const\n{\n\tif (aAt.mLine >= (int)mLines.size() || aAt.mColumn == 0)\n\t\treturn true;\n\n\tauto& line = mLines[aAt.mLine];\n\tauto cindex = GetCharacterIndex(aAt);\n\tif (cindex >= (int)line.size())\n\t\treturn true;\n\n\tif (mColorizerEnabled)\n\t\treturn line[cindex].mColorIndex != line[size_t(cindex - 1)].mColorIndex;\n\n\treturn isspace(line[cindex].mChar) != isspace(line[cindex - 1].mChar);\n}\n\nvoid TextEditor::RemoveLine(int aStart, int aEnd)\n{\n\tassert(!mReadOnly);\n\tassert(aEnd >= aStart);\n\tassert(mLines.size() > (size_t)(aEnd - aStart));\n\n\tErrorMarkers etmp;\n\tfor (auto& i : mErrorMarkers)\n\t{\n\t\tErrorMarkers::value_type e(i.first >= aStart ? i.first - 1 : i.first, i.second);\n\t\tif (e.first >= aStart && e.first <= aEnd)\n\t\t\tcontinue;\n\t\tetmp.insert(e);\n\t}\n\tmErrorMarkers = std::move(etmp);\n\n\tBreakpoints btmp;\n\tfor (auto i : mBreakpoints)\n\t{\n\t\tif (i >= aStart && i <= aEnd)\n\t\t\tcontinue;\n\t\tbtmp.insert(i >= aStart ? i - 1 : i);\n\t}\n\tmBreakpoints = std::move(btmp);\n\n\tmLines.erase(mLines.begin() + aStart, mLines.begin() + aEnd);\n\tassert(!mLines.empty());\n\n\tmTextChanged = true;\n}\n\nvoid TextEditor::RemoveLine(int aIndex)\n{\n\tassert(!mReadOnly);\n\tassert(mLines.size() > 1);\n\n\tErrorMarkers etmp;\n\tfor (auto& i : mErrorMarkers)\n\t{\n\t\tErrorMarkers::value_type e(i.first > aIndex ? i.first - 1 : i.first, i.second);\n\t\tif (e.first - 1 == aIndex)\n\t\t\tcontinue;\n\t\tetmp.insert(e);\n\t}\n\tmErrorMarkers = std::move(etmp);\n\n\tBreakpoints btmp;\n\tfor (auto i : mBreakpoints)\n\t{\n\t\tif (i == aIndex)\n\t\t\tcontinue;\n\t\tbtmp.insert(i >= aIndex ? i - 1 : i);\n\t}\n\tmBreakpoints = std::move(btmp);\n\n\tmLines.erase(mLines.begin() + aIndex);\n\tassert(!mLines.empty());\n\n\tmTextChanged = true;\n}\n\nTextEditor::Line& TextEditor::InsertLine(int aIndex)\n{\n\tassert(!mReadOnly);\n\n\tauto& result = *mLines.insert(mLines.begin() + aIndex, Line());\n\n\tErrorMarkers etmp;\n\tfor (auto& i : mErrorMarkers)\n\t\tetmp.insert(ErrorMarkers::value_type(i.first >= aIndex ? i.first + 1 : i.first, i.second));\n\tmErrorMarkers = std::move(etmp);\n\n\tBreakpoints btmp;\n\tfor (auto i : mBreakpoints)\n\t\tbtmp.insert(i >= aIndex ? i + 1 : i);\n\tmBreakpoints = std::move(btmp);\n\n\treturn result;\n}\n\nstd::string TextEditor::GetWordUnderCursor() const\n{\n\tauto c = GetCursorPosition();\n\treturn GetWordAt(c);\n}\n\nstd::string TextEditor::GetWordAt(const Coordinates & aCoords) const\n{\n\tauto start = FindWordStart(aCoords);\n\tauto end = FindWordEnd(aCoords);\n\n\tstd::string r;\n\n\tauto istart = GetCharacterIndex(start);\n\tauto iend = GetCharacterIndex(end);\n\n\tfor (auto it = istart; it < iend; ++it)\n\t\tr.push_back(mLines[aCoords.mLine][it].mChar);\n\n\treturn r;\n}\n\nImU32 TextEditor::GetGlyphColor(const Glyph & aGlyph) const\n{\n\tif (!mColorizerEnabled)\n\t\treturn mPalette[(int)PaletteIndex::Default];\n\tif (aGlyph.mComment)\n\t\treturn mPalette[(int)PaletteIndex::Comment];\n\tif (aGlyph.mMultiLineComment)\n\t\treturn mPalette[(int)PaletteIndex::MultiLineComment];\n\tauto const color = mPalette[(int)aGlyph.mColorIndex];\n\tif (aGlyph.mPreprocessor)\n\t{\n\t\tconst auto ppcolor = mPalette[(int)PaletteIndex::Preprocessor];\n\t\tconst int c0 = ((ppcolor & 0xff) + (color & 0xff)) / 2;\n\t\tconst int c1 = (((ppcolor >> 8) & 0xff) + ((color >> 8) & 0xff)) / 2;\n\t\tconst int c2 = (((ppcolor >> 16) & 0xff) + ((color >> 16) & 0xff)) / 2;\n\t\tconst int c3 = (((ppcolor >> 24) & 0xff) + ((color >> 24) & 0xff)) / 2;\n\t\treturn ImU32(c0 | (c1 << 8) | (c2 << 16) | (c3 << 24));\n\t}\n\treturn color;\n}\n\nvoid TextEditor::HandleKeyboardInputs()\n{\n\tImGuiIO& io = ImGui::GetIO();\n\tauto shift = io.KeyShift;\n\tauto ctrl = io.ConfigMacOSXBehaviors ? io.KeySuper : io.KeyCtrl;\n\tauto alt = io.ConfigMacOSXBehaviors ? io.KeyCtrl : io.KeyAlt;\n\n\tif (ImGui::IsWindowFocused())\n\t{\n\t\tif (ImGui::IsWindowHovered())\n\t\t\tImGui::SetMouseCursor(ImGuiMouseCursor_TextInput);\n\t\t//ImGui::CaptureKeyboardFromApp(true);\n\n\t\tio.WantCaptureKeyboard = true;\n\t\tio.WantTextInput = true;\n\n\t\tif (!IsReadOnly() && ctrl && !shift && !alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_Z)))\n\t\t\tUndo();\n\t\telse if (!IsReadOnly() && !ctrl && !shift && alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_Backspace)))\n\t\t\tUndo();\n\t\telse if (!IsReadOnly() && ctrl && !shift && !alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_Y)))\n\t\t\tRedo();\n\t\telse if (!ctrl && !alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_UpArrow)))\n\t\t\tMoveUp(1, shift);\n\t\telse if (!ctrl && !alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_DownArrow)))\n\t\t\tMoveDown(1, shift);\n\t\telse if (!alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_LeftArrow)))\n\t\t\tMoveLeft(1, shift, ctrl);\n\t\telse if (!alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_RightArrow)))\n\t\t\tMoveRight(1, shift, ctrl);\n\t\telse if (!alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_PageUp)))\n\t\t\tMoveUp(GetPageSize() - 4, shift);\n\t\telse if (!alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_PageDown)))\n\t\t\tMoveDown(GetPageSize() - 4, shift);\n\t\telse if (!alt && ctrl && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_Home)))\n\t\t\tMoveTop(shift);\n\t\telse if (ctrl && !alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_End)))\n\t\t\tMoveBottom(shift);\n\t\telse if (!ctrl && !alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_Home)))\n\t\t\tMoveHome(shift);\n\t\telse if (!ctrl && !alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_End)))\n\t\t\tMoveEnd(shift);\n\t\telse if (!IsReadOnly() && !ctrl && !shift && !alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_Delete)))\n\t\t\tDelete();\n\t\telse if (!IsReadOnly() && !ctrl && !shift && !alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_Backspace)))\n\t\t\tBackspace();\n\t\telse if (!ctrl && !shift && !alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_Insert)))\n\t\t\tmOverwrite ^= true;\n\t\telse if (ctrl && !shift && !alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_Insert)))\n\t\t\tCopy();\n\t\telse if (ctrl && !shift && !alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_C)))\n\t\t\tCopy();\n\t\telse if (!IsReadOnly() && !ctrl && shift && !alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_Insert)))\n\t\t\tPaste();\n\t\telse if (!IsReadOnly() && ctrl && !shift && !alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_V)))\n\t\t\tPaste();\n\t\telse if (ctrl && !shift && !alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_X)))\n\t\t\tCut();\n\t\telse if (!ctrl && shift && !alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_Delete)))\n\t\t\tCut();\n\t\telse if (ctrl && !shift && !alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_A)))\n\t\t\tSelectAll();\n\t\telse if (!IsReadOnly() && !ctrl && !shift && !alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_Enter)))\n\t\t\tEnterCharacter('\\n', false);\n\t\telse if (!IsReadOnly() && !ctrl && !alt && ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_Tab)))\n\t\t\tEnterCharacter('\\t', shift);\n\n\t\tif (!IsReadOnly() && !io.InputQueueCharacters.empty())\n\t\t{\n\t\t\tfor (int i = 0; i < io.InputQueueCharacters.Size; i++)\n\t\t\t{\n\t\t\t\tauto c = io.InputQueueCharacters[i];\n\t\t\t\tif (c != 0 && (c == '\\n' || c >= 32))\n\t\t\t\t\tEnterCharacter(c, shift);\n\t\t\t}\n\t\t\tio.InputQueueCharacters.resize(0);\n\t\t}\n\t}\n}\n\nvoid TextEditor::HandleMouseInputs()\n{\n\tImGuiIO& io = ImGui::GetIO();\n\tauto shift = io.KeyShift;\n\tauto ctrl = io.ConfigMacOSXBehaviors ? io.KeySuper : io.KeyCtrl;\n\tauto alt = io.ConfigMacOSXBehaviors ? io.KeyCtrl : io.KeyAlt;\n\n\tif (ImGui::IsWindowHovered())\n\t{\n\t\tif (!shift && !alt)\n\t\t{\n\t\t\tauto click = ImGui::IsMouseClicked(0);\n\t\t\tauto doubleClick = ImGui::IsMouseDoubleClicked(0);\n\t\t\tauto t = ImGui::GetTime();\n\t\t\tauto tripleClick = click && !doubleClick && (mLastClick != -1.0f && (t - mLastClick) < io.MouseDoubleClickTime);\n\n\t\t\t/*\n\t\t\tLeft mouse button triple click\n\t\t\t*/\n\n\t\t\tif (tripleClick)\n\t\t\t{\n\t\t\t\tif (!ctrl)\n\t\t\t\t{\n\t\t\t\t\tmState.mCursorPosition = mInteractiveStart = mInteractiveEnd = ScreenPosToCoordinates(ImGui::GetMousePos());\n\t\t\t\t\tmSelectionMode = SelectionMode::Line;\n\t\t\t\t\tSetSelection(mInteractiveStart, mInteractiveEnd, mSelectionMode);\n\t\t\t\t}\n\n\t\t\t\tmLastClick = -1.0f;\n\t\t\t}\n\n\t\t\t/*\n\t\t\tLeft mouse button double click\n\t\t\t*/\n\n\t\t\telse if (doubleClick)\n\t\t\t{\n\t\t\t\tif (!ctrl)\n\t\t\t\t{\n\t\t\t\t\tmState.mCursorPosition = mInteractiveStart = mInteractiveEnd = ScreenPosToCoordinates(ImGui::GetMousePos());\n\t\t\t\t\tif (mSelectionMode == SelectionMode::Line)\n\t\t\t\t\t\tmSelectionMode = SelectionMode::Normal;\n\t\t\t\t\telse\n\t\t\t\t\t\tmSelectionMode = SelectionMode::Word;\n\t\t\t\t\tSetSelection(mInteractiveStart, mInteractiveEnd, mSelectionMode);\n\t\t\t\t}\n\n\t\t\t\tmLastClick = (float)ImGui::GetTime();\n\t\t\t}\n\n\t\t\t/*\n\t\t\tLeft mouse button click\n\t\t\t*/\n\t\t\telse if (click)\n\t\t\t{\n\t\t\t\tmState.mCursorPosition = mInteractiveStart = mInteractiveEnd = ScreenPosToCoordinates(ImGui::GetMousePos());\n\t\t\t\tif (ctrl)\n\t\t\t\t\tmSelectionMode = SelectionMode::Word;\n\t\t\t\telse\n\t\t\t\t\tmSelectionMode = SelectionMode::Normal;\n\t\t\t\tSetSelection(mInteractiveStart, mInteractiveEnd, mSelectionMode);\n\n\t\t\t\tmLastClick = (float)ImGui::GetTime();\n\t\t\t}\n\t\t\t// Mouse left button dragging (=> update selection)\n\t\t\telse if (ImGui::IsMouseDragging(0) && ImGui::IsMouseDown(0))\n\t\t\t{\n\t\t\t\tio.WantCaptureMouse = true;\n\t\t\t\tmState.mCursorPosition = mInteractiveEnd = ScreenPosToCoordinates(ImGui::GetMousePos());\n\t\t\t\tSetSelection(mInteractiveStart, mInteractiveEnd, mSelectionMode);\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid TextEditor::Render()\n{\n\t/* Compute mCharAdvance regarding to scaled font size (Ctrl + mouse wheel)*/\n\tconst float fontSize = ImGui::GetFont()->CalcTextSizeA(ImGui::GetFontSize(), FLT_MAX, -1.0f, \"#\", nullptr, nullptr).x;\n\tmCharAdvance = ImVec2(fontSize, ImGui::GetTextLineHeightWithSpacing() * mLineSpacing);\n\n\t/* Update palette with the current alpha from style */\n\tfor (int i = 0; i < (int)PaletteIndex::Max; ++i)\n\t{\n\t\tauto color = ImGui::ColorConvertU32ToFloat4(mPaletteBase[i]);\n\t\tcolor.w *= ImGui::GetStyle().Alpha;\n\t\tmPalette[i] = ImGui::ColorConvertFloat4ToU32(color);\n\t}\n\n\tassert(mLineBuffer.empty());\n\n\tauto contentSize = ImGui::GetWindowContentRegionMax();\n\tauto drawList = ImGui::GetWindowDrawList();\n\tfloat longest(mTextStart);\n\n\tif (mScrollToTop)\n\t{\n\t\tmScrollToTop = false;\n\t\tImGui::SetScrollY(0.f);\n\t}\n\n\tImVec2 cursorScreenPos = ImGui::GetCursorScreenPos();\n\tauto scrollX = ImGui::GetScrollX();\n\tauto scrollY = ImGui::GetScrollY();\n\n\tauto lineNo = (int)floor(scrollY / mCharAdvance.y);\n\tauto globalLineMax = (int)mLines.size();\n\tauto lineMax = std::max(0, std::min((int)mLines.size() - 1, lineNo + (int)floor((scrollY + contentSize.y) / mCharAdvance.y)));\n\n\t// Deduce mTextStart by evaluating mLines size (global lineMax) plus two spaces as text width\n\tchar buf[16];\n\tsnprintf(buf, 16, \" %d \", globalLineMax);\n\tmTextStart = ImGui::GetFont()->CalcTextSizeA(ImGui::GetFontSize(), FLT_MAX, -1.0f, buf, nullptr, nullptr).x + mLeftMargin;\n\n\tif (!mLines.empty())\n\t{\n\t\tfloat spaceSize = ImGui::GetFont()->CalcTextSizeA(ImGui::GetFontSize(), FLT_MAX, -1.0f, \" \", nullptr, nullptr).x;\n\n\t\twhile (lineNo <= lineMax)\n\t\t{\n\t\t\tImVec2 lineStartScreenPos = ImVec2(cursorScreenPos.x, cursorScreenPos.y + lineNo * mCharAdvance.y);\n\t\t\tImVec2 textScreenPos = ImVec2(lineStartScreenPos.x + mTextStart, lineStartScreenPos.y);\n\n\t\t\tauto& line = mLines[lineNo];\n\t\t\tlongest = std::max(mTextStart + TextDistanceToLineStart(Coordinates(lineNo, GetLineMaxColumn(lineNo))), longest);\n\t\t\tauto columnNo = 0;\n\t\t\tCoordinates lineStartCoord(lineNo, 0);\n\t\t\tCoordinates lineEndCoord(lineNo, GetLineMaxColumn(lineNo));\n\n\t\t\t// Draw selection for the current line\n\t\t\tfloat sstart = -1.0f;\n\t\t\tfloat ssend = -1.0f;\n\n\t\t\tassert(mState.mSelectionStart <= mState.mSelectionEnd);\n\t\t\tif (mState.mSelectionStart <= lineEndCoord)\n\t\t\t\tsstart = mState.mSelectionStart > lineStartCoord ? TextDistanceToLineStart(mState.mSelectionStart) : 0.0f;\n\t\t\tif (mState.mSelectionEnd > lineStartCoord)\n\t\t\t\tssend = TextDistanceToLineStart(mState.mSelectionEnd < lineEndCoord ? mState.mSelectionEnd : lineEndCoord);\n\n\t\t\tif (mState.mSelectionEnd.mLine > lineNo)\n\t\t\t\tssend += mCharAdvance.x;\n\n\t\t\tif (sstart != -1 && ssend != -1 && sstart < ssend)\n\t\t\t{\n\t\t\t\tImVec2 vstart(lineStartScreenPos.x + mTextStart + sstart, lineStartScreenPos.y);\n\t\t\t\tImVec2 vend(lineStartScreenPos.x + mTextStart + ssend, lineStartScreenPos.y + mCharAdvance.y);\n\t\t\t\tdrawList->AddRectFilled(vstart, vend, mPalette[(int)PaletteIndex::Selection]);\n\t\t\t}\n\n\t\t\t// Draw breakpoints\n\t\t\tauto start = ImVec2(lineStartScreenPos.x + scrollX, lineStartScreenPos.y);\n\n\t\t\tif (mBreakpoints.count(lineNo + 1) != 0)\n\t\t\t{\n\t\t\t\tauto end = ImVec2(lineStartScreenPos.x + contentSize.x + 2.0f * scrollX, lineStartScreenPos.y + mCharAdvance.y);\n\t\t\t\tdrawList->AddRectFilled(start, end, mPalette[(int)PaletteIndex::Breakpoint]);\n\t\t\t}\n\n\t\t\t// Draw error markers\n\t\t\tauto errorIt = mErrorMarkers.find(lineNo + 1);\n\t\t\tif (errorIt != mErrorMarkers.end())\n\t\t\t{\n\t\t\t\tauto end = ImVec2(lineStartScreenPos.x + contentSize.x + 2.0f * scrollX, lineStartScreenPos.y + mCharAdvance.y);\n\t\t\t\tdrawList->AddRectFilled(start, end, mPalette[(int)PaletteIndex::ErrorMarker]);\n\n\t\t\t\tif (ImGui::IsMouseHoveringRect(lineStartScreenPos, end))\n\t\t\t\t{\n\t\t\t\t\tImGui::BeginTooltip();\n\t\t\t\t\tImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 0.2f, 0.2f, 1.0f));\n\t\t\t\t\tImGui::Text(\"Error at line %d:\", errorIt->first);\n\t\t\t\t\tImGui::PopStyleColor();\n\t\t\t\t\tImGui::Separator();\n\t\t\t\t\tImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 1.0f, 0.2f, 1.0f));\n\t\t\t\t\tImGui::Text(\"%s\", errorIt->second.c_str());\n\t\t\t\t\tImGui::PopStyleColor();\n\t\t\t\t\tImGui::EndTooltip();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Draw line number (right aligned)\n\t\t\tsnprintf(buf, 16, \"%d  \", lineNo + 1);\n\n\t\t\tauto lineNoWidth = ImGui::GetFont()->CalcTextSizeA(ImGui::GetFontSize(), FLT_MAX, -1.0f, buf, nullptr, nullptr).x;\n\t\t\tdrawList->AddText(ImVec2(lineStartScreenPos.x + mTextStart - lineNoWidth, lineStartScreenPos.y), mPalette[(int)PaletteIndex::LineNumber], buf);\n\n\t\t\tif (mState.mCursorPosition.mLine == lineNo)\n\t\t\t{\n\t\t\t\tauto focused = ImGui::IsWindowFocused();\n\n\t\t\t\t// Highlight the current line (where the cursor is)\n\t\t\t\tif (!HasSelection())\n\t\t\t\t{\n\t\t\t\t\tauto end = ImVec2(start.x + contentSize.x + scrollX, start.y + mCharAdvance.y);\n\t\t\t\t\tdrawList->AddRectFilled(start, end, mPalette[(int)(focused ? PaletteIndex::CurrentLineFill : PaletteIndex::CurrentLineFillInactive)]);\n\t\t\t\t\tdrawList->AddRect(start, end, mPalette[(int)PaletteIndex::CurrentLineEdge], 1.0f);\n\t\t\t\t}\n\n\t\t\t\t// Render the cursor\n\t\t\t\tif (focused)\n\t\t\t\t{\n\t\t\t\t\tauto timeEnd = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();\n\t\t\t\t\tauto elapsed = timeEnd - mStartTime;\n\t\t\t\t\tif (elapsed > 400)\n\t\t\t\t\t{\n\t\t\t\t\t\tfloat width = 1.0f;\n\t\t\t\t\t\tauto cindex = GetCharacterIndex(mState.mCursorPosition);\n\t\t\t\t\t\tfloat cx = TextDistanceToLineStart(mState.mCursorPosition);\n\n\t\t\t\t\t\tif (mOverwrite && cindex < (int)line.size())\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tauto c = line[cindex].mChar;\n\t\t\t\t\t\t\tif (c == '\\t')\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tauto x = (1.0f + std::floor((1.0f + cx) / (float(mTabSize) * spaceSize))) * (float(mTabSize) * spaceSize);\n\t\t\t\t\t\t\t\twidth = x - cx;\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\tchar buf2[2];\n\t\t\t\t\t\t\t\tbuf2[0] = line[cindex].mChar;\n\t\t\t\t\t\t\t\tbuf2[1] = '\\0';\n\t\t\t\t\t\t\t\twidth = ImGui::GetFont()->CalcTextSizeA(ImGui::GetFontSize(), FLT_MAX, -1.0f, buf2).x;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tImVec2 cstart(textScreenPos.x + cx, lineStartScreenPos.y);\n\t\t\t\t\t\tImVec2 cend(textScreenPos.x + cx + width, lineStartScreenPos.y + mCharAdvance.y);\n\t\t\t\t\t\tdrawList->AddRectFilled(cstart, cend, mPalette[(int)PaletteIndex::Cursor]);\n\t\t\t\t\t\tif (elapsed > 800)\n\t\t\t\t\t\t\tmStartTime = timeEnd;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Render colorized text\n\t\t\tauto prevColor = line.empty() ? mPalette[(int)PaletteIndex::Default] : GetGlyphColor(line[0]);\n\t\t\tImVec2 bufferOffset;\n\n\t\t\tfor (int i = 0; i < line.size();)\n\t\t\t{\n\t\t\t\tauto& glyph = line[i];\n\t\t\t\tauto color = GetGlyphColor(glyph);\n\n\t\t\t\tif ((color != prevColor || glyph.mChar == '\\t' || glyph.mChar == ' ') && !mLineBuffer.empty())\n\t\t\t\t{\n\t\t\t\t\tconst ImVec2 newOffset(textScreenPos.x + bufferOffset.x, textScreenPos.y + bufferOffset.y);\n\t\t\t\t\tdrawList->AddText(newOffset, prevColor, mLineBuffer.c_str());\n\t\t\t\t\tauto textSize = ImGui::GetFont()->CalcTextSizeA(ImGui::GetFontSize(), FLT_MAX, -1.0f, mLineBuffer.c_str(), nullptr, nullptr);\n\t\t\t\t\tbufferOffset.x += textSize.x;\n\t\t\t\t\tmLineBuffer.clear();\n\t\t\t\t}\n\t\t\t\tprevColor = color;\n\n\t\t\t\tif (glyph.mChar == '\\t')\n\t\t\t\t{\n\t\t\t\t\tauto oldX = bufferOffset.x;\n\t\t\t\t\tbufferOffset.x = (1.0f + std::floor((1.0f + bufferOffset.x) / (float(mTabSize) * spaceSize))) * (float(mTabSize) * spaceSize);\n\t\t\t\t\t++i;\n\n\t\t\t\t\tif (mShowWhitespaces)\n\t\t\t\t\t{\n\t\t\t\t\t\tconst auto s = ImGui::GetFontSize();\n\t\t\t\t\t\tconst auto x1 = textScreenPos.x + oldX + 1.0f;\n\t\t\t\t\t\tconst auto x2 = textScreenPos.x + bufferOffset.x - 1.0f;\n\t\t\t\t\t\tconst auto y = textScreenPos.y + bufferOffset.y + s * 0.5f;\n\t\t\t\t\t\tconst ImVec2 p1(x1, y);\n\t\t\t\t\t\tconst ImVec2 p2(x2, y);\n\t\t\t\t\t\tconst ImVec2 p3(x2 - s * 0.2f, y - s * 0.2f);\n\t\t\t\t\t\tconst ImVec2 p4(x2 - s * 0.2f, y + s * 0.2f);\n\t\t\t\t\t\tdrawList->AddLine(p1, p2, 0x90909090);\n\t\t\t\t\t\tdrawList->AddLine(p2, p3, 0x90909090);\n\t\t\t\t\t\tdrawList->AddLine(p2, p4, 0x90909090);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (glyph.mChar == ' ')\n\t\t\t\t{\n\t\t\t\t\tif (mShowWhitespaces)\n\t\t\t\t\t{\n\t\t\t\t\t\tconst auto s = ImGui::GetFontSize();\n\t\t\t\t\t\tconst auto x = textScreenPos.x + bufferOffset.x + spaceSize * 0.5f;\n\t\t\t\t\t\tconst auto y = textScreenPos.y + bufferOffset.y + s * 0.5f;\n\t\t\t\t\t\tdrawList->AddCircleFilled(ImVec2(x, y), 1.5f, 0x80808080, 4);\n\t\t\t\t\t}\n\t\t\t\t\tbufferOffset.x += spaceSize;\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tauto l = UTF8CharLength(glyph.mChar);\n\t\t\t\t\twhile (l-- > 0)\n\t\t\t\t\t\tmLineBuffer.push_back(line[i++].mChar);\n\t\t\t\t}\n\t\t\t\t++columnNo;\n\t\t\t}\n\n\t\t\tif (!mLineBuffer.empty())\n\t\t\t{\n\t\t\t\tconst ImVec2 newOffset(textScreenPos.x + bufferOffset.x, textScreenPos.y + bufferOffset.y);\n\t\t\t\tdrawList->AddText(newOffset, prevColor, mLineBuffer.c_str());\n\t\t\t\tmLineBuffer.clear();\n\t\t\t}\n\n\t\t\t++lineNo;\n\t\t}\n\n\t\t// Draw a tooltip on known identifiers/preprocessor symbols\n\t\tif (ImGui::IsMousePosValid())\n\t\t{\n\t\t\tauto id = GetWordAt(ScreenPosToCoordinates(ImGui::GetMousePos()));\n\t\t\tif (!id.empty())\n\t\t\t{\n\t\t\t\tauto it = mLanguageDefinition.mIdentifiers.find(id);\n\t\t\t\tif (it != mLanguageDefinition.mIdentifiers.end())\n\t\t\t\t{\n\t\t\t\t\tImGui::BeginTooltip();\n\t\t\t\t\tImGui::TextUnformatted(it->second.mDeclaration.c_str());\n\t\t\t\t\tImGui::EndTooltip();\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tauto pi = mLanguageDefinition.mPreprocIdentifiers.find(id);\n\t\t\t\t\tif (pi != mLanguageDefinition.mPreprocIdentifiers.end())\n\t\t\t\t\t{\n\t\t\t\t\t\tImGui::BeginTooltip();\n\t\t\t\t\t\tImGui::TextUnformatted(pi->second.mDeclaration.c_str());\n\t\t\t\t\t\tImGui::EndTooltip();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\n\tImGui::Dummy(ImVec2((longest + 2), mLines.size() * mCharAdvance.y));\n\n\tif (mScrollToCursor)\n\t{\n\t\tEnsureCursorVisible();\n\t\tImGui::SetWindowFocus();\n\t\tmScrollToCursor = false;\n\t}\n}\n\nvoid TextEditor::Render(const char* aTitle, const ImVec2& aSize, bool aBorder)\n{\n\tmWithinRender = true;\n\tmTextChanged = false;\n\tmCursorPositionChanged = false;\n\n\tImGui::PushStyleColor(ImGuiCol_ChildBg, ImGui::ColorConvertU32ToFloat4(mPalette[(int)PaletteIndex::Background]));\n\tImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0.0f, 0.0f));\n\tif (!mIgnoreImGuiChild)\n\t\tImGui::BeginChild(aTitle, aSize, aBorder, ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar | ImGuiWindowFlags_NoMove);\n\n\tif (mHandleKeyboardInputs)\n\t{\n\t\tHandleKeyboardInputs();\n\t\tImGui::PushAllowKeyboardFocus(true);\n\t}\n\n\tif (mHandleMouseInputs)\n\t\tHandleMouseInputs();\n\n\tColorizeInternal();\n\tRender();\n\n\tif (mHandleKeyboardInputs)\n\t\tImGui::PopAllowKeyboardFocus();\n\n\tif (!mIgnoreImGuiChild)\n\t\tImGui::EndChild();\n\n\tImGui::PopStyleVar();\n\tImGui::PopStyleColor();\n\n\tmWithinRender = false;\n}\n\nvoid TextEditor::SetText(const std::string & aText)\n{\n\tmLines.clear();\n\tmLines.emplace_back(Line());\n\tfor (auto chr : aText)\n\t{\n\t\tif (chr == '\\r')\n\t\t{\n\t\t\t// ignore the carriage return character\n\t\t}\n\t\telse if (chr == '\\n')\n\t\t\tmLines.emplace_back(Line());\n\t\telse\n\t\t{\n\t\t\tmLines.back().emplace_back(Glyph(chr, PaletteIndex::Default));\n\t\t}\n\t}\n\n\tmTextChanged = true;\n\tmScrollToTop = true;\n\n\tmUndoBuffer.clear();\n\tmUndoIndex = 0;\n\n\tColorize();\n}\n\nvoid TextEditor::SetTextLines(const std::vector<std::string> & aLines)\n{\n\tmLines.clear();\n\n\tif (aLines.empty())\n\t{\n\t\tmLines.emplace_back(Line());\n\t}\n\telse\n\t{\n\t\tmLines.resize(aLines.size());\n\n\t\tfor (size_t i = 0; i < aLines.size(); ++i)\n\t\t{\n\t\t\tconst std::string & aLine = aLines[i];\n\n\t\t\tmLines[i].reserve(aLine.size());\n\t\t\tfor (size_t j = 0; j < aLine.size(); ++j)\n\t\t\t\tmLines[i].emplace_back(Glyph(aLine[j], PaletteIndex::Default));\n\t\t}\n\t}\n\n\tmTextChanged = true;\n\tmScrollToTop = true;\n\n\tmUndoBuffer.clear();\n\tmUndoIndex = 0;\n\n\tColorize();\n}\n\nvoid TextEditor::EnterCharacter(ImWchar aChar, bool aShift)\n{\n\tassert(!mReadOnly);\n\n\tUndoRecord u;\n\n\tu.mBefore = mState;\n\n\tif (HasSelection())\n\t{\n\t\tif (aChar == '\\t' && mState.mSelectionStart.mLine != mState.mSelectionEnd.mLine)\n\t\t{\n\n\t\t\tauto start = mState.mSelectionStart;\n\t\t\tauto end = mState.mSelectionEnd;\n\t\t\tauto originalEnd = end;\n\n\t\t\tif (start > end)\n\t\t\t\tstd::swap(start, end);\n\t\t\tstart.mColumn = 0;\n\t\t\t//\t\t\tend.mColumn = end.mLine < mLines.size() ? mLines[end.mLine].size() : 0;\n\t\t\tif (end.mColumn == 0 && end.mLine > 0)\n\t\t\t\t--end.mLine;\n\t\t\tif (end.mLine >= (int)mLines.size())\n\t\t\t\tend.mLine = mLines.empty() ? 0 : (int)mLines.size() - 1;\n\t\t\tend.mColumn = GetLineMaxColumn(end.mLine);\n\n\t\t\t//if (end.mColumn >= GetLineMaxColumn(end.mLine))\n\t\t\t//\tend.mColumn = GetLineMaxColumn(end.mLine) - 1;\n\n\t\t\tu.mRemovedStart = start;\n\t\t\tu.mRemovedEnd = end;\n\t\t\tu.mRemoved = GetText(start, end);\n\n\t\t\tbool modified = false;\n\n\t\t\tfor (int i = start.mLine; i <= end.mLine; i++)\n\t\t\t{\n\t\t\t\tauto& line = mLines[i];\n\t\t\t\tif (aShift)\n\t\t\t\t{\n\t\t\t\t\tif (!line.empty())\n\t\t\t\t\t{\n\t\t\t\t\t\tif (line.front().mChar == '\\t')\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tline.erase(line.begin());\n\t\t\t\t\t\t\tmodified = true;\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\tfor (int j = 0; j < mTabSize && !line.empty() && line.front().mChar == ' '; j++)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tline.erase(line.begin());\n\t\t\t\t\t\t\t\tmodified = true;\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\n\t\t\t\t{\n\t\t\t\t\tline.insert(line.begin(), Glyph('\\t', TextEditor::PaletteIndex::Background));\n\t\t\t\t\tmodified = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (modified)\n\t\t\t{\n\t\t\t\tstart = Coordinates(start.mLine, GetCharacterColumn(start.mLine, 0));\n\t\t\t\tCoordinates rangeEnd;\n\t\t\t\tif (originalEnd.mColumn != 0)\n\t\t\t\t{\n\t\t\t\t\tend = Coordinates(end.mLine, GetLineMaxColumn(end.mLine));\n\t\t\t\t\trangeEnd = end;\n\t\t\t\t\tu.mAdded = GetText(start, end);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tend = Coordinates(originalEnd.mLine, 0);\n\t\t\t\t\trangeEnd = Coordinates(end.mLine - 1, GetLineMaxColumn(end.mLine - 1));\n\t\t\t\t\tu.mAdded = GetText(start, rangeEnd);\n\t\t\t\t}\n\n\t\t\t\tu.mAddedStart = start;\n\t\t\t\tu.mAddedEnd = rangeEnd;\n\t\t\t\tu.mAfter = mState;\n\n\t\t\t\tmState.mSelectionStart = start;\n\t\t\t\tmState.mSelectionEnd = end;\n\t\t\t\tAddUndo(u);\n\n\t\t\t\tmTextChanged = true;\n\n\t\t\t\tEnsureCursorVisible();\n\t\t\t}\n\n\t\t\treturn;\n\t\t} // c == '\\t'\n\t\telse\n\t\t{\n\t\t\tu.mRemoved = GetSelectedText();\n\t\t\tu.mRemovedStart = mState.mSelectionStart;\n\t\t\tu.mRemovedEnd = mState.mSelectionEnd;\n\t\t\tDeleteSelection();\n\t\t}\n\t} // HasSelection\n\n\tauto coord = GetActualCursorCoordinates();\n\tu.mAddedStart = coord;\n\n\tassert(!mLines.empty());\n\n\tif (aChar == '\\n')\n\t{\n\t\tInsertLine(coord.mLine + 1);\n\t\tauto& line = mLines[coord.mLine];\n\t\tauto& newLine = mLines[coord.mLine + 1];\n\n\t\tif (mLanguageDefinition.mAutoIndentation)\n\t\t\tfor (size_t it = 0; it < line.size() && isascii(line[it].mChar) && isblank(line[it].mChar); ++it)\n\t\t\t\tnewLine.push_back(line[it]);\n\n\t\tconst size_t whitespaceSize = newLine.size();\n\t\tauto cindex = GetCharacterIndex(coord);\n\t\tnewLine.insert(newLine.end(), line.begin() + cindex, line.end());\n\t\tline.erase(line.begin() + cindex, line.begin() + line.size());\n\t\tSetCursorPosition(Coordinates(coord.mLine + 1, GetCharacterColumn(coord.mLine + 1, (int)whitespaceSize)));\n\t\tu.mAdded = (char)aChar;\n\t}\n\telse\n\t{\n\t\tchar buf[7];\n\t\tint e = ImTextCharToUtf8(buf, 7, aChar);\n\t\tif (e > 0)\n\t\t{\n\t\t\tbuf[e] = '\\0';\n\t\t\tauto& line = mLines[coord.mLine];\n\t\t\tauto cindex = GetCharacterIndex(coord);\n\n\t\t\tif (mOverwrite && cindex < (int)line.size())\n\t\t\t{\n\t\t\t\tauto d = UTF8CharLength(line[cindex].mChar);\n\n\t\t\t\tu.mRemovedStart = mState.mCursorPosition;\n\t\t\t\tu.mRemovedEnd = Coordinates(coord.mLine, GetCharacterColumn(coord.mLine, cindex + d));\n\n\t\t\t\twhile (d-- > 0 && cindex < (int)line.size())\n\t\t\t\t{\n\t\t\t\t\tu.mRemoved += line[cindex].mChar;\n\t\t\t\t\tline.erase(line.begin() + cindex);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (auto p = buf; *p != '\\0'; p++, ++cindex)\n\t\t\t\tline.insert(line.begin() + cindex, Glyph(*p, PaletteIndex::Default));\n\t\t\tu.mAdded = buf;\n\n\t\t\tSetCursorPosition(Coordinates(coord.mLine, GetCharacterColumn(coord.mLine, cindex)));\n\t\t}\n\t\telse\n\t\t\treturn;\n\t}\n\n\tmTextChanged = true;\n\n\tu.mAddedEnd = GetActualCursorCoordinates();\n\tu.mAfter = mState;\n\n\tAddUndo(u);\n\n\tColorize(coord.mLine - 1, 3);\n\tEnsureCursorVisible();\n}\n\nvoid TextEditor::SetReadOnly(bool aValue)\n{\n\tmReadOnly = aValue;\n}\n\nvoid TextEditor::SetColorizerEnable(bool aValue)\n{\n\tmColorizerEnabled = aValue;\n}\n\nvoid TextEditor::SetCursorPosition(const Coordinates & aPosition)\n{\n\tif (mState.mCursorPosition != aPosition)\n\t{\n\t\tmState.mCursorPosition = aPosition;\n\t\tmCursorPositionChanged = true;\n\t\tEnsureCursorVisible();\n\t}\n}\n\nvoid TextEditor::SetSelectionStart(const Coordinates & aPosition)\n{\n\tmState.mSelectionStart = SanitizeCoordinates(aPosition);\n\tif (mState.mSelectionStart > mState.mSelectionEnd)\n\t\tstd::swap(mState.mSelectionStart, mState.mSelectionEnd);\n}\n\nvoid TextEditor::SetSelectionEnd(const Coordinates & aPosition)\n{\n\tmState.mSelectionEnd = SanitizeCoordinates(aPosition);\n\tif (mState.mSelectionStart > mState.mSelectionEnd)\n\t\tstd::swap(mState.mSelectionStart, mState.mSelectionEnd);\n}\n\nvoid TextEditor::SetSelection(const Coordinates & aStart, const Coordinates & aEnd, SelectionMode aMode)\n{\n\tauto oldSelStart = mState.mSelectionStart;\n\tauto oldSelEnd = mState.mSelectionEnd;\n\n\tmState.mSelectionStart = SanitizeCoordinates(aStart);\n\tmState.mSelectionEnd = SanitizeCoordinates(aEnd);\n\tif (mState.mSelectionStart > mState.mSelectionEnd)\n\t\tstd::swap(mState.mSelectionStart, mState.mSelectionEnd);\n\n\tswitch (aMode)\n\t{\n\tcase TextEditor::SelectionMode::Normal:\n\t\tbreak;\n\tcase TextEditor::SelectionMode::Word:\n\t{\n\t\tmState.mSelectionStart = FindWordStart(mState.mSelectionStart);\n\t\tif (!IsOnWordBoundary(mState.mSelectionEnd))\n\t\t\tmState.mSelectionEnd = FindWordEnd(FindWordStart(mState.mSelectionEnd));\n\t\tbreak;\n\t}\n\tcase TextEditor::SelectionMode::Line:\n\t{\n\t\tconst auto lineNo = mState.mSelectionEnd.mLine;\n\t\tconst auto lineSize = (size_t)lineNo < mLines.size() ? mLines[lineNo].size() : 0;\n\t\tmState.mSelectionStart = Coordinates(mState.mSelectionStart.mLine, 0);\n\t\tmState.mSelectionEnd = Coordinates(lineNo, GetLineMaxColumn(lineNo));\n\t\tbreak;\n\t}\n\tdefault:\n\t\tbreak;\n\t}\n\n\tif (mState.mSelectionStart != oldSelStart ||\n\t\tmState.mSelectionEnd != oldSelEnd)\n\t\tmCursorPositionChanged = true;\n}\n\nvoid TextEditor::SetTabSize(int aValue)\n{\n\tmTabSize = std::max(0, std::min(32, aValue));\n}\n\nvoid TextEditor::InsertText(const std::string & aValue)\n{\n\tInsertText(aValue.c_str());\n}\n\nvoid TextEditor::InsertText(const char * aValue)\n{\n\tif (aValue == nullptr)\n\t\treturn;\n\n\tauto pos = GetActualCursorCoordinates();\n\tauto start = std::min(pos, mState.mSelectionStart);\n\tint totalLines = pos.mLine - start.mLine;\n\n\ttotalLines += InsertTextAt(pos, aValue);\n\n\tSetSelection(pos, pos);\n\tSetCursorPosition(pos);\n\tColorize(start.mLine - 1, totalLines + 2);\n}\n\nvoid TextEditor::DeleteSelection()\n{\n\tassert(mState.mSelectionEnd >= mState.mSelectionStart);\n\n\tif (mState.mSelectionEnd == mState.mSelectionStart)\n\t\treturn;\n\n\tDeleteRange(mState.mSelectionStart, mState.mSelectionEnd);\n\n\tSetSelection(mState.mSelectionStart, mState.mSelectionStart);\n\tSetCursorPosition(mState.mSelectionStart);\n\tColorize(mState.mSelectionStart.mLine, 1);\n}\n\nvoid TextEditor::MoveUp(int aAmount, bool aSelect)\n{\n\tauto oldPos = mState.mCursorPosition;\n\tmState.mCursorPosition.mLine = std::max(0, mState.mCursorPosition.mLine - aAmount);\n\tif (oldPos != mState.mCursorPosition)\n\t{\n\t\tif (aSelect)\n\t\t{\n\t\t\tif (oldPos == mInteractiveStart)\n\t\t\t\tmInteractiveStart = mState.mCursorPosition;\n\t\t\telse if (oldPos == mInteractiveEnd)\n\t\t\t\tmInteractiveEnd = mState.mCursorPosition;\n\t\t\telse\n\t\t\t{\n\t\t\t\tmInteractiveStart = mState.mCursorPosition;\n\t\t\t\tmInteractiveEnd = oldPos;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t\tmInteractiveStart = mInteractiveEnd = mState.mCursorPosition;\n\t\tSetSelection(mInteractiveStart, mInteractiveEnd);\n\n\t\tEnsureCursorVisible();\n\t}\n}\n\nvoid TextEditor::MoveDown(int aAmount, bool aSelect)\n{\n\tassert(mState.mCursorPosition.mColumn >= 0);\n\tauto oldPos = mState.mCursorPosition;\n\tmState.mCursorPosition.mLine = std::max(0, std::min((int)mLines.size() - 1, mState.mCursorPosition.mLine + aAmount));\n\n\tif (mState.mCursorPosition != oldPos)\n\t{\n\t\tif (aSelect)\n\t\t{\n\t\t\tif (oldPos == mInteractiveEnd)\n\t\t\t\tmInteractiveEnd = mState.mCursorPosition;\n\t\t\telse if (oldPos == mInteractiveStart)\n\t\t\t\tmInteractiveStart = mState.mCursorPosition;\n\t\t\telse\n\t\t\t{\n\t\t\t\tmInteractiveStart = oldPos;\n\t\t\t\tmInteractiveEnd = mState.mCursorPosition;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t\tmInteractiveStart = mInteractiveEnd = mState.mCursorPosition;\n\t\tSetSelection(mInteractiveStart, mInteractiveEnd);\n\n\t\tEnsureCursorVisible();\n\t}\n}\n\nstatic bool IsUTFSequence(char c)\n{\n\treturn (c & 0xC0) == 0x80;\n}\n\nvoid TextEditor::MoveLeft(int aAmount, bool aSelect, bool aWordMode)\n{\n\tif (mLines.empty())\n\t\treturn;\n\n\tauto oldPos = mState.mCursorPosition;\n\tmState.mCursorPosition = GetActualCursorCoordinates();\n\tauto line = mState.mCursorPosition.mLine;\n\tauto cindex = GetCharacterIndex(mState.mCursorPosition);\n\n\twhile (aAmount-- > 0)\n\t{\n\t\tif (cindex == 0)\n\t\t{\n\t\t\tif (line > 0)\n\t\t\t{\n\t\t\t\t--line;\n\t\t\t\tif ((int)mLines.size() > line)\n\t\t\t\t\tcindex = (int)mLines[line].size();\n\t\t\t\telse\n\t\t\t\t\tcindex = 0;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\t--cindex;\n\t\t\tif (cindex > 0)\n\t\t\t{\n\t\t\t\tif ((int)mLines.size() > line)\n\t\t\t\t{\n\t\t\t\t\twhile (cindex > 0 && IsUTFSequence(mLines[line][cindex].mChar))\n\t\t\t\t\t\t--cindex;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tmState.mCursorPosition = Coordinates(line, GetCharacterColumn(line, cindex));\n\t\tif (aWordMode)\n\t\t{\n\t\t\tmState.mCursorPosition = FindWordStart(mState.mCursorPosition);\n\t\t\tcindex = GetCharacterIndex(mState.mCursorPosition);\n\t\t}\n\t}\n\n\tmState.mCursorPosition = Coordinates(line, GetCharacterColumn(line, cindex));\n\n\tassert(mState.mCursorPosition.mColumn >= 0);\n\tif (aSelect)\n\t{\n\t\tif (oldPos == mInteractiveStart)\n\t\t\tmInteractiveStart = mState.mCursorPosition;\n\t\telse if (oldPos == mInteractiveEnd)\n\t\t\tmInteractiveEnd = mState.mCursorPosition;\n\t\telse\n\t\t{\n\t\t\tmInteractiveStart = mState.mCursorPosition;\n\t\t\tmInteractiveEnd = oldPos;\n\t\t}\n\t}\n\telse\n\t\tmInteractiveStart = mInteractiveEnd = mState.mCursorPosition;\n\tSetSelection(mInteractiveStart, mInteractiveEnd, aSelect && aWordMode ? SelectionMode::Word : SelectionMode::Normal);\n\n\tEnsureCursorVisible();\n}\n\nvoid TextEditor::MoveRight(int aAmount, bool aSelect, bool aWordMode)\n{\n\tauto oldPos = mState.mCursorPosition;\n\n\tif (mLines.empty() || oldPos.mLine >= mLines.size())\n\t\treturn;\n\n\tauto cindex = GetCharacterIndex(mState.mCursorPosition);\n\twhile (aAmount-- > 0)\n\t{\n\t\tauto lindex = mState.mCursorPosition.mLine;\n\t\tauto& line = mLines[lindex];\n\n\t\tif (cindex >= line.size())\n\t\t{\n\t\t\tif (mState.mCursorPosition.mLine < mLines.size() - 1)\n\t\t\t{\n\t\t\t\tmState.mCursorPosition.mLine = std::max(0, std::min((int)mLines.size() - 1, mState.mCursorPosition.mLine + 1));\n\t\t\t\tmState.mCursorPosition.mColumn = 0;\n\t\t\t}\n\t\t\telse\n\t\t\t\treturn;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcindex += UTF8CharLength(line[cindex].mChar);\n\t\t\tmState.mCursorPosition = Coordinates(lindex, GetCharacterColumn(lindex, cindex));\n\t\t\tif (aWordMode)\n\t\t\t\tmState.mCursorPosition = FindNextWord(mState.mCursorPosition);\n\t\t}\n\t}\n\n\tif (aSelect)\n\t{\n\t\tif (oldPos == mInteractiveEnd)\n\t\t\tmInteractiveEnd = SanitizeCoordinates(mState.mCursorPosition);\n\t\telse if (oldPos == mInteractiveStart)\n\t\t\tmInteractiveStart = mState.mCursorPosition;\n\t\telse\n\t\t{\n\t\t\tmInteractiveStart = oldPos;\n\t\t\tmInteractiveEnd = mState.mCursorPosition;\n\t\t}\n\t}\n\telse\n\t\tmInteractiveStart = mInteractiveEnd = mState.mCursorPosition;\n\tSetSelection(mInteractiveStart, mInteractiveEnd, aSelect && aWordMode ? SelectionMode::Word : SelectionMode::Normal);\n\n\tEnsureCursorVisible();\n}\n\nvoid TextEditor::MoveTop(bool aSelect)\n{\n\tauto oldPos = mState.mCursorPosition;\n\tSetCursorPosition(Coordinates(0, 0));\n\n\tif (mState.mCursorPosition != oldPos)\n\t{\n\t\tif (aSelect)\n\t\t{\n\t\t\tmInteractiveEnd = oldPos;\n\t\t\tmInteractiveStart = mState.mCursorPosition;\n\t\t}\n\t\telse\n\t\t\tmInteractiveStart = mInteractiveEnd = mState.mCursorPosition;\n\t\tSetSelection(mInteractiveStart, mInteractiveEnd);\n\t}\n}\n\nvoid TextEditor::TextEditor::MoveBottom(bool aSelect)\n{\n\tauto oldPos = GetCursorPosition();\n\tauto newPos = Coordinates((int)mLines.size() - 1, 0);\n\tSetCursorPosition(newPos);\n\tif (aSelect)\n\t{\n\t\tmInteractiveStart = oldPos;\n\t\tmInteractiveEnd = newPos;\n\t}\n\telse\n\t\tmInteractiveStart = mInteractiveEnd = newPos;\n\tSetSelection(mInteractiveStart, mInteractiveEnd);\n}\n\nvoid TextEditor::MoveHome(bool aSelect)\n{\n\tauto oldPos = mState.mCursorPosition;\n\tSetCursorPosition(Coordinates(mState.mCursorPosition.mLine, 0));\n\n\tif (mState.mCursorPosition != oldPos)\n\t{\n\t\tif (aSelect)\n\t\t{\n\t\t\tif (oldPos == mInteractiveStart)\n\t\t\t\tmInteractiveStart = mState.mCursorPosition;\n\t\t\telse if (oldPos == mInteractiveEnd)\n\t\t\t\tmInteractiveEnd = mState.mCursorPosition;\n\t\t\telse\n\t\t\t{\n\t\t\t\tmInteractiveStart = mState.mCursorPosition;\n\t\t\t\tmInteractiveEnd = oldPos;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t\tmInteractiveStart = mInteractiveEnd = mState.mCursorPosition;\n\t\tSetSelection(mInteractiveStart, mInteractiveEnd);\n\t}\n}\n\nvoid TextEditor::MoveEnd(bool aSelect)\n{\n\tauto oldPos = mState.mCursorPosition;\n\tSetCursorPosition(Coordinates(mState.mCursorPosition.mLine, GetLineMaxColumn(oldPos.mLine)));\n\n\tif (mState.mCursorPosition != oldPos)\n\t{\n\t\tif (aSelect)\n\t\t{\n\t\t\tif (oldPos == mInteractiveEnd)\n\t\t\t\tmInteractiveEnd = mState.mCursorPosition;\n\t\t\telse if (oldPos == mInteractiveStart)\n\t\t\t\tmInteractiveStart = mState.mCursorPosition;\n\t\t\telse\n\t\t\t{\n\t\t\t\tmInteractiveStart = oldPos;\n\t\t\t\tmInteractiveEnd = mState.mCursorPosition;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t\tmInteractiveStart = mInteractiveEnd = mState.mCursorPosition;\n\t\tSetSelection(mInteractiveStart, mInteractiveEnd);\n\t}\n}\n\nvoid TextEditor::Delete()\n{\n\tassert(!mReadOnly);\n\n\tif (mLines.empty())\n\t\treturn;\n\n\tUndoRecord u;\n\tu.mBefore = mState;\n\n\tif (HasSelection())\n\t{\n\t\tu.mRemoved = GetSelectedText();\n\t\tu.mRemovedStart = mState.mSelectionStart;\n\t\tu.mRemovedEnd = mState.mSelectionEnd;\n\n\t\tDeleteSelection();\n\t}\n\telse\n\t{\n\t\tauto pos = GetActualCursorCoordinates();\n\t\tSetCursorPosition(pos);\n\t\tauto& line = mLines[pos.mLine];\n\n\t\tif (pos.mColumn == GetLineMaxColumn(pos.mLine))\n\t\t{\n\t\t\tif (pos.mLine == (int)mLines.size() - 1)\n\t\t\t\treturn;\n\n\t\t\tu.mRemoved = '\\n';\n\t\t\tu.mRemovedStart = u.mRemovedEnd = GetActualCursorCoordinates();\n\t\t\tAdvance(u.mRemovedEnd);\n\n\t\t\tauto& nextLine = mLines[pos.mLine + 1];\n\t\t\tline.insert(line.end(), nextLine.begin(), nextLine.end());\n\t\t\tRemoveLine(pos.mLine + 1);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tauto cindex = GetCharacterIndex(pos);\n\t\t\tu.mRemovedStart = u.mRemovedEnd = GetActualCursorCoordinates();\n\t\t\tu.mRemovedEnd.mColumn++;\n\t\t\tu.mRemoved = GetText(u.mRemovedStart, u.mRemovedEnd);\n\n\t\t\tauto d = UTF8CharLength(line[cindex].mChar);\n\t\t\twhile (d-- > 0 && cindex < (int)line.size())\n\t\t\t\tline.erase(line.begin() + cindex);\n\t\t}\n\n\t\tmTextChanged = true;\n\n\t\tColorize(pos.mLine, 1);\n\t}\n\n\tu.mAfter = mState;\n\tAddUndo(u);\n}\n\nvoid TextEditor::Backspace()\n{\n\tassert(!mReadOnly);\n\n\tif (mLines.empty())\n\t\treturn;\n\n\tUndoRecord u;\n\tu.mBefore = mState;\n\n\tif (HasSelection())\n\t{\n\t\tu.mRemoved = GetSelectedText();\n\t\tu.mRemovedStart = mState.mSelectionStart;\n\t\tu.mRemovedEnd = mState.mSelectionEnd;\n\n\t\tDeleteSelection();\n\t}\n\telse\n\t{\n\t\tauto pos = GetActualCursorCoordinates();\n\t\tSetCursorPosition(pos);\n\n\t\tif (mState.mCursorPosition.mColumn == 0)\n\t\t{\n\t\t\tif (mState.mCursorPosition.mLine == 0)\n\t\t\t\treturn;\n\n\t\t\tu.mRemoved = '\\n';\n\t\t\tu.mRemovedStart = u.mRemovedEnd = Coordinates(pos.mLine - 1, GetLineMaxColumn(pos.mLine - 1));\n\t\t\tAdvance(u.mRemovedEnd);\n\n\t\t\tauto& line = mLines[mState.mCursorPosition.mLine];\n\t\t\tauto& prevLine = mLines[mState.mCursorPosition.mLine - 1];\n\t\t\tauto prevSize = GetLineMaxColumn(mState.mCursorPosition.mLine - 1);\n\t\t\tprevLine.insert(prevLine.end(), line.begin(), line.end());\n\n\t\t\tErrorMarkers etmp;\n\t\t\tfor (auto& i : mErrorMarkers)\n\t\t\t\tetmp.insert(ErrorMarkers::value_type(i.first - 1 == mState.mCursorPosition.mLine ? i.first - 1 : i.first, i.second));\n\t\t\tmErrorMarkers = std::move(etmp);\n\n\t\t\tRemoveLine(mState.mCursorPosition.mLine);\n\t\t\t--mState.mCursorPosition.mLine;\n\t\t\tmState.mCursorPosition.mColumn = prevSize;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tauto& line = mLines[mState.mCursorPosition.mLine];\n\t\t\tauto cindex = GetCharacterIndex(pos) - 1;\n\t\t\tauto cend = cindex + 1;\n\t\t\twhile (cindex > 0 && IsUTFSequence(line[cindex].mChar))\n\t\t\t\t--cindex;\n\n\t\t\t//if (cindex > 0 && UTF8CharLength(line[cindex].mChar) > 1)\n\t\t\t//\t--cindex;\n\n\t\t\tu.mRemovedStart = u.mRemovedEnd = GetActualCursorCoordinates();\n\t\t\t--u.mRemovedStart.mColumn;\n\t\t\t--mState.mCursorPosition.mColumn;\n\n\t\t\twhile (cindex < line.size() && cend-- > cindex)\n\t\t\t{\n\t\t\t\tu.mRemoved += line[cindex].mChar;\n\t\t\t\tline.erase(line.begin() + cindex);\n\t\t\t}\n\t\t}\n\n\t\tmTextChanged = true;\n\n\t\tEnsureCursorVisible();\n\t\tColorize(mState.mCursorPosition.mLine, 1);\n\t}\n\n\tu.mAfter = mState;\n\tAddUndo(u);\n}\n\nvoid TextEditor::SelectWordUnderCursor()\n{\n\tauto c = GetCursorPosition();\n\tSetSelection(FindWordStart(c), FindWordEnd(c));\n}\n\nvoid TextEditor::SelectAll()\n{\n\tSetSelection(Coordinates(0, 0), Coordinates((int)mLines.size(), 0));\n}\n\nbool TextEditor::HasSelection() const\n{\n\treturn mState.mSelectionEnd > mState.mSelectionStart;\n}\n\nvoid TextEditor::Copy()\n{\n\tif (HasSelection())\n\t{\n\t\tImGui::SetClipboardText(GetSelectedText().c_str());\n\t}\n\telse\n\t{\n\t\tif (!mLines.empty())\n\t\t{\n\t\t\tstd::string str;\n\t\t\tauto& line = mLines[GetActualCursorCoordinates().mLine];\n\t\t\tfor (auto& g : line)\n\t\t\t\tstr.push_back(g.mChar);\n\t\t\tImGui::SetClipboardText(str.c_str());\n\t\t}\n\t}\n}\n\nvoid TextEditor::Cut()\n{\n\tif (IsReadOnly())\n\t{\n\t\tCopy();\n\t}\n\telse\n\t{\n\t\tif (HasSelection())\n\t\t{\n\t\t\tUndoRecord u;\n\t\t\tu.mBefore = mState;\n\t\t\tu.mRemoved = GetSelectedText();\n\t\t\tu.mRemovedStart = mState.mSelectionStart;\n\t\t\tu.mRemovedEnd = mState.mSelectionEnd;\n\n\t\t\tCopy();\n\t\t\tDeleteSelection();\n\n\t\t\tu.mAfter = mState;\n\t\t\tAddUndo(u);\n\t\t}\n\t}\n}\n\nvoid TextEditor::Paste()\n{\n\tif (IsReadOnly())\n\t\treturn;\n\n\tauto clipText = ImGui::GetClipboardText();\n\tif (clipText != nullptr && strlen(clipText) > 0)\n\t{\n\t\tUndoRecord u;\n\t\tu.mBefore = mState;\n\n\t\tif (HasSelection())\n\t\t{\n\t\t\tu.mRemoved = GetSelectedText();\n\t\t\tu.mRemovedStart = mState.mSelectionStart;\n\t\t\tu.mRemovedEnd = mState.mSelectionEnd;\n\t\t\tDeleteSelection();\n\t\t}\n\n\t\tu.mAdded = clipText;\n\t\tu.mAddedStart = GetActualCursorCoordinates();\n\n\t\tInsertText(clipText);\n\n\t\tu.mAddedEnd = GetActualCursorCoordinates();\n\t\tu.mAfter = mState;\n\t\tAddUndo(u);\n\t}\n}\n\nbool TextEditor::CanUndo() const\n{\n\treturn !mReadOnly && mUndoIndex > 0;\n}\n\nbool TextEditor::CanRedo() const\n{\n\treturn !mReadOnly && mUndoIndex < (int)mUndoBuffer.size();\n}\n\nvoid TextEditor::Undo(int aSteps)\n{\n\twhile (CanUndo() && aSteps-- > 0)\n\t\tmUndoBuffer[--mUndoIndex].Undo(this);\n}\n\nvoid TextEditor::Redo(int aSteps)\n{\n\twhile (CanRedo() && aSteps-- > 0)\n\t\tmUndoBuffer[mUndoIndex++].Redo(this);\n}\n\nconst TextEditor::Palette & TextEditor::GetDarkPalette()\n{\n\tconst static Palette p = { {\n\t\t\t0xff7f7f7f,\t// Default\n\t\t\t0xffd69c56,\t// Keyword\t\n\t\t\t0xff00ff00,\t// Number\n\t\t\t0xff7070e0,\t// String\n\t\t\t0xff70a0e0, // Char literal\n\t\t\t0xffffffff, // Punctuation\n\t\t\t0xff408080,\t// Preprocessor\n\t\t\t0xffaaaaaa, // Identifier\n\t\t\t0xff9bc64d, // Known identifier\n\t\t\t0xffc040a0, // Preproc identifier\n\t\t\t0xff206020, // Comment (single line)\n\t\t\t0xff406020, // Comment (multi line)\n\t\t\t0xff101010, // Background\n\t\t\t0xffe0e0e0, // Cursor\n\t\t\t0x80a06020, // Selection\n\t\t\t0x800020ff, // ErrorMarker\n\t\t\t0x40f08000, // Breakpoint\n\t\t\t0xff707000, // Line number\n\t\t\t0x40000000, // Current line fill\n\t\t\t0x40808080, // Current line fill (inactive)\n\t\t\t0x40a0a0a0, // Current line edge\n\t\t} };\n\treturn p;\n}\n\nconst TextEditor::Palette & TextEditor::GetLightPalette()\n{\n\tconst static Palette p = { {\n\t\t\t0xff7f7f7f,\t// None\n\t\t\t0xffff0c06,\t// Keyword\t\n\t\t\t0xff008000,\t// Number\n\t\t\t0xff2020a0,\t// String\n\t\t\t0xff304070, // Char literal\n\t\t\t0xff000000, // Punctuation\n\t\t\t0xff406060,\t// Preprocessor\n\t\t\t0xff404040, // Identifier\n\t\t\t0xff606010, // Known identifier\n\t\t\t0xffc040a0, // Preproc identifier\n\t\t\t0xff205020, // Comment (single line)\n\t\t\t0xff405020, // Comment (multi line)\n\t\t\t0xffffffff, // Background\n\t\t\t0xff000000, // Cursor\n\t\t\t0x80600000, // Selection\n\t\t\t0xa00010ff, // ErrorMarker\n\t\t\t0x80f08000, // Breakpoint\n\t\t\t0xff505000, // Line number\n\t\t\t0x40000000, // Current line fill\n\t\t\t0x40808080, // Current line fill (inactive)\n\t\t\t0x40000000, // Current line edge\n\t\t} };\n\treturn p;\n}\n\nconst TextEditor::Palette & TextEditor::GetRetroBluePalette()\n{\n\tconst static Palette p = { {\n\t\t\t0xff00ffff,\t// None\n\t\t\t0xffffff00,\t// Keyword\t\n\t\t\t0xff00ff00,\t// Number\n\t\t\t0xff808000,\t// String\n\t\t\t0xff808000, // Char literal\n\t\t\t0xffffffff, // Punctuation\n\t\t\t0xff008000,\t// Preprocessor\n\t\t\t0xff00ffff, // Identifier\n\t\t\t0xffffffff, // Known identifier\n\t\t\t0xffff00ff, // Preproc identifier\n\t\t\t0xff808080, // Comment (single line)\n\t\t\t0xff404040, // Comment (multi line)\n\t\t\t0xff800000, // Background\n\t\t\t0xff0080ff, // Cursor\n\t\t\t0x80ffff00, // Selection\n\t\t\t0xa00000ff, // ErrorMarker\n\t\t\t0x80ff8000, // Breakpoint\n\t\t\t0xff808000, // Line number\n\t\t\t0x40000000, // Current line fill\n\t\t\t0x40808080, // Current line fill (inactive)\n\t\t\t0x40000000, // Current line edge\n\t\t} };\n\treturn p;\n}\n\n\nstd::string TextEditor::GetText() const\n{\n\treturn GetText(Coordinates(), Coordinates((int)mLines.size(), 0));\n}\n\nstd::vector<std::string> TextEditor::GetTextLines() const\n{\n\tstd::vector<std::string> result;\n\n\tresult.reserve(mLines.size());\n\n\tfor (auto & line : mLines)\n\t{\n\t\tstd::string text;\n\n\t\ttext.resize(line.size());\n\n\t\tfor (size_t i = 0; i < line.size(); ++i)\n\t\t\ttext[i] = line[i].mChar;\n\n\t\tresult.emplace_back(std::move(text));\n\t}\n\n\treturn result;\n}\n\nstd::string TextEditor::GetSelectedText() const\n{\n\treturn GetText(mState.mSelectionStart, mState.mSelectionEnd);\n}\n\nstd::string TextEditor::GetCurrentLineText()const\n{\n\tauto lineLength = GetLineMaxColumn(mState.mCursorPosition.mLine);\n\treturn GetText(\n\t\tCoordinates(mState.mCursorPosition.mLine, 0),\n\t\tCoordinates(mState.mCursorPosition.mLine, lineLength));\n}\n\nvoid TextEditor::ProcessInputs()\n{\n}\n\nvoid TextEditor::Colorize(int aFromLine, int aLines)\n{\n\tint toLine = aLines == -1 ? (int)mLines.size() : std::min((int)mLines.size(), aFromLine + aLines);\n\tmColorRangeMin = std::min(mColorRangeMin, aFromLine);\n\tmColorRangeMax = std::max(mColorRangeMax, toLine);\n\tmColorRangeMin = std::max(0, mColorRangeMin);\n\tmColorRangeMax = std::max(mColorRangeMin, mColorRangeMax);\n\tmCheckComments = true;\n}\n\nvoid TextEditor::ColorizeRange(int aFromLine, int aToLine)\n{\n\tif (mLines.empty() || aFromLine >= aToLine)\n\t\treturn;\n\n\tstd::string buffer;\n\tstd::cmatch results;\n\tstd::string id;\n\n\tint endLine = std::max(0, std::min((int)mLines.size(), aToLine));\n\tfor (int i = aFromLine; i < endLine; ++i)\n\t{\n\t\tauto& line = mLines[i];\n\n\t\tif (line.empty())\n\t\t\tcontinue;\n\n\t\tbuffer.resize(line.size());\n\t\tfor (size_t j = 0; j < line.size(); ++j)\n\t\t{\n\t\t\tauto& col = line[j];\n\t\t\tbuffer[j] = col.mChar;\n\t\t\tcol.mColorIndex = PaletteIndex::Default;\n\t\t}\n\n\t\tconst char * bufferBegin = &buffer.front();\n\t\tconst char * bufferEnd = bufferBegin + buffer.size();\n\n\t\tauto last = bufferEnd;\n\n\t\tfor (auto first = bufferBegin; first != last; )\n\t\t{\n\t\t\tconst char * token_begin = nullptr;\n\t\t\tconst char * token_end = nullptr;\n\t\t\tPaletteIndex token_color = PaletteIndex::Default;\n\n\t\t\tbool hasTokenizeResult = false;\n\n\t\t\tif (mLanguageDefinition.mTokenize != nullptr)\n\t\t\t{\n\t\t\t\tif (mLanguageDefinition.mTokenize(first, last, token_begin, token_end, token_color))\n\t\t\t\t\thasTokenizeResult = true;\n\t\t\t}\n\n\t\t\tif (hasTokenizeResult == false)\n\t\t\t{\n\t\t\t\t// todo : remove\n\t\t\t\t//printf(\"using regex for %.*s\\n\", first + 10 < last ? 10 : int(last - first), first);\n\n\t\t\t\tfor (auto& p : mRegexList)\n\t\t\t\t{\n\t\t\t\t\tif (std::regex_search(first, last, results, p.first, std::regex_constants::match_continuous))\n\t\t\t\t\t{\n\t\t\t\t\t\thasTokenizeResult = true;\n\n\t\t\t\t\t\tauto& v = *results.begin();\n\t\t\t\t\t\ttoken_begin = v.first;\n\t\t\t\t\t\ttoken_end = v.second;\n\t\t\t\t\t\ttoken_color = p.second;\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 (hasTokenizeResult == false)\n\t\t\t{\n\t\t\t\tfirst++;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tconst size_t token_length = token_end - token_begin;\n\n\t\t\t\tif (token_color == PaletteIndex::Identifier)\n\t\t\t\t{\n\t\t\t\t\tid.assign(token_begin, token_end);\n\n\t\t\t\t\t// todo : allmost all language definitions use lower case to specify keywords, so shouldn't this use ::tolower ?\n\t\t\t\t\tif (!mLanguageDefinition.mCaseSensitive)\n\t\t\t\t\t\tstd::transform(id.begin(), id.end(), id.begin(), ::toupper);\n\n\t\t\t\t\tif (!line[first - bufferBegin].mPreprocessor)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (mLanguageDefinition.mKeywords.count(id) != 0)\n\t\t\t\t\t\t\ttoken_color = PaletteIndex::Keyword;\n\t\t\t\t\t\telse if (mLanguageDefinition.mIdentifiers.count(id) != 0)\n\t\t\t\t\t\t\ttoken_color = PaletteIndex::KnownIdentifier;\n\t\t\t\t\t\telse if (mLanguageDefinition.mPreprocIdentifiers.count(id) != 0)\n\t\t\t\t\t\t\ttoken_color = PaletteIndex::PreprocIdentifier;\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 (mLanguageDefinition.mPreprocIdentifiers.count(id) != 0)\n\t\t\t\t\t\t\ttoken_color = PaletteIndex::PreprocIdentifier;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tfor (size_t j = 0; j < token_length; ++j)\n\t\t\t\t\tline[(token_begin - bufferBegin) + j].mColorIndex = token_color;\n\n\t\t\t\tfirst = token_end;\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid TextEditor::ColorizeInternal()\n{\n\tif (mLines.empty() || !mColorizerEnabled)\n\t\treturn;\n\n\tif (mCheckComments)\n\t{\n\t\tauto endLine = mLines.size();\n\t\tauto endIndex = 0;\n\t\tauto commentStartLine = endLine;\n\t\tauto commentStartIndex = endIndex;\n\t\tauto withinString = false;\n\t\tauto withinSingleLineComment = false;\n\t\tauto withinPreproc = false;\n\t\tauto firstChar = true;\t\t\t// there is no other non-whitespace characters in the line before\n\t\tauto concatenate = false;\t\t// '\\' on the very end of the line\n\t\tauto currentLine = 0;\n\t\tauto currentIndex = 0;\n\t\twhile (currentLine < endLine || currentIndex < endIndex)\n\t\t{\n\t\t\tauto& line = mLines[currentLine];\n\n\t\t\tif (currentIndex == 0 && !concatenate)\n\t\t\t{\n\t\t\t\twithinSingleLineComment = false;\n\t\t\t\twithinPreproc = false;\n\t\t\t\tfirstChar = true;\n\t\t\t}\n\n\t\t\tconcatenate = false;\n\n\t\t\tif (!line.empty())\n\t\t\t{\n\t\t\t\tauto& g = line[currentIndex];\n\t\t\t\tauto c = g.mChar;\n\n\t\t\t\tif (c != mLanguageDefinition.mPreprocChar && !isspace(c))\n\t\t\t\t\tfirstChar = false;\n\n\t\t\t\tif (currentIndex == (int)line.size() - 1 && line[line.size() - 1].mChar == '\\\\')\n\t\t\t\t\tconcatenate = true;\n\n\t\t\t\tbool inComment = (commentStartLine < currentLine || (commentStartLine == currentLine && commentStartIndex <= currentIndex));\n\n\t\t\t\tif (withinString)\n\t\t\t\t{\n\t\t\t\t\tline[currentIndex].mMultiLineComment = inComment;\n\n\t\t\t\t\tif (c == '\\\"')\n\t\t\t\t\t{\n\t\t\t\t\t\tif (currentIndex + 1 < (int)line.size() && line[currentIndex + 1].mChar == '\\\"')\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcurrentIndex += 1;\n\t\t\t\t\t\t\tif (currentIndex < (int)line.size())\n\t\t\t\t\t\t\t\tline[currentIndex].mMultiLineComment = inComment;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\twithinString = false;\n\t\t\t\t\t}\n\t\t\t\t\telse if (c == '\\\\')\n\t\t\t\t\t{\n\t\t\t\t\t\tcurrentIndex += 1;\n\t\t\t\t\t\tif (currentIndex < (int)line.size())\n\t\t\t\t\t\t\tline[currentIndex].mMultiLineComment = inComment;\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\tif (firstChar && c == mLanguageDefinition.mPreprocChar)\n\t\t\t\t\t\twithinPreproc = true;\n\n\t\t\t\t\tif (c == '\\\"')\n\t\t\t\t\t{\n\t\t\t\t\t\twithinString = true;\n\t\t\t\t\t\tline[currentIndex].mMultiLineComment = inComment;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tauto pred = [](const char& a, const Glyph& b) { return a == b.mChar; };\n\t\t\t\t\t\tauto from = line.begin() + currentIndex;\n\t\t\t\t\t\tauto& startStr = mLanguageDefinition.mCommentStart;\n\t\t\t\t\t\tauto& singleStartStr = mLanguageDefinition.mSingleLineComment;\n\n\t\t\t\t\t\tif (singleStartStr.size() > 0 &&\n\t\t\t\t\t\t\tcurrentIndex + singleStartStr.size() <= line.size() &&\n\t\t\t\t\t\t\tequals(singleStartStr.begin(), singleStartStr.end(), from, from + singleStartStr.size(), pred))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\twithinSingleLineComment = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (!withinSingleLineComment && currentIndex + startStr.size() <= line.size() &&\n\t\t\t\t\t\t\tequals(startStr.begin(), startStr.end(), from, from + startStr.size(), pred))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcommentStartLine = currentLine;\n\t\t\t\t\t\t\tcommentStartIndex = currentIndex;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tinComment = inComment = (commentStartLine < currentLine || (commentStartLine == currentLine && commentStartIndex <= currentIndex));\n\n\t\t\t\t\t\tline[currentIndex].mMultiLineComment = inComment;\n\t\t\t\t\t\tline[currentIndex].mComment = withinSingleLineComment;\n\n\t\t\t\t\t\tauto& endStr = mLanguageDefinition.mCommentEnd;\n\t\t\t\t\t\tif (currentIndex + 1 >= (int)endStr.size() &&\n\t\t\t\t\t\t\tequals(endStr.begin(), endStr.end(), from + 1 - endStr.size(), from + 1, pred))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcommentStartIndex = endIndex;\n\t\t\t\t\t\t\tcommentStartLine = endLine;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tline[currentIndex].mPreprocessor = withinPreproc;\n\t\t\t\tcurrentIndex += UTF8CharLength(c);\n\t\t\t\tif (currentIndex >= (int)line.size())\n\t\t\t\t{\n\t\t\t\t\tcurrentIndex = 0;\n\t\t\t\t\t++currentLine;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcurrentIndex = 0;\n\t\t\t\t++currentLine;\n\t\t\t}\n\t\t}\n\t\tmCheckComments = false;\n\t}\n\n\tif (mColorRangeMin < mColorRangeMax)\n\t{\n\t\tconst int increment = (mLanguageDefinition.mTokenize == nullptr) ? 10 : 10000;\n\t\tconst int to = std::min(mColorRangeMin + increment, mColorRangeMax);\n\t\tColorizeRange(mColorRangeMin, to);\n\t\tmColorRangeMin = to;\n\n\t\tif (mColorRangeMax == mColorRangeMin)\n\t\t{\n\t\t\tmColorRangeMin = std::numeric_limits<int>::max();\n\t\t\tmColorRangeMax = 0;\n\t\t}\n\t\treturn;\n\t}\n}\n\nfloat TextEditor::TextDistanceToLineStart(const Coordinates& aFrom) const\n{\n\tauto& line = mLines[aFrom.mLine];\n\tfloat distance = 0.0f;\n\tfloat spaceSize = ImGui::GetFont()->CalcTextSizeA(ImGui::GetFontSize(), FLT_MAX, -1.0f, \" \", nullptr, nullptr).x;\n\tint colIndex = GetCharacterIndex(aFrom);\n\tfor (size_t it = 0u; it < line.size() && it < colIndex; )\n\t{\n\t\tif (line[it].mChar == '\\t')\n\t\t{\n\t\t\tdistance = (1.0f + std::floor((1.0f + distance) / (float(mTabSize) * spaceSize))) * (float(mTabSize) * spaceSize);\n\t\t\t++it;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tauto d = UTF8CharLength(line[it].mChar);\n\t\t\tchar tempCString[7];\n\t\t\tint i = 0;\n\t\t\tfor (; i < 6 && d-- > 0 && it < (int)line.size(); i++, it++)\n\t\t\t\ttempCString[i] = line[it].mChar;\n\n\t\t\ttempCString[i] = '\\0';\n\t\t\tdistance += ImGui::GetFont()->CalcTextSizeA(ImGui::GetFontSize(), FLT_MAX, -1.0f, tempCString, nullptr, nullptr).x;\n\t\t}\n\t}\n\n\treturn distance;\n}\n\nvoid TextEditor::EnsureCursorVisible()\n{\n\tif (!mWithinRender)\n\t{\n\t\tmScrollToCursor = true;\n\t\treturn;\n\t}\n\n\tfloat scrollX = ImGui::GetScrollX();\n\tfloat scrollY = ImGui::GetScrollY();\n\n\tauto height = ImGui::GetWindowHeight();\n\tauto width = ImGui::GetWindowWidth();\n\n\tauto top = 1 + (int)ceil(scrollY / mCharAdvance.y);\n\tauto bottom = (int)ceil((scrollY + height) / mCharAdvance.y);\n\n\tauto left = (int)ceil(scrollX / mCharAdvance.x);\n\tauto right = (int)ceil((scrollX + width) / mCharAdvance.x);\n\n\tauto pos = GetActualCursorCoordinates();\n\tauto len = TextDistanceToLineStart(pos);\n\n\tif (pos.mLine < top)\n\t\tImGui::SetScrollY(std::max(0.0f, (pos.mLine - 1) * mCharAdvance.y));\n\tif (pos.mLine > bottom - 4)\n\t\tImGui::SetScrollY(std::max(0.0f, (pos.mLine + 4) * mCharAdvance.y - height));\n\tif (len + mTextStart < left + 4)\n\t\tImGui::SetScrollX(std::max(0.0f, len + mTextStart - 4));\n\tif (len + mTextStart > right - 4)\n\t\tImGui::SetScrollX(std::max(0.0f, len + mTextStart + 4 - width));\n}\n\nint TextEditor::GetPageSize() const\n{\n\tauto height = ImGui::GetWindowHeight() - 20.0f;\n\treturn (int)floor(height / mCharAdvance.y);\n}\n\nTextEditor::UndoRecord::UndoRecord(\n\tconst std::string& aAdded,\n\tconst TextEditor::Coordinates aAddedStart,\n\tconst TextEditor::Coordinates aAddedEnd,\n\tconst std::string& aRemoved,\n\tconst TextEditor::Coordinates aRemovedStart,\n\tconst TextEditor::Coordinates aRemovedEnd,\n\tTextEditor::EditorState& aBefore,\n\tTextEditor::EditorState& aAfter)\n\t: mAdded(aAdded)\n\t, mAddedStart(aAddedStart)\n\t, mAddedEnd(aAddedEnd)\n\t, mRemoved(aRemoved)\n\t, mRemovedStart(aRemovedStart)\n\t, mRemovedEnd(aRemovedEnd)\n\t, mBefore(aBefore)\n\t, mAfter(aAfter)\n{\n\tassert(mAddedStart <= mAddedEnd);\n\tassert(mRemovedStart <= mRemovedEnd);\n}\n\nvoid TextEditor::UndoRecord::Undo(TextEditor * aEditor)\n{\n\tif (!mAdded.empty())\n\t{\n\t\taEditor->DeleteRange(mAddedStart, mAddedEnd);\n\t\taEditor->Colorize(mAddedStart.mLine - 1, mAddedEnd.mLine - mAddedStart.mLine + 2);\n\t}\n\n\tif (!mRemoved.empty())\n\t{\n\t\tauto start = mRemovedStart;\n\t\taEditor->InsertTextAt(start, mRemoved.c_str());\n\t\taEditor->Colorize(mRemovedStart.mLine - 1, mRemovedEnd.mLine - mRemovedStart.mLine + 2);\n\t}\n\n\taEditor->mState = mBefore;\n\taEditor->EnsureCursorVisible();\n\n}\n\nvoid TextEditor::UndoRecord::Redo(TextEditor * aEditor)\n{\n\tif (!mRemoved.empty())\n\t{\n\t\taEditor->DeleteRange(mRemovedStart, mRemovedEnd);\n\t\taEditor->Colorize(mRemovedStart.mLine - 1, mRemovedEnd.mLine - mRemovedStart.mLine + 1);\n\t}\n\n\tif (!mAdded.empty())\n\t{\n\t\tauto start = mAddedStart;\n\t\taEditor->InsertTextAt(start, mAdded.c_str());\n\t\taEditor->Colorize(mAddedStart.mLine - 1, mAddedEnd.mLine - mAddedStart.mLine + 1);\n\t}\n\n\taEditor->mState = mAfter;\n\taEditor->EnsureCursorVisible();\n}\n\nstatic bool TokenizeCStyleString(const char * in_begin, const char * in_end, const char *& out_begin, const char *& out_end)\n{\n\tconst char * p = in_begin;\n\n\tif (*p == '\"')\n\t{\n\t\tp++;\n\n\t\twhile (p < in_end)\n\t\t{\n\t\t\t// handle end of string\n\t\t\tif (*p == '\"')\n\t\t\t{\n\t\t\t\tout_begin = in_begin;\n\t\t\t\tout_end = p + 1;\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\t// handle escape character for \"\n\t\t\tif (*p == '\\\\' && p + 1 < in_end && p[1] == '\"')\n\t\t\t\tp++;\n\n\t\t\tp++;\n\t\t}\n\t}\n\n\treturn false;\n}\n\nstatic bool TokenizeCStyleCharacterLiteral(const char * in_begin, const char * in_end, const char *& out_begin, const char *& out_end)\n{\n\tconst char * p = in_begin;\n\n\tif (*p == '\\'')\n\t{\n\t\tp++;\n\n\t\t// handle escape characters\n\t\tif (p < in_end && *p == '\\\\')\n\t\t\tp++;\n\n\t\tif (p < in_end)\n\t\t\tp++;\n\n\t\t// handle end of character literal\n\t\tif (p < in_end && *p == '\\'')\n\t\t{\n\t\t\tout_begin = in_begin;\n\t\t\tout_end = p + 1;\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\nstatic bool TokenizeCStyleIdentifier(const char * in_begin, const char * in_end, const char *& out_begin, const char *& out_end)\n{\n\tconst char * p = in_begin;\n\n\tif ((*p >= 'a' && *p <= 'z') || (*p >= 'A' && *p <= 'Z') || *p == '_')\n\t{\n\t\tp++;\n\n\t\twhile ((p < in_end) && ((*p >= 'a' && *p <= 'z') || (*p >= 'A' && *p <= 'Z') || (*p >= '0' && *p <= '9') || *p == '_'))\n\t\t\tp++;\n\n\t\tout_begin = in_begin;\n\t\tout_end = p;\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nstatic bool TokenizeCStyleNumber(const char * in_begin, const char * in_end, const char *& out_begin, const char *& out_end)\n{\n\tconst char * p = in_begin;\n\n\tconst bool startsWithNumber = *p >= '0' && *p <= '9';\n\n\tif (*p != '+' && *p != '-' && !startsWithNumber)\n\t\treturn false;\n\n\tp++;\n\n\tbool hasNumber = startsWithNumber;\n\n\twhile (p < in_end && (*p >= '0' && *p <= '9'))\n\t{\n\t\thasNumber = true;\n\n\t\tp++;\n\t}\n\n\tif (hasNumber == false)\n\t\treturn false;\n\n\tbool isFloat = false;\n\tbool isHex = false;\n\tbool isBinary = false;\n\n\tif (p < in_end)\n\t{\n\t\tif (*p == '.')\n\t\t{\n\t\t\tisFloat = true;\n\n\t\t\tp++;\n\n\t\t\twhile (p < in_end && (*p >= '0' && *p <= '9'))\n\t\t\t\tp++;\n\t\t}\n\t\telse if (*p == 'x' || *p == 'X')\n\t\t{\n\t\t\t// hex formatted integer of the type 0xef80\n\n\t\t\tisHex = true;\n\n\t\t\tp++;\n\n\t\t\twhile (p < in_end && ((*p >= '0' && *p <= '9') || (*p >= 'a' && *p <= 'f') || (*p >= 'A' && *p <= 'F')))\n\t\t\t\tp++;\n\t\t}\n\t\telse if (*p == 'b' || *p == 'B')\n\t\t{\n\t\t\t// binary formatted integer of the type 0b01011101\n\n\t\t\tisBinary = true;\n\n\t\t\tp++;\n\n\t\t\twhile (p < in_end && (*p >= '0' && *p <= '1'))\n\t\t\t\tp++;\n\t\t}\n\t}\n\n\tif (isHex == false && isBinary == false)\n\t{\n\t\t// floating point exponent\n\t\tif (p < in_end && (*p == 'e' || *p == 'E'))\n\t\t{\n\t\t\tisFloat = true;\n\n\t\t\tp++;\n\n\t\t\tif (p < in_end && (*p == '+' || *p == '-'))\n\t\t\t\tp++;\n\n\t\t\tbool hasDigits = false;\n\n\t\t\twhile (p < in_end && (*p >= '0' && *p <= '9'))\n\t\t\t{\n\t\t\t\thasDigits = true;\n\n\t\t\t\tp++;\n\t\t\t}\n\n\t\t\tif (hasDigits == false)\n\t\t\t\treturn false;\n\t\t}\n\n\t\t// single precision floating point type\n\t\tif (p < in_end && *p == 'f')\n\t\t\tp++;\n\t}\n\n\tif (isFloat == false)\n\t{\n\t\t// integer size type\n\t\twhile (p < in_end && (*p == 'u' || *p == 'U' || *p == 'l' || *p == 'L'))\n\t\t\tp++;\n\t}\n\n\tout_begin = in_begin;\n\tout_end = p;\n\treturn true;\n}\n\nstatic bool TokenizeCStylePunctuation(const char * in_begin, const char * in_end, const char *& out_begin, const char *& out_end)\n{\n\t(void)in_end;\n\n\tswitch (*in_begin)\n\t{\n\tcase '[':\n\tcase ']':\n\tcase '{':\n\tcase '}':\n\tcase '!':\n\tcase '%':\n\tcase '^':\n\tcase '&':\n\tcase '*':\n\tcase '(':\n\tcase ')':\n\tcase '-':\n\tcase '+':\n\tcase '=':\n\tcase '~':\n\tcase '|':\n\tcase '<':\n\tcase '>':\n\tcase '?':\n\tcase ':':\n\tcase '/':\n\tcase ';':\n\tcase ',':\n\tcase '.':\n\t\tout_begin = in_begin;\n\t\tout_end = in_begin + 1;\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nconst TextEditor::LanguageDefinition& TextEditor::LanguageDefinition::CPlusPlus()\n{\n\tstatic bool inited = false;\n\tstatic LanguageDefinition langDef;\n\tif (!inited)\n\t{\n\t\tstatic const char* const cppKeywords[] = {\n\t\t\t\"alignas\", \"alignof\", \"and\", \"and_eq\", \"asm\", \"atomic_cancel\", \"atomic_commit\", \"atomic_noexcept\", \"auto\", \"bitand\", \"bitor\", \"bool\", \"break\", \"case\", \"catch\", \"char\", \"char16_t\", \"char32_t\", \"class\",\n\t\t\t\"compl\", \"concept\", \"const\", \"constexpr\", \"const_cast\", \"continue\", \"decltype\", \"default\", \"delete\", \"do\", \"double\", \"dynamic_cast\", \"else\", \"enum\", \"explicit\", \"export\", \"extern\", \"false\", \"float\",\n\t\t\t\"for\", \"friend\", \"goto\", \"if\", \"import\", \"inline\", \"int\", \"long\", \"module\", \"mutable\", \"namespace\", \"new\", \"noexcept\", \"not\", \"not_eq\", \"nullptr\", \"operator\", \"or\", \"or_eq\", \"private\", \"protected\", \"public\",\n\t\t\t\"register\", \"reinterpret_cast\", \"requires\", \"return\", \"short\", \"signed\", \"sizeof\", \"static\", \"static_assert\", \"static_cast\", \"struct\", \"switch\", \"synchronized\", \"template\", \"this\", \"thread_local\",\n\t\t\t\"throw\", \"true\", \"try\", \"typedef\", \"typeid\", \"typename\", \"union\", \"unsigned\", \"using\", \"virtual\", \"void\", \"volatile\", \"wchar_t\", \"while\", \"xor\", \"xor_eq\"\n\t\t};\n\t\tfor (auto& k : cppKeywords)\n\t\t\tlangDef.mKeywords.insert(k);\n\n\t\tstatic const char* const identifiers[] = {\n\t\t\t\"abort\", \"abs\", \"acos\", \"asin\", \"atan\", \"atexit\", \"atof\", \"atoi\", \"atol\", \"ceil\", \"clock\", \"cosh\", \"ctime\", \"div\", \"exit\", \"fabs\", \"floor\", \"fmod\", \"getchar\", \"getenv\", \"isalnum\", \"isalpha\", \"isdigit\", \"isgraph\",\n\t\t\t\"ispunct\", \"isspace\", \"isupper\", \"kbhit\", \"log10\", \"log2\", \"log\", \"memcmp\", \"modf\", \"pow\", \"printf\", \"sprintf\", \"snprintf\", \"putchar\", \"putenv\", \"puts\", \"rand\", \"remove\", \"rename\", \"sinh\", \"sqrt\", \"srand\", \"strcat\", \"strcmp\", \"strerror\", \"time\", \"tolower\", \"toupper\",\n\t\t\t\"std\", \"string\", \"vector\", \"map\", \"unordered_map\", \"set\", \"unordered_set\", \"min\", \"max\"\n\t\t};\n\t\tfor (auto& k : identifiers)\n\t\t{\n\t\t\tIdentifier id;\n\t\t\tid.mDeclaration = \"Built-in function\";\n\t\t\tlangDef.mIdentifiers.insert(std::make_pair(std::string(k), id));\n\t\t}\n\n\t\tlangDef.mTokenize = [](const char * in_begin, const char * in_end, const char *& out_begin, const char *& out_end, PaletteIndex & paletteIndex) -> bool\n\t\t{\n\t\t\tpaletteIndex = PaletteIndex::Max;\n\n\t\t\twhile (in_begin < in_end && isascii(*in_begin) && isblank(*in_begin))\n\t\t\t\tin_begin++;\n\n\t\t\tif (in_begin == in_end)\n\t\t\t{\n\t\t\t\tout_begin = in_end;\n\t\t\t\tout_end = in_end;\n\t\t\t\tpaletteIndex = PaletteIndex::Default;\n\t\t\t}\n\t\t\telse if (TokenizeCStyleString(in_begin, in_end, out_begin, out_end))\n\t\t\t\tpaletteIndex = PaletteIndex::String;\n\t\t\telse if (TokenizeCStyleCharacterLiteral(in_begin, in_end, out_begin, out_end))\n\t\t\t\tpaletteIndex = PaletteIndex::CharLiteral;\n\t\t\telse if (TokenizeCStyleIdentifier(in_begin, in_end, out_begin, out_end))\n\t\t\t\tpaletteIndex = PaletteIndex::Identifier;\n\t\t\telse if (TokenizeCStyleNumber(in_begin, in_end, out_begin, out_end))\n\t\t\t\tpaletteIndex = PaletteIndex::Number;\n\t\t\telse if (TokenizeCStylePunctuation(in_begin, in_end, out_begin, out_end))\n\t\t\t\tpaletteIndex = PaletteIndex::Punctuation;\n\n\t\t\treturn paletteIndex != PaletteIndex::Max;\n\t\t};\n\n\t\tlangDef.mCommentStart = \"/*\";\n\t\tlangDef.mCommentEnd = \"*/\";\n\t\tlangDef.mSingleLineComment = \"//\";\n\n\t\tlangDef.mCaseSensitive = true;\n\t\tlangDef.mAutoIndentation = true;\n\n\t\tlangDef.mName = \"C++\";\n\n\t\tinited = true;\n\t}\n\treturn langDef;\n}\n\nconst TextEditor::LanguageDefinition& TextEditor::LanguageDefinition::HLSL()\n{\n\tstatic bool inited = false;\n\tstatic LanguageDefinition langDef;\n\tif (!inited)\n\t{\n\t\tstatic const char* const keywords[] = {\n\t\t\t\"AppendStructuredBuffer\", \"asm\", \"asm_fragment\", \"BlendState\", \"bool\", \"break\", \"Buffer\", \"ByteAddressBuffer\", \"case\", \"cbuffer\", \"centroid\", \"class\", \"column_major\", \"compile\", \"compile_fragment\",\n\t\t\t\"CompileShader\", \"const\", \"continue\", \"ComputeShader\", \"ConsumeStructuredBuffer\", \"default\", \"DepthStencilState\", \"DepthStencilView\", \"discard\", \"do\", \"double\", \"DomainShader\", \"dword\", \"else\",\n\t\t\t\"export\", \"extern\", \"false\", \"float\", \"for\", \"fxgroup\", \"GeometryShader\", \"groupshared\", \"half\", \"Hullshader\", \"if\", \"in\", \"inline\", \"inout\", \"InputPatch\", \"int\", \"interface\", \"line\", \"lineadj\",\n\t\t\t\"linear\", \"LineStream\", \"matrix\", \"min16float\", \"min10float\", \"min16int\", \"min12int\", \"min16uint\", \"namespace\", \"nointerpolation\", \"noperspective\", \"NULL\", \"out\", \"OutputPatch\", \"packoffset\",\n\t\t\t\"pass\", \"pixelfragment\", \"PixelShader\", \"point\", \"PointStream\", \"precise\", \"RasterizerState\", \"RenderTargetView\", \"return\", \"register\", \"row_major\", \"RWBuffer\", \"RWByteAddressBuffer\", \"RWStructuredBuffer\",\n\t\t\t\"RWTexture1D\", \"RWTexture1DArray\", \"RWTexture2D\", \"RWTexture2DArray\", \"RWTexture3D\", \"sample\", \"sampler\", \"SamplerState\", \"SamplerComparisonState\", \"shared\", \"snorm\", \"stateblock\", \"stateblock_state\",\n\t\t\t\"static\", \"string\", \"struct\", \"switch\", \"StructuredBuffer\", \"tbuffer\", \"technique\", \"technique10\", \"technique11\", \"texture\", \"Texture1D\", \"Texture1DArray\", \"Texture2D\", \"Texture2DArray\", \"Texture2DMS\",\n\t\t\t\"Texture2DMSArray\", \"Texture3D\", \"TextureCube\", \"TextureCubeArray\", \"true\", \"typedef\", \"triangle\", \"triangleadj\", \"TriangleStream\", \"uint\", \"uniform\", \"unorm\", \"unsigned\", \"vector\", \"vertexfragment\",\n\t\t\t\"VertexShader\", \"void\", \"volatile\", \"while\",\n\t\t\t\"bool1\",\"bool2\",\"bool3\",\"bool4\",\"double1\",\"double2\",\"double3\",\"double4\", \"float1\", \"float2\", \"float3\", \"float4\", \"int1\", \"int2\", \"int3\", \"int4\", \"in\", \"out\", \"inout\",\n\t\t\t\"uint1\", \"uint2\", \"uint3\", \"uint4\", \"dword1\", \"dword2\", \"dword3\", \"dword4\", \"half1\", \"half2\", \"half3\", \"half4\",\n\t\t\t\"float1x1\",\"float2x1\",\"float3x1\",\"float4x1\",\"float1x2\",\"float2x2\",\"float3x2\",\"float4x2\",\n\t\t\t\"float1x3\",\"float2x3\",\"float3x3\",\"float4x3\",\"float1x4\",\"float2x4\",\"float3x4\",\"float4x4\",\n\t\t\t\"half1x1\",\"half2x1\",\"half3x1\",\"half4x1\",\"half1x2\",\"half2x2\",\"half3x2\",\"half4x2\",\n\t\t\t\"half1x3\",\"half2x3\",\"half3x3\",\"half4x3\",\"half1x4\",\"half2x4\",\"half3x4\",\"half4x4\",\n\t\t};\n\t\tfor (auto& k : keywords)\n\t\t\tlangDef.mKeywords.insert(k);\n\n\t\tstatic const char* const identifiers[] = {\n\t\t\t\"abort\", \"abs\", \"acos\", \"all\", \"AllMemoryBarrier\", \"AllMemoryBarrierWithGroupSync\", \"any\", \"asdouble\", \"asfloat\", \"asin\", \"asint\", \"asint\", \"asuint\",\n\t\t\t\"asuint\", \"atan\", \"atan2\", \"ceil\", \"CheckAccessFullyMapped\", \"clamp\", \"clip\", \"cos\", \"cosh\", \"countbits\", \"cross\", \"D3DCOLORtoUBYTE4\", \"ddx\",\n\t\t\t\"ddx_coarse\", \"ddx_fine\", \"ddy\", \"ddy_coarse\", \"ddy_fine\", \"degrees\", \"determinant\", \"DeviceMemoryBarrier\", \"DeviceMemoryBarrierWithGroupSync\",\n\t\t\t\"distance\", \"dot\", \"dst\", \"errorf\", \"EvaluateAttributeAtCentroid\", \"EvaluateAttributeAtSample\", \"EvaluateAttributeSnapped\", \"exp\", \"exp2\",\n\t\t\t\"f16tof32\", \"f32tof16\", \"faceforward\", \"firstbithigh\", \"firstbitlow\", \"floor\", \"fma\", \"fmod\", \"frac\", \"frexp\", \"fwidth\", \"GetRenderTargetSampleCount\",\n\t\t\t\"GetRenderTargetSamplePosition\", \"GroupMemoryBarrier\", \"GroupMemoryBarrierWithGroupSync\", \"InterlockedAdd\", \"InterlockedAnd\", \"InterlockedCompareExchange\",\n\t\t\t\"InterlockedCompareStore\", \"InterlockedExchange\", \"InterlockedMax\", \"InterlockedMin\", \"InterlockedOr\", \"InterlockedXor\", \"isfinite\", \"isinf\", \"isnan\",\n\t\t\t\"ldexp\", \"length\", \"lerp\", \"lit\", \"log\", \"log10\", \"log2\", \"mad\", \"max\", \"min\", \"modf\", \"msad4\", \"mul\", \"noise\", \"normalize\", \"pow\", \"printf\",\n\t\t\t\"Process2DQuadTessFactorsAvg\", \"Process2DQuadTessFactorsMax\", \"Process2DQuadTessFactorsMin\", \"ProcessIsolineTessFactors\", \"ProcessQuadTessFactorsAvg\",\n\t\t\t\"ProcessQuadTessFactorsMax\", \"ProcessQuadTessFactorsMin\", \"ProcessTriTessFactorsAvg\", \"ProcessTriTessFactorsMax\", \"ProcessTriTessFactorsMin\",\n\t\t\t\"radians\", \"rcp\", \"reflect\", \"refract\", \"reversebits\", \"round\", \"rsqrt\", \"saturate\", \"sign\", \"sin\", \"sincos\", \"sinh\", \"smoothstep\", \"sqrt\", \"step\",\n\t\t\t\"tan\", \"tanh\", \"tex1D\", \"tex1D\", \"tex1Dbias\", \"tex1Dgrad\", \"tex1Dlod\", \"tex1Dproj\", \"tex2D\", \"tex2D\", \"tex2Dbias\", \"tex2Dgrad\", \"tex2Dlod\", \"tex2Dproj\",\n\t\t\t\"tex3D\", \"tex3D\", \"tex3Dbias\", \"tex3Dgrad\", \"tex3Dlod\", \"tex3Dproj\", \"texCUBE\", \"texCUBE\", \"texCUBEbias\", \"texCUBEgrad\", \"texCUBElod\", \"texCUBEproj\", \"transpose\", \"trunc\"\n\t\t};\n\t\tfor (auto& k : identifiers)\n\t\t{\n\t\t\tIdentifier id;\n\t\t\tid.mDeclaration = \"Built-in function\";\n\t\t\tlangDef.mIdentifiers.insert(std::make_pair(std::string(k), id));\n\t\t}\n\n\t\tlangDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>(\"[ \\\\t]*#[ \\\\t]*[a-zA-Z_]+\", PaletteIndex::Preprocessor));\n\t\tlangDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>(\"L?\\\\\\\"(\\\\\\\\.|[^\\\\\\\"])*\\\\\\\"\", PaletteIndex::String));\n\t\tlangDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>(\"\\\\'\\\\\\\\?[^\\\\']\\\\'\", PaletteIndex::CharLiteral));\n\t\tlangDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>(\"[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][+-]?[0-9]+)?[fF]?\", PaletteIndex::Number));\n\t\tlangDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>(\"[+-]?[0-9]+[Uu]?[lL]?[lL]?\", PaletteIndex::Number));\n\t\tlangDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>(\"0[0-7]+[Uu]?[lL]?[lL]?\", PaletteIndex::Number));\n\t\tlangDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>(\"0[xX][0-9a-fA-F]+[uU]?[lL]?[lL]?\", PaletteIndex::Number));\n\t\tlangDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>(\"[a-zA-Z_][a-zA-Z0-9_]*\", PaletteIndex::Identifier));\n\t\tlangDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>(\"[\\\\[\\\\]\\\\{\\\\}\\\\!\\\\%\\\\^\\\\&\\\\*\\\\(\\\\)\\\\-\\\\+\\\\=\\\\~\\\\|\\\\<\\\\>\\\\?\\\\/\\\\;\\\\,\\\\.]\", PaletteIndex::Punctuation));\n\n\t\tlangDef.mCommentStart = \"/*\";\n\t\tlangDef.mCommentEnd = \"*/\";\n\t\tlangDef.mSingleLineComment = \"//\";\n\n\t\tlangDef.mCaseSensitive = true;\n\t\tlangDef.mAutoIndentation = true;\n\n\t\tlangDef.mName = \"HLSL\";\n\n\t\tinited = true;\n\t}\n\treturn langDef;\n}\n\nconst TextEditor::LanguageDefinition& TextEditor::LanguageDefinition::GLSL()\n{\n\tstatic bool inited = false;\n\tstatic LanguageDefinition langDef;\n\tif (!inited)\n\t{\n\t\tstatic const char* const keywords[] = {\n\t\t\t\"auto\", \"break\", \"case\", \"char\", \"const\", \"continue\", \"default\", \"do\", \"double\", \"else\", \"enum\", \"extern\", \"float\", \"for\", \"goto\", \"if\", \"inline\", \"int\", \"long\", \"register\", \"restrict\", \"return\", \"short\",\n\t\t\t\"signed\", \"sizeof\", \"static\", \"struct\", \"switch\", \"typedef\", \"union\", \"unsigned\", \"void\", \"volatile\", \"while\", \"_Alignas\", \"_Alignof\", \"_Atomic\", \"_Bool\", \"_Complex\", \"_Generic\", \"_Imaginary\",\n\t\t\t\"_Noreturn\", \"_Static_assert\", \"_Thread_local\"\n\t\t};\n\t\tfor (auto& k : keywords)\n\t\t\tlangDef.mKeywords.insert(k);\n\n\t\tstatic const char* const identifiers[] = {\n\t\t\t\"abort\", \"abs\", \"acos\", \"asin\", \"atan\", \"atexit\", \"atof\", \"atoi\", \"atol\", \"ceil\", \"clock\", \"cosh\", \"ctime\", \"div\", \"exit\", \"fabs\", \"floor\", \"fmod\", \"getchar\", \"getenv\", \"isalnum\", \"isalpha\", \"isdigit\", \"isgraph\",\n\t\t\t\"ispunct\", \"isspace\", \"isupper\", \"kbhit\", \"log10\", \"log2\", \"log\", \"memcmp\", \"modf\", \"pow\", \"putchar\", \"putenv\", \"puts\", \"rand\", \"remove\", \"rename\", \"sinh\", \"sqrt\", \"srand\", \"strcat\", \"strcmp\", \"strerror\", \"time\", \"tolower\", \"toupper\"\n\t\t};\n\t\tfor (auto& k : identifiers)\n\t\t{\n\t\t\tIdentifier id;\n\t\t\tid.mDeclaration = \"Built-in function\";\n\t\t\tlangDef.mIdentifiers.insert(std::make_pair(std::string(k), id));\n\t\t}\n\n\t\tlangDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>(\"[ \\\\t]*#[ \\\\t]*[a-zA-Z_]+\", PaletteIndex::Preprocessor));\n\t\tlangDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>(\"L?\\\\\\\"(\\\\\\\\.|[^\\\\\\\"])*\\\\\\\"\", PaletteIndex::String));\n\t\tlangDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>(\"\\\\'\\\\\\\\?[^\\\\']\\\\'\", PaletteIndex::CharLiteral));\n\t\tlangDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>(\"[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][+-]?[0-9]+)?[fF]?\", PaletteIndex::Number));\n\t\tlangDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>(\"[+-]?[0-9]+[Uu]?[lL]?[lL]?\", PaletteIndex::Number));\n\t\tlangDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>(\"0[0-7]+[Uu]?[lL]?[lL]?\", PaletteIndex::Number));\n\t\tlangDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>(\"0[xX][0-9a-fA-F]+[uU]?[lL]?[lL]?\", PaletteIndex::Number));\n\t\tlangDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>(\"[a-zA-Z_][a-zA-Z0-9_]*\", PaletteIndex::Identifier));\n\t\tlangDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>(\"[\\\\[\\\\]\\\\{\\\\}\\\\!\\\\%\\\\^\\\\&\\\\*\\\\(\\\\)\\\\-\\\\+\\\\=\\\\~\\\\|\\\\<\\\\>\\\\?\\\\/\\\\;\\\\,\\\\.]\", PaletteIndex::Punctuation));\n\n\t\tlangDef.mCommentStart = \"/*\";\n\t\tlangDef.mCommentEnd = \"*/\";\n\t\tlangDef.mSingleLineComment = \"//\";\n\n\t\tlangDef.mCaseSensitive = true;\n\t\tlangDef.mAutoIndentation = true;\n\n\t\tlangDef.mName = \"GLSL\";\n\n\t\tinited = true;\n\t}\n\treturn langDef;\n}\n\nconst TextEditor::LanguageDefinition& TextEditor::LanguageDefinition::C()\n{\n\tstatic bool inited = false;\n\tstatic LanguageDefinition langDef;\n\tif (!inited)\n\t{\n\t\tstatic const char* const keywords[] = {\n\t\t\t\"auto\", \"break\", \"case\", \"char\", \"const\", \"continue\", \"default\", \"do\", \"double\", \"else\", \"enum\", \"extern\", \"float\", \"for\", \"goto\", \"if\", \"inline\", \"int\", \"long\", \"register\", \"restrict\", \"return\", \"short\",\n\t\t\t\"signed\", \"sizeof\", \"static\", \"struct\", \"switch\", \"typedef\", \"union\", \"unsigned\", \"void\", \"volatile\", \"while\", \"_Alignas\", \"_Alignof\", \"_Atomic\", \"_Bool\", \"_Complex\", \"_Generic\", \"_Imaginary\",\n\t\t\t\"_Noreturn\", \"_Static_assert\", \"_Thread_local\"\n\t\t};\n\t\tfor (auto& k : keywords)\n\t\t\tlangDef.mKeywords.insert(k);\n\n\t\tstatic const char* const identifiers[] = {\n\t\t\t\"abort\", \"abs\", \"acos\", \"asin\", \"atan\", \"atexit\", \"atof\", \"atoi\", \"atol\", \"ceil\", \"clock\", \"cosh\", \"ctime\", \"div\", \"exit\", \"fabs\", \"floor\", \"fmod\", \"getchar\", \"getenv\", \"isalnum\", \"isalpha\", \"isdigit\", \"isgraph\",\n\t\t\t\"ispunct\", \"isspace\", \"isupper\", \"kbhit\", \"log10\", \"log2\", \"log\", \"memcmp\", \"modf\", \"pow\", \"putchar\", \"putenv\", \"puts\", \"rand\", \"remove\", \"rename\", \"sinh\", \"sqrt\", \"srand\", \"strcat\", \"strcmp\", \"strerror\", \"time\", \"tolower\", \"toupper\"\n\t\t};\n\t\tfor (auto& k : identifiers)\n\t\t{\n\t\t\tIdentifier id;\n\t\t\tid.mDeclaration = \"Built-in function\";\n\t\t\tlangDef.mIdentifiers.insert(std::make_pair(std::string(k), id));\n\t\t}\n\n\t\tlangDef.mTokenize = [](const char * in_begin, const char * in_end, const char *& out_begin, const char *& out_end, PaletteIndex & paletteIndex) -> bool\n\t\t{\n\t\t\tpaletteIndex = PaletteIndex::Max;\n\n\t\t\twhile (in_begin < in_end && isascii(*in_begin) && isblank(*in_begin))\n\t\t\t\tin_begin++;\n\n\t\t\tif (in_begin == in_end)\n\t\t\t{\n\t\t\t\tout_begin = in_end;\n\t\t\t\tout_end = in_end;\n\t\t\t\tpaletteIndex = PaletteIndex::Default;\n\t\t\t}\n\t\t\telse if (TokenizeCStyleString(in_begin, in_end, out_begin, out_end))\n\t\t\t\tpaletteIndex = PaletteIndex::String;\n\t\t\telse if (TokenizeCStyleCharacterLiteral(in_begin, in_end, out_begin, out_end))\n\t\t\t\tpaletteIndex = PaletteIndex::CharLiteral;\n\t\t\telse if (TokenizeCStyleIdentifier(in_begin, in_end, out_begin, out_end))\n\t\t\t\tpaletteIndex = PaletteIndex::Identifier;\n\t\t\telse if (TokenizeCStyleNumber(in_begin, in_end, out_begin, out_end))\n\t\t\t\tpaletteIndex = PaletteIndex::Number;\n\t\t\telse if (TokenizeCStylePunctuation(in_begin, in_end, out_begin, out_end))\n\t\t\t\tpaletteIndex = PaletteIndex::Punctuation;\n\n\t\t\treturn paletteIndex != PaletteIndex::Max;\n\t\t};\n\n\t\tlangDef.mCommentStart = \"/*\";\n\t\tlangDef.mCommentEnd = \"*/\";\n\t\tlangDef.mSingleLineComment = \"//\";\n\n\t\tlangDef.mCaseSensitive = true;\n\t\tlangDef.mAutoIndentation = true;\n\n\t\tlangDef.mName = \"C\";\n\n\t\tinited = true;\n\t}\n\treturn langDef;\n}\n\nconst TextEditor::LanguageDefinition& TextEditor::LanguageDefinition::SQL()\n{\n\tstatic bool inited = false;\n\tstatic LanguageDefinition langDef;\n\tif (!inited)\n\t{\n\t\tstatic const char* const keywords[] = {\n\t\t\t\"ADD\", \"EXCEPT\", \"PERCENT\", \"ALL\", \"EXEC\", \"PLAN\", \"ALTER\", \"EXECUTE\", \"PRECISION\", \"AND\", \"EXISTS\", \"PRIMARY\", \"ANY\", \"EXIT\", \"PRINT\", \"AS\", \"FETCH\", \"PROC\", \"ASC\", \"FILE\", \"PROCEDURE\",\n\t\t\t\"AUTHORIZATION\", \"FILLFACTOR\", \"PUBLIC\", \"BACKUP\", \"FOR\", \"RAISERROR\", \"BEGIN\", \"FOREIGN\", \"READ\", \"BETWEEN\", \"FREETEXT\", \"READTEXT\", \"BREAK\", \"FREETEXTTABLE\", \"RECONFIGURE\",\n\t\t\t\"BROWSE\", \"FROM\", \"REFERENCES\", \"BULK\", \"FULL\", \"REPLICATION\", \"BY\", \"FUNCTION\", \"RESTORE\", \"CASCADE\", \"GOTO\", \"RESTRICT\", \"CASE\", \"GRANT\", \"RETURN\", \"CHECK\", \"GROUP\", \"REVOKE\",\n\t\t\t\"CHECKPOINT\", \"HAVING\", \"RIGHT\", \"CLOSE\", \"HOLDLOCK\", \"ROLLBACK\", \"CLUSTERED\", \"IDENTITY\", \"ROWCOUNT\", \"COALESCE\", \"IDENTITY_INSERT\", \"ROWGUIDCOL\", \"COLLATE\", \"IDENTITYCOL\", \"RULE\",\n\t\t\t\"COLUMN\", \"IF\", \"SAVE\", \"COMMIT\", \"IN\", \"SCHEMA\", \"COMPUTE\", \"INDEX\", \"SELECT\", \"CONSTRAINT\", \"INNER\", \"SESSION_USER\", \"CONTAINS\", \"INSERT\", \"SET\", \"CONTAINSTABLE\", \"INTERSECT\", \"SETUSER\",\n\t\t\t\"CONTINUE\", \"INTO\", \"SHUTDOWN\", \"CONVERT\", \"IS\", \"SOME\", \"CREATE\", \"JOIN\", \"STATISTICS\", \"CROSS\", \"KEY\", \"SYSTEM_USER\", \"CURRENT\", \"KILL\", \"TABLE\", \"CURRENT_DATE\", \"LEFT\", \"TEXTSIZE\",\n\t\t\t\"CURRENT_TIME\", \"LIKE\", \"THEN\", \"CURRENT_TIMESTAMP\", \"LINENO\", \"TO\", \"CURRENT_USER\", \"LOAD\", \"TOP\", \"CURSOR\", \"NATIONAL\", \"TRAN\", \"DATABASE\", \"NOCHECK\", \"TRANSACTION\",\n\t\t\t\"DBCC\", \"NONCLUSTERED\", \"TRIGGER\", \"DEALLOCATE\", \"NOT\", \"TRUNCATE\", \"DECLARE\", \"NULL\", \"TSEQUAL\", \"DEFAULT\", \"NULLIF\", \"UNION\", \"DELETE\", \"OF\", \"UNIQUE\", \"DENY\", \"OFF\", \"UPDATE\",\n\t\t\t\"DESC\", \"OFFSETS\", \"UPDATETEXT\", \"DISK\", \"ON\", \"USE\", \"DISTINCT\", \"OPEN\", \"USER\", \"DISTRIBUTED\", \"OPENDATASOURCE\", \"VALUES\", \"DOUBLE\", \"OPENQUERY\", \"VARYING\",\"DROP\", \"OPENROWSET\", \"VIEW\",\n\t\t\t\"DUMMY\", \"OPENXML\", \"WAITFOR\", \"DUMP\", \"OPTION\", \"WHEN\", \"ELSE\", \"OR\", \"WHERE\", \"END\", \"ORDER\", \"WHILE\", \"ERRLVL\", \"OUTER\", \"WITH\", \"ESCAPE\", \"OVER\", \"WRITETEXT\"\n\t\t};\n\n\t\tfor (auto& k : keywords)\n\t\t\tlangDef.mKeywords.insert(k);\n\n\t\tstatic const char* const identifiers[] = {\n\t\t\t\"ABS\",  \"ACOS\",  \"ADD_MONTHS\",  \"ASCII\",  \"ASCIISTR\",  \"ASIN\",  \"ATAN\",  \"ATAN2\",  \"AVG\",  \"BFILENAME\",  \"BIN_TO_NUM\",  \"BITAND\",  \"CARDINALITY\",  \"CASE\",  \"CAST\",  \"CEIL\",\n\t\t\t\"CHARTOROWID\",  \"CHR\",  \"COALESCE\",  \"COMPOSE\",  \"CONCAT\",  \"CONVERT\",  \"CORR\",  \"COS\",  \"COSH\",  \"COUNT\",  \"COVAR_POP\",  \"COVAR_SAMP\",  \"CUME_DIST\",  \"CURRENT_DATE\",\n\t\t\t\"CURRENT_TIMESTAMP\",  \"DBTIMEZONE\",  \"DECODE\",  \"DECOMPOSE\",  \"DENSE_RANK\",  \"DUMP\",  \"EMPTY_BLOB\",  \"EMPTY_CLOB\",  \"EXP\",  \"EXTRACT\",  \"FIRST_VALUE\",  \"FLOOR\",  \"FROM_TZ\",  \"GREATEST\",\n\t\t\t\"GROUP_ID\",  \"HEXTORAW\",  \"INITCAP\",  \"INSTR\",  \"INSTR2\",  \"INSTR4\",  \"INSTRB\",  \"INSTRC\",  \"LAG\",  \"LAST_DAY\",  \"LAST_VALUE\",  \"LEAD\",  \"LEAST\",  \"LENGTH\",  \"LENGTH2\",  \"LENGTH4\",\n\t\t\t\"LENGTHB\",  \"LENGTHC\",  \"LISTAGG\",  \"LN\",  \"LNNVL\",  \"LOCALTIMESTAMP\",  \"LOG\",  \"LOWER\",  \"LPAD\",  \"LTRIM\",  \"MAX\",  \"MEDIAN\",  \"MIN\",  \"MOD\",  \"MONTHS_BETWEEN\",  \"NANVL\",  \"NCHR\",\n\t\t\t\"NEW_TIME\",  \"NEXT_DAY\",  \"NTH_VALUE\",  \"NULLIF\",  \"NUMTODSINTERVAL\",  \"NUMTOYMINTERVAL\",  \"NVL\",  \"NVL2\",  \"POWER\",  \"RANK\",  \"RAWTOHEX\",  \"REGEXP_COUNT\",  \"REGEXP_INSTR\",\n\t\t\t\"REGEXP_REPLACE\",  \"REGEXP_SUBSTR\",  \"REMAINDER\",  \"REPLACE\",  \"ROUND\",  \"ROWNUM\",  \"RPAD\",  \"RTRIM\",  \"SESSIONTIMEZONE\",  \"SIGN\",  \"SIN\",  \"SINH\",\n\t\t\t\"SOUNDEX\",  \"SQRT\",  \"STDDEV\",  \"SUBSTR\",  \"SUM\",  \"SYS_CONTEXT\",  \"SYSDATE\",  \"SYSTIMESTAMP\",  \"TAN\",  \"TANH\",  \"TO_CHAR\",  \"TO_CLOB\",  \"TO_DATE\",  \"TO_DSINTERVAL\",  \"TO_LOB\",\n\t\t\t\"TO_MULTI_BYTE\",  \"TO_NCLOB\",  \"TO_NUMBER\",  \"TO_SINGLE_BYTE\",  \"TO_TIMESTAMP\",  \"TO_TIMESTAMP_TZ\",  \"TO_YMINTERVAL\",  \"TRANSLATE\",  \"TRIM\",  \"TRUNC\", \"TZ_OFFSET\",  \"UID\",  \"UPPER\",\n\t\t\t\"USER\",  \"USERENV\",  \"VAR_POP\",  \"VAR_SAMP\",  \"VARIANCE\",  \"VSIZE \"\n\t\t};\n\t\tfor (auto& k : identifiers)\n\t\t{\n\t\t\tIdentifier id;\n\t\t\tid.mDeclaration = \"Built-in function\";\n\t\t\tlangDef.mIdentifiers.insert(std::make_pair(std::string(k), id));\n\t\t}\n\n\t\tlangDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>(\"L?\\\\\\\"(\\\\\\\\.|[^\\\\\\\"])*\\\\\\\"\", PaletteIndex::String));\n\t\tlangDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>(\"\\\\\\'[^\\\\\\']*\\\\\\'\", PaletteIndex::String));\n\t\tlangDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>(\"[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][+-]?[0-9]+)?[fF]?\", PaletteIndex::Number));\n\t\tlangDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>(\"[+-]?[0-9]+[Uu]?[lL]?[lL]?\", PaletteIndex::Number));\n\t\tlangDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>(\"0[0-7]+[Uu]?[lL]?[lL]?\", PaletteIndex::Number));\n\t\tlangDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>(\"0[xX][0-9a-fA-F]+[uU]?[lL]?[lL]?\", PaletteIndex::Number));\n\t\tlangDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>(\"[a-zA-Z_][a-zA-Z0-9_]*\", PaletteIndex::Identifier));\n\t\tlangDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>(\"[\\\\[\\\\]\\\\{\\\\}\\\\!\\\\%\\\\^\\\\&\\\\*\\\\(\\\\)\\\\-\\\\+\\\\=\\\\~\\\\|\\\\<\\\\>\\\\?\\\\/\\\\;\\\\,\\\\.]\", PaletteIndex::Punctuation));\n\n\t\tlangDef.mCommentStart = \"/*\";\n\t\tlangDef.mCommentEnd = \"*/\";\n\t\tlangDef.mSingleLineComment = \"//\";\n\n\t\tlangDef.mCaseSensitive = false;\n\t\tlangDef.mAutoIndentation = false;\n\n\t\tlangDef.mName = \"SQL\";\n\n\t\tinited = true;\n\t}\n\treturn langDef;\n}\n\nconst TextEditor::LanguageDefinition& TextEditor::LanguageDefinition::AngelScript()\n{\n\tstatic bool inited = false;\n\tstatic LanguageDefinition langDef;\n\tif (!inited)\n\t{\n\t\tstatic const char* const keywords[] = {\n\t\t\t\"and\", \"abstract\", \"auto\", \"bool\", \"break\", \"case\", \"cast\", \"class\", \"const\", \"continue\", \"default\", \"do\", \"double\", \"else\", \"enum\", \"false\", \"final\", \"float\", \"for\",\n\t\t\t\"from\", \"funcdef\", \"function\", \"get\", \"if\", \"import\", \"in\", \"inout\", \"int\", \"interface\", \"int8\", \"int16\", \"int32\", \"int64\", \"is\", \"mixin\", \"namespace\", \"not\",\n\t\t\t\"null\", \"or\", \"out\", \"override\", \"private\", \"protected\", \"return\", \"set\", \"shared\", \"super\", \"switch\", \"this \", \"true\", \"typedef\", \"uint\", \"uint8\", \"uint16\", \"uint32\",\n\t\t\t\"uint64\", \"void\", \"while\", \"xor\"\n\t\t};\n\n\t\tfor (auto& k : keywords)\n\t\t\tlangDef.mKeywords.insert(k);\n\n\t\tstatic const char* const identifiers[] = {\n\t\t\t\"cos\", \"sin\", \"tab\", \"acos\", \"asin\", \"atan\", \"atan2\", \"cosh\", \"sinh\", \"tanh\", \"log\", \"log10\", \"pow\", \"sqrt\", \"abs\", \"ceil\", \"floor\", \"fraction\", \"closeTo\", \"fpFromIEEE\", \"fpToIEEE\",\n\t\t\t\"complex\", \"opEquals\", \"opAddAssign\", \"opSubAssign\", \"opMulAssign\", \"opDivAssign\", \"opAdd\", \"opSub\", \"opMul\", \"opDiv\"\n\t\t};\n\t\tfor (auto& k : identifiers)\n\t\t{\n\t\t\tIdentifier id;\n\t\t\tid.mDeclaration = \"Built-in function\";\n\t\t\tlangDef.mIdentifiers.insert(std::make_pair(std::string(k), id));\n\t\t}\n\n\t\tlangDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>(\"L?\\\\\\\"(\\\\\\\\.|[^\\\\\\\"])*\\\\\\\"\", PaletteIndex::String));\n\t\tlangDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>(\"\\\\'\\\\\\\\?[^\\\\']\\\\'\", PaletteIndex::String));\n\t\tlangDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>(\"[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][+-]?[0-9]+)?[fF]?\", PaletteIndex::Number));\n\t\tlangDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>(\"[+-]?[0-9]+[Uu]?[lL]?[lL]?\", PaletteIndex::Number));\n\t\tlangDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>(\"0[0-7]+[Uu]?[lL]?[lL]?\", PaletteIndex::Number));\n\t\tlangDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>(\"0[xX][0-9a-fA-F]+[uU]?[lL]?[lL]?\", PaletteIndex::Number));\n\t\tlangDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>(\"[a-zA-Z_][a-zA-Z0-9_]*\", PaletteIndex::Identifier));\n\t\tlangDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>(\"[\\\\[\\\\]\\\\{\\\\}\\\\!\\\\%\\\\^\\\\&\\\\*\\\\(\\\\)\\\\-\\\\+\\\\=\\\\~\\\\|\\\\<\\\\>\\\\?\\\\/\\\\;\\\\,\\\\.]\", PaletteIndex::Punctuation));\n\n\t\tlangDef.mCommentStart = \"/*\";\n\t\tlangDef.mCommentEnd = \"*/\";\n\t\tlangDef.mSingleLineComment = \"//\";\n\n\t\tlangDef.mCaseSensitive = true;\n\t\tlangDef.mAutoIndentation = true;\n\n\t\tlangDef.mName = \"AngelScript\";\n\n\t\tinited = true;\n\t}\n\treturn langDef;\n}\n\nconst TextEditor::LanguageDefinition& TextEditor::LanguageDefinition::Lua()\n{\n\tstatic bool inited = false;\n\tstatic LanguageDefinition langDef;\n\tif (!inited)\n\t{\n\t\tstatic const char* const keywords[] = {\n\t\t\t\"and\", \"break\", \"do\", \"\", \"else\", \"elseif\", \"end\", \"false\", \"for\", \"function\", \"if\", \"in\", \"\", \"local\", \"nil\", \"not\", \"or\", \"repeat\", \"return\", \"then\", \"true\", \"until\", \"while\"\n\t\t};\n\n\t\tfor (auto& k : keywords)\n\t\t\tlangDef.mKeywords.insert(k);\n\n\t\tstatic const char* const identifiers[] = {\n\t\t\t\"assert\", \"collectgarbage\", \"dofile\", \"error\", \"getmetatable\", \"ipairs\", \"loadfile\", \"load\", \"loadstring\",  \"next\",  \"pairs\",  \"pcall\",  \"print\",  \"rawequal\",  \"rawlen\",  \"rawget\",  \"rawset\",\n\t\t\t\"select\",  \"setmetatable\",  \"tonumber\",  \"tostring\",  \"type\",  \"xpcall\",  \"_G\",  \"_VERSION\",\"arshift\", \"band\", \"bnot\", \"bor\", \"bxor\", \"btest\", \"extract\", \"lrotate\", \"lshift\", \"replace\",\n\t\t\t\"rrotate\", \"rshift\", \"create\", \"resume\", \"running\", \"status\", \"wrap\", \"yield\", \"isyieldable\", \"debug\",\"getuservalue\", \"gethook\", \"getinfo\", \"getlocal\", \"getregistry\", \"getmetatable\",\n\t\t\t\"getupvalue\", \"upvaluejoin\", \"upvalueid\", \"setuservalue\", \"sethook\", \"setlocal\", \"setmetatable\", \"setupvalue\", \"traceback\", \"close\", \"flush\", \"input\", \"lines\", \"open\", \"output\", \"popen\",\n\t\t\t\"read\", \"tmpfile\", \"type\", \"write\", \"close\", \"flush\", \"lines\", \"read\", \"seek\", \"setvbuf\", \"write\", \"__gc\", \"__tostring\", \"abs\", \"acos\", \"asin\", \"atan\", \"ceil\", \"cos\", \"deg\", \"exp\", \"tointeger\",\n\t\t\t\"floor\", \"fmod\", \"ult\", \"log\", \"max\", \"min\", \"modf\", \"rad\", \"random\", \"randomseed\", \"sin\", \"sqrt\", \"string\", \"tan\", \"type\", \"atan2\", \"cosh\", \"sinh\", \"tanh\",\n\t\t\t\"pow\", \"frexp\", \"ldexp\", \"log10\", \"pi\", \"huge\", \"maxinteger\", \"mininteger\", \"loadlib\", \"searchpath\", \"seeall\", \"preload\", \"cpath\", \"path\", \"searchers\", \"loaded\", \"module\", \"require\", \"clock\",\n\t\t\t\"date\", \"difftime\", \"execute\", \"exit\", \"getenv\", \"remove\", \"rename\", \"setlocale\", \"time\", \"tmpname\", \"byte\", \"char\", \"dump\", \"find\", \"format\", \"gmatch\", \"gsub\", \"len\", \"lower\", \"match\", \"rep\",\n\t\t\t\"reverse\", \"sub\", \"upper\", \"pack\", \"packsize\", \"unpack\", \"concat\", \"maxn\", \"insert\", \"pack\", \"unpack\", \"remove\", \"move\", \"sort\", \"offset\", \"codepoint\", \"char\", \"len\", \"codes\", \"charpattern\",\n\t\t\t\"coroutine\", \"table\", \"io\", \"os\", \"string\", \"utf8\", \"bit32\", \"math\", \"debug\", \"package\"\n\t\t};\n\t\tfor (auto& k : identifiers)\n\t\t{\n\t\t\tIdentifier id;\n\t\t\tid.mDeclaration = \"Built-in function\";\n\t\t\tlangDef.mIdentifiers.insert(std::make_pair(std::string(k), id));\n\t\t}\n\n\t\tlangDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>(\"L?\\\\\\\"(\\\\\\\\.|[^\\\\\\\"])*\\\\\\\"\", PaletteIndex::String));\n\t\tlangDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>(\"\\\\\\'[^\\\\\\']*\\\\\\'\", PaletteIndex::String));\n\t\tlangDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>(\"0[xX][0-9a-fA-F]+[uU]?[lL]?[lL]?\", PaletteIndex::Number));\n\t\tlangDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>(\"[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)([eE][+-]?[0-9]+)?[fF]?\", PaletteIndex::Number));\n\t\tlangDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>(\"[+-]?[0-9]+[Uu]?[lL]?[lL]?\", PaletteIndex::Number));\n\t\tlangDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>(\"[a-zA-Z_][a-zA-Z0-9_]*\", PaletteIndex::Identifier));\n\t\tlangDef.mTokenRegexStrings.push_back(std::make_pair<std::string, PaletteIndex>(\"[\\\\[\\\\]\\\\{\\\\}\\\\!\\\\%\\\\^\\\\&\\\\*\\\\(\\\\)\\\\-\\\\+\\\\=\\\\~\\\\|\\\\<\\\\>\\\\?\\\\/\\\\;\\\\,\\\\.]\", PaletteIndex::Punctuation));\n\n\t\tlangDef.mCommentStart = \"--[[\";\n\t\tlangDef.mCommentEnd = \"]]\";\n\t\tlangDef.mSingleLineComment = \"--\";\n\n\t\tlangDef.mCaseSensitive = true;\n\t\tlangDef.mAutoIndentation = false;\n\n\t\tlangDef.mName = \"Lua\";\n\n\t\tinited = true;\n\t}\n\treturn langDef;\n}\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/ImGuiColorTextEdit/TextEditor.h",
    "content": "#pragma once\r\n\r\n#include <string>\r\n#include <vector>\r\n#include <array>\r\n#include <memory>\r\n#include <unordered_set>\r\n#include <unordered_map>\r\n#include <map>\r\n#include <regex>\r\n#include \"imgui/imgui.h\"\r\n\r\nclass TextEditor\r\n{\r\npublic:\r\n\tenum class PaletteIndex\r\n\t{\r\n\t\tDefault,\r\n\t\tKeyword,\r\n\t\tNumber,\r\n\t\tString,\r\n\t\tCharLiteral,\r\n\t\tPunctuation,\r\n\t\tPreprocessor,\r\n\t\tIdentifier,\r\n\t\tKnownIdentifier,\r\n\t\tPreprocIdentifier,\r\n\t\tComment,\r\n\t\tMultiLineComment,\r\n\t\tBackground,\r\n\t\tCursor,\r\n\t\tSelection,\r\n\t\tErrorMarker,\r\n\t\tBreakpoint,\r\n\t\tLineNumber,\r\n\t\tCurrentLineFill,\r\n\t\tCurrentLineFillInactive,\r\n\t\tCurrentLineEdge,\r\n\t\tMax\r\n\t};\r\n\r\n\tenum class SelectionMode\r\n\t{\r\n\t\tNormal,\r\n\t\tWord,\r\n\t\tLine\r\n\t};\r\n\r\n\tstruct Breakpoint\r\n\t{\r\n\t\tint mLine;\r\n\t\tbool mEnabled;\r\n\t\tstd::string mCondition;\r\n\r\n\t\tBreakpoint()\r\n\t\t\t: mLine(-1)\r\n\t\t\t, mEnabled(false)\r\n\t\t{}\r\n\t};\r\n\r\n\t// Represents a character coordinate from the user's point of view,\r\n\t// i. e. consider an uniform grid (assuming fixed-width font) on the\r\n\t// screen as it is rendered, and each cell has its own coordinate, starting from 0.\r\n\t// Tabs are counted as [1..mTabSize] count empty spaces, depending on\r\n\t// how many space is necessary to reach the next tab stop.\r\n\t// For example, coordinate (1, 5) represents the character 'B' in a line \"\\tABC\", when mTabSize = 4,\r\n\t// because it is rendered as \"    ABC\" on the screen.\r\n\tstruct Coordinates\r\n\t{\r\n\t\tint mLine, mColumn;\r\n\t\tCoordinates() : mLine(0), mColumn(0) {}\r\n\t\tCoordinates(int aLine, int aColumn) : mLine(aLine), mColumn(aColumn)\r\n\t\t{\r\n\t\t\tassert(aLine >= 0);\r\n\t\t\tassert(aColumn >= 0);\r\n\t\t}\r\n\t\tstatic Coordinates Invalid() { static Coordinates invalid(-1, -1); return invalid; }\r\n\r\n\t\tbool operator ==(const Coordinates& o) const\r\n\t\t{\r\n\t\t\treturn\r\n\t\t\t\tmLine == o.mLine &&\r\n\t\t\t\tmColumn == o.mColumn;\r\n\t\t}\r\n\r\n\t\tbool operator !=(const Coordinates& o) const\r\n\t\t{\r\n\t\t\treturn\r\n\t\t\t\tmLine != o.mLine ||\r\n\t\t\t\tmColumn != o.mColumn;\r\n\t\t}\r\n\r\n\t\tbool operator <(const Coordinates& o) const\r\n\t\t{\r\n\t\t\tif (mLine != o.mLine)\r\n\t\t\t\treturn mLine < o.mLine;\r\n\t\t\treturn mColumn < o.mColumn;\r\n\t\t}\r\n\r\n\t\tbool operator >(const Coordinates& o) const\r\n\t\t{\r\n\t\t\tif (mLine != o.mLine)\r\n\t\t\t\treturn mLine > o.mLine;\r\n\t\t\treturn mColumn > o.mColumn;\r\n\t\t}\r\n\r\n\t\tbool operator <=(const Coordinates& o) const\r\n\t\t{\r\n\t\t\tif (mLine != o.mLine)\r\n\t\t\t\treturn mLine < o.mLine;\r\n\t\t\treturn mColumn <= o.mColumn;\r\n\t\t}\r\n\r\n\t\tbool operator >=(const Coordinates& o) const\r\n\t\t{\r\n\t\t\tif (mLine != o.mLine)\r\n\t\t\t\treturn mLine > o.mLine;\r\n\t\t\treturn mColumn >= o.mColumn;\r\n\t\t}\r\n\t};\r\n\r\n\tstruct Identifier\r\n\t{\r\n\t\tCoordinates mLocation;\r\n\t\tstd::string mDeclaration;\r\n\t};\r\n\r\n\ttypedef std::string String;\r\n\ttypedef std::unordered_map<std::string, Identifier> Identifiers;\r\n\ttypedef std::unordered_set<std::string> Keywords;\r\n\ttypedef std::map<int, std::string> ErrorMarkers;\r\n\ttypedef std::unordered_set<int> Breakpoints;\r\n\ttypedef std::array<ImU32, (unsigned)PaletteIndex::Max> Palette;\r\n\ttypedef uint8_t Char;\r\n\r\n\tstruct Glyph\r\n\t{\r\n\t\tChar mChar;\r\n\t\tPaletteIndex mColorIndex = PaletteIndex::Default;\r\n\t\tbool mComment : 1;\r\n\t\tbool mMultiLineComment : 1;\r\n\t\tbool mPreprocessor : 1;\r\n\r\n\t\tGlyph(Char aChar, PaletteIndex aColorIndex) : mChar(aChar), mColorIndex(aColorIndex),\r\n\t\t\tmComment(false), mMultiLineComment(false), mPreprocessor(false) {}\r\n\t};\r\n\r\n\ttypedef std::vector<Glyph> Line;\r\n\ttypedef std::vector<Line> Lines;\r\n\r\n\tstruct LanguageDefinition\r\n\t{\r\n\t\ttypedef std::pair<std::string, PaletteIndex> TokenRegexString;\r\n\t\ttypedef std::vector<TokenRegexString> TokenRegexStrings;\r\n\t\ttypedef bool(*TokenizeCallback)(const char * in_begin, const char * in_end, const char *& out_begin, const char *& out_end, PaletteIndex & paletteIndex);\r\n\r\n\t\tstd::string mName;\r\n\t\tKeywords mKeywords;\r\n\t\tIdentifiers mIdentifiers;\r\n\t\tIdentifiers mPreprocIdentifiers;\r\n\t\tstd::string mCommentStart, mCommentEnd, mSingleLineComment;\r\n\t\tchar mPreprocChar;\r\n\t\tbool mAutoIndentation;\r\n\r\n\t\tTokenizeCallback mTokenize;\r\n\r\n\t\tTokenRegexStrings mTokenRegexStrings;\r\n\r\n\t\tbool mCaseSensitive;\r\n\r\n\t\tLanguageDefinition()\r\n\t\t\t: mPreprocChar('#'), mAutoIndentation(true), mTokenize(nullptr), mCaseSensitive(true)\r\n\t\t{\r\n\t\t}\r\n\r\n\t\tstatic const LanguageDefinition& CPlusPlus();\r\n\t\tstatic const LanguageDefinition& HLSL();\r\n\t\tstatic const LanguageDefinition& GLSL();\r\n\t\tstatic const LanguageDefinition& C();\r\n\t\tstatic const LanguageDefinition& SQL();\r\n\t\tstatic const LanguageDefinition& AngelScript();\r\n\t\tstatic const LanguageDefinition& Lua();\r\n\t};\r\n\r\n\tTextEditor();\r\n\t~TextEditor();\r\n\r\n\tvoid SetLanguageDefinition(const LanguageDefinition& aLanguageDef);\r\n\tconst LanguageDefinition& GetLanguageDefinition() const { return mLanguageDefinition; }\r\n\r\n\tconst Palette& GetPalette() const { return mPaletteBase; }\r\n\tvoid SetPalette(const Palette& aValue);\r\n\r\n\tvoid SetErrorMarkers(const ErrorMarkers& aMarkers) { mErrorMarkers = aMarkers; }\r\n\tvoid SetBreakpoints(const Breakpoints& aMarkers) { mBreakpoints = aMarkers; }\r\n\r\n\tvoid Render(const char* aTitle, const ImVec2& aSize = ImVec2(), bool aBorder = false);\r\n\tvoid SetText(const std::string& aText);\r\n\tstd::string GetText() const;\r\n\r\n\tvoid SetTextLines(const std::vector<std::string>& aLines);\r\n\tstd::vector<std::string> GetTextLines() const;\r\n\r\n\tstd::string GetSelectedText() const;\r\n\tstd::string GetCurrentLineText()const;\r\n\r\n\tint GetTotalLines() const { return (int)mLines.size(); }\r\n\tbool IsOverwrite() const { return mOverwrite; }\r\n\r\n\tvoid SetReadOnly(bool aValue);\r\n\tbool IsReadOnly() const { return mReadOnly; }\r\n\tbool IsTextChanged() const { return mTextChanged; }\r\n\tbool IsCursorPositionChanged() const { return mCursorPositionChanged; }\r\n\r\n\tbool IsColorizerEnabled() const { return mColorizerEnabled; }\r\n\tvoid SetColorizerEnable(bool aValue);\r\n\r\n\tCoordinates GetCursorPosition() const { return GetActualCursorCoordinates(); }\r\n\tvoid SetCursorPosition(const Coordinates& aPosition);\r\n\r\n\tinline void SetHandleMouseInputs    (bool aValue){ mHandleMouseInputs    = aValue;}\r\n\tinline bool IsHandleMouseInputsEnabled() const { return mHandleKeyboardInputs; }\r\n\r\n\tinline void SetHandleKeyboardInputs (bool aValue){ mHandleKeyboardInputs = aValue;}\r\n\tinline bool IsHandleKeyboardInputsEnabled() const { return mHandleKeyboardInputs; }\r\n\r\n\tinline void SetImGuiChildIgnored    (bool aValue){ mIgnoreImGuiChild     = aValue;}\r\n\tinline bool IsImGuiChildIgnored() const { return mIgnoreImGuiChild; }\r\n\r\n\tinline void SetShowWhitespaces(bool aValue) { mShowWhitespaces = aValue; }\r\n\tinline bool IsShowingWhitespaces() const { return mShowWhitespaces; }\r\n\r\n\tvoid SetTabSize(int aValue);\r\n\tinline int GetTabSize() const { return mTabSize; }\r\n\r\n\tvoid InsertText(const std::string& aValue);\r\n\tvoid InsertText(const char* aValue);\r\n\r\n\tvoid MoveUp(int aAmount = 1, bool aSelect = false);\r\n\tvoid MoveDown(int aAmount = 1, bool aSelect = false);\r\n\tvoid MoveLeft(int aAmount = 1, bool aSelect = false, bool aWordMode = false);\r\n\tvoid MoveRight(int aAmount = 1, bool aSelect = false, bool aWordMode = false);\r\n\tvoid MoveTop(bool aSelect = false);\r\n\tvoid MoveBottom(bool aSelect = false);\r\n\tvoid MoveHome(bool aSelect = false);\r\n\tvoid MoveEnd(bool aSelect = false);\r\n\r\n\tvoid SetSelectionStart(const Coordinates& aPosition);\r\n\tvoid SetSelectionEnd(const Coordinates& aPosition);\r\n\tvoid SetSelection(const Coordinates& aStart, const Coordinates& aEnd, SelectionMode aMode = SelectionMode::Normal);\r\n\tvoid SelectWordUnderCursor();\r\n\tvoid SelectAll();\r\n\tbool HasSelection() const;\r\n\r\n\tvoid Copy();\r\n\tvoid Cut();\r\n\tvoid Paste();\r\n\tvoid Delete();\r\n\r\n\tbool CanUndo() const;\r\n\tbool CanRedo() const;\r\n\tvoid Undo(int aSteps = 1);\r\n\tvoid Redo(int aSteps = 1);\r\n\r\n\tstatic const Palette& GetDarkPalette();\r\n\tstatic const Palette& GetLightPalette();\r\n\tstatic const Palette& GetRetroBluePalette();\r\n\r\nprivate:\r\n\ttypedef std::vector<std::pair<std::regex, PaletteIndex>> RegexList;\r\n\r\n\tstruct EditorState\r\n\t{\r\n\t\tCoordinates mSelectionStart;\r\n\t\tCoordinates mSelectionEnd;\r\n\t\tCoordinates mCursorPosition;\r\n\t};\r\n\r\n\tclass UndoRecord\r\n\t{\r\n\tpublic:\r\n\t\tUndoRecord() {}\r\n\t\t~UndoRecord() {}\r\n\r\n\t\tUndoRecord(\r\n\t\t\tconst std::string& aAdded,\r\n\t\t\tconst TextEditor::Coordinates aAddedStart,\r\n\t\t\tconst TextEditor::Coordinates aAddedEnd,\r\n\r\n\t\t\tconst std::string& aRemoved,\r\n\t\t\tconst TextEditor::Coordinates aRemovedStart,\r\n\t\t\tconst TextEditor::Coordinates aRemovedEnd,\r\n\r\n\t\t\tTextEditor::EditorState& aBefore,\r\n\t\t\tTextEditor::EditorState& aAfter);\r\n\r\n\t\tvoid Undo(TextEditor* aEditor);\r\n\t\tvoid Redo(TextEditor* aEditor);\r\n\r\n\t\tstd::string mAdded;\r\n\t\tCoordinates mAddedStart;\r\n\t\tCoordinates mAddedEnd;\r\n\r\n\t\tstd::string mRemoved;\r\n\t\tCoordinates mRemovedStart;\r\n\t\tCoordinates mRemovedEnd;\r\n\r\n\t\tEditorState mBefore;\r\n\t\tEditorState mAfter;\r\n\t};\r\n\r\n\ttypedef std::vector<UndoRecord> UndoBuffer;\r\n\r\n\tvoid ProcessInputs();\r\n\tvoid Colorize(int aFromLine = 0, int aCount = -1);\r\n\tvoid ColorizeRange(int aFromLine = 0, int aToLine = 0);\r\n\tvoid ColorizeInternal();\r\n\tfloat TextDistanceToLineStart(const Coordinates& aFrom) const;\r\n\tvoid EnsureCursorVisible();\r\n\tint GetPageSize() const;\r\n\tstd::string GetText(const Coordinates& aStart, const Coordinates& aEnd) const;\r\n\tCoordinates GetActualCursorCoordinates() const;\r\n\tCoordinates SanitizeCoordinates(const Coordinates& aValue) const;\r\n\tvoid Advance(Coordinates& aCoordinates) const;\r\n\tvoid DeleteRange(const Coordinates& aStart, const Coordinates& aEnd);\r\n\tint InsertTextAt(Coordinates& aWhere, const char* aValue);\r\n\tvoid AddUndo(UndoRecord& aValue);\r\n\tCoordinates ScreenPosToCoordinates(const ImVec2& aPosition) const;\r\n\tCoordinates FindWordStart(const Coordinates& aFrom) const;\r\n\tCoordinates FindWordEnd(const Coordinates& aFrom) const;\r\n\tCoordinates FindNextWord(const Coordinates& aFrom) const;\r\n\tint GetCharacterIndex(const Coordinates& aCoordinates) const;\r\n\tint GetCharacterColumn(int aLine, int aIndex) const;\r\n\tint GetLineCharacterCount(int aLine) const;\r\n\tint GetLineMaxColumn(int aLine) const;\r\n\tbool IsOnWordBoundary(const Coordinates& aAt) const;\r\n\tvoid RemoveLine(int aStart, int aEnd);\r\n\tvoid RemoveLine(int aIndex);\r\n\tLine& InsertLine(int aIndex);\r\n\tvoid EnterCharacter(ImWchar aChar, bool aShift);\r\n\tvoid Backspace();\r\n\tvoid DeleteSelection();\r\n\tstd::string GetWordUnderCursor() const;\r\n\tstd::string GetWordAt(const Coordinates& aCoords) const;\r\n\tImU32 GetGlyphColor(const Glyph& aGlyph) const;\r\n\r\n\tvoid HandleKeyboardInputs();\r\n\tvoid HandleMouseInputs();\r\n\tvoid Render();\r\n\r\n\tfloat mLineSpacing;\r\n\tLines mLines;\r\n\tEditorState mState;\r\n\tUndoBuffer mUndoBuffer;\r\n\tint mUndoIndex;\r\n\r\n\tint mTabSize;\r\n\tbool mOverwrite;\r\n\tbool mReadOnly;\r\n\tbool mWithinRender;\r\n\tbool mScrollToCursor;\r\n\tbool mScrollToTop;\r\n\tbool mTextChanged;\r\n\tbool mColorizerEnabled;\r\n\tfloat mTextStart;                   // position (in pixels) where a code line starts relative to the left of the TextEditor.\r\n\tint  mLeftMargin;\r\n\tbool mCursorPositionChanged;\r\n\tint mColorRangeMin, mColorRangeMax;\r\n\tSelectionMode mSelectionMode;\r\n\tbool mHandleKeyboardInputs;\r\n\tbool mHandleMouseInputs;\r\n\tbool mIgnoreImGuiChild;\r\n\tbool mShowWhitespaces;\r\n\r\n\tPalette mPaletteBase;\r\n\tPalette mPalette;\r\n\tLanguageDefinition mLanguageDefinition;\r\n\tRegexList mRegexList;\r\n\r\n\tbool mCheckComments;\r\n\tBreakpoints mBreakpoints;\r\n\tErrorMarkers mErrorMarkers;\r\n\tImVec2 mCharAdvance;\r\n\tCoordinates mInteractiveStart, mInteractiveEnd;\r\n\tstd::string mLineBuffer;\r\n\tuint64_t mStartTime;\r\n\r\n\tfloat mLastClick;\r\n};\r\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/ImGuizmo/ImGuizmo.cpp",
    "content": "// https://github.com/CedricGuillemet/ImGuizmo\n// v 1.84 WIP\n//\n// The MIT License(MIT)\n//\n// Copyright(c) 2021 Cedric Guillemet\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files(the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions :\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n//\n\n#include \"imgui.h\"\n#ifndef IMGUI_DEFINE_MATH_OPERATORS\n#define IMGUI_DEFINE_MATH_OPERATORS\n#endif\n#include \"imgui_internal.h\"\n#include \"ImGuizmo.h\"\n\n#if defined(_MSC_VER) || defined(__MINGW32__)\n#include <malloc.h>\n#endif\n#if !defined(_MSC_VER) && !defined(__MINGW64_VERSION_MAJOR)\n#define _malloca(x) alloca(x)\n#define _freea(x)\n#endif\n\n// includes patches for multiview from\n// https://github.com/CedricGuillemet/ImGuizmo/issues/15\n\nnamespace IMGUIZMO_NAMESPACE\n{\n   static const float ZPI = 3.14159265358979323846f;\n   static const float RAD2DEG = (180.f / ZPI);\n   static const float DEG2RAD = (ZPI / 180.f);\n   const float screenRotateSize = 0.06f;\n   // scale a bit so translate axis do not touch when in universal\n   const float rotationDisplayFactor = 1.2f;\n\n   static OPERATION operator&(OPERATION lhs, OPERATION rhs)\n   {\n     return static_cast<OPERATION>(static_cast<int>(lhs) & static_cast<int>(rhs));\n   }\n\n   static bool operator!=(OPERATION lhs, int rhs)\n   {\n     return static_cast<int>(lhs) != rhs;\n   }\n\n   static bool operator==(OPERATION lhs, int rhs)\n   {\n     return static_cast<int>(lhs) == rhs;\n   }\n\n   static bool Intersects(OPERATION lhs, OPERATION rhs)\n   {\n     return (lhs & rhs) != 0;\n   }\n\n   // True if lhs contains rhs\n   static bool Contains(OPERATION lhs, OPERATION rhs)\n   {\n     return (lhs & rhs) == rhs;\n   }\n\n   ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n   // utility and math\n\n   void FPU_MatrixF_x_MatrixF(const float* a, const float* b, float* r)\n   {\n      r[0] = a[0] * b[0] + a[1] * b[4] + a[2] * b[8] + a[3] * b[12];\n      r[1] = a[0] * b[1] + a[1] * b[5] + a[2] * b[9] + a[3] * b[13];\n      r[2] = a[0] * b[2] + a[1] * b[6] + a[2] * b[10] + a[3] * b[14];\n      r[3] = a[0] * b[3] + a[1] * b[7] + a[2] * b[11] + a[3] * b[15];\n\n      r[4] = a[4] * b[0] + a[5] * b[4] + a[6] * b[8] + a[7] * b[12];\n      r[5] = a[4] * b[1] + a[5] * b[5] + a[6] * b[9] + a[7] * b[13];\n      r[6] = a[4] * b[2] + a[5] * b[6] + a[6] * b[10] + a[7] * b[14];\n      r[7] = a[4] * b[3] + a[5] * b[7] + a[6] * b[11] + a[7] * b[15];\n\n      r[8] = a[8] * b[0] + a[9] * b[4] + a[10] * b[8] + a[11] * b[12];\n      r[9] = a[8] * b[1] + a[9] * b[5] + a[10] * b[9] + a[11] * b[13];\n      r[10] = a[8] * b[2] + a[9] * b[6] + a[10] * b[10] + a[11] * b[14];\n      r[11] = a[8] * b[3] + a[9] * b[7] + a[10] * b[11] + a[11] * b[15];\n\n      r[12] = a[12] * b[0] + a[13] * b[4] + a[14] * b[8] + a[15] * b[12];\n      r[13] = a[12] * b[1] + a[13] * b[5] + a[14] * b[9] + a[15] * b[13];\n      r[14] = a[12] * b[2] + a[13] * b[6] + a[14] * b[10] + a[15] * b[14];\n      r[15] = a[12] * b[3] + a[13] * b[7] + a[14] * b[11] + a[15] * b[15];\n   }\n\n   void Frustum(float left, float right, float bottom, float top, float znear, float zfar, float* m16)\n   {\n      float temp, temp2, temp3, temp4;\n      temp = 2.0f * znear;\n      temp2 = right - left;\n      temp3 = top - bottom;\n      temp4 = zfar - znear;\n      m16[0] = temp / temp2;\n      m16[1] = 0.0;\n      m16[2] = 0.0;\n      m16[3] = 0.0;\n      m16[4] = 0.0;\n      m16[5] = temp / temp3;\n      m16[6] = 0.0;\n      m16[7] = 0.0;\n      m16[8] = (right + left) / temp2;\n      m16[9] = (top + bottom) / temp3;\n      m16[10] = (-zfar - znear) / temp4;\n      m16[11] = -1.0f;\n      m16[12] = 0.0;\n      m16[13] = 0.0;\n      m16[14] = (-temp * zfar) / temp4;\n      m16[15] = 0.0;\n   }\n\n   void Perspective(float fovyInDegrees, float aspectRatio, float znear, float zfar, float* m16)\n   {\n      float ymax, xmax;\n      ymax = znear * tanf(fovyInDegrees * DEG2RAD);\n      xmax = ymax * aspectRatio;\n      Frustum(-xmax, xmax, -ymax, ymax, znear, zfar, m16);\n   }\n\n   void Cross(const float* a, const float* b, float* r)\n   {\n      r[0] = a[1] * b[2] - a[2] * b[1];\n      r[1] = a[2] * b[0] - a[0] * b[2];\n      r[2] = a[0] * b[1] - a[1] * b[0];\n   }\n\n   float Dot(const float* a, const float* b)\n   {\n      return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];\n   }\n\n   void Normalize(const float* a, float* r)\n   {\n      float il = 1.f / (sqrtf(Dot(a, a)) + FLT_EPSILON);\n      r[0] = a[0] * il;\n      r[1] = a[1] * il;\n      r[2] = a[2] * il;\n   }\n\n   void LookAt(const float* eye, const float* at, const float* up, float* m16)\n   {\n      float X[3], Y[3], Z[3], tmp[3];\n\n      tmp[0] = eye[0] - at[0];\n      tmp[1] = eye[1] - at[1];\n      tmp[2] = eye[2] - at[2];\n      Normalize(tmp, Z);\n      Normalize(up, Y);\n      Cross(Y, Z, tmp);\n      Normalize(tmp, X);\n      Cross(Z, X, tmp);\n      Normalize(tmp, Y);\n\n      m16[0] = X[0];\n      m16[1] = Y[0];\n      m16[2] = Z[0];\n      m16[3] = 0.0f;\n      m16[4] = X[1];\n      m16[5] = Y[1];\n      m16[6] = Z[1];\n      m16[7] = 0.0f;\n      m16[8] = X[2];\n      m16[9] = Y[2];\n      m16[10] = Z[2];\n      m16[11] = 0.0f;\n      m16[12] = -Dot(X, eye);\n      m16[13] = -Dot(Y, eye);\n      m16[14] = -Dot(Z, eye);\n      m16[15] = 1.0f;\n   }\n\n   template <typename T> T Clamp(T x, T y, T z) { return ((x < y) ? y : ((x > z) ? z : x)); }\n   template <typename T> T max(T x, T y) { return (x > y) ? x : y; }\n   template <typename T> T min(T x, T y) { return (x < y) ? x : y; }\n   template <typename T> bool IsWithin(T x, T y, T z) { return (x >= y) && (x <= z); }\n\n   struct matrix_t;\n   struct vec_t\n   {\n   public:\n      float x, y, z, w;\n\n      void Lerp(const vec_t& v, float t)\n      {\n         x += (v.x - x) * t;\n         y += (v.y - y) * t;\n         z += (v.z - z) * t;\n         w += (v.w - w) * t;\n      }\n\n      void Set(float v) { x = y = z = w = v; }\n      void Set(float _x, float _y, float _z = 0.f, float _w = 0.f) { x = _x; y = _y; z = _z; w = _w; }\n\n      vec_t& operator -= (const vec_t& v) { x -= v.x; y -= v.y; z -= v.z; w -= v.w; return *this; }\n      vec_t& operator += (const vec_t& v) { x += v.x; y += v.y; z += v.z; w += v.w; return *this; }\n      vec_t& operator *= (const vec_t& v) { x *= v.x; y *= v.y; z *= v.z; w *= v.w; return *this; }\n      vec_t& operator *= (float v) { x *= v;    y *= v;    z *= v;    w *= v;    return *this; }\n\n      vec_t operator * (float f) const;\n      vec_t operator - () const;\n      vec_t operator - (const vec_t& v) const;\n      vec_t operator + (const vec_t& v) const;\n      vec_t operator * (const vec_t& v) const;\n\n      const vec_t& operator + () const { return (*this); }\n      float Length() const { return sqrtf(x * x + y * y + z * z); };\n      float LengthSq() const { return (x * x + y * y + z * z); };\n      vec_t Normalize() { (*this) *= (1.f / ( Length() > FLT_EPSILON ? Length() : FLT_EPSILON ) ); return (*this); }\n      vec_t Normalize(const vec_t& v) { this->Set(v.x, v.y, v.z, v.w); this->Normalize(); return (*this); }\n      vec_t Abs() const;\n\n      void Cross(const vec_t& v)\n      {\n         vec_t res;\n         res.x = y * v.z - z * v.y;\n         res.y = z * v.x - x * v.z;\n         res.z = x * v.y - y * v.x;\n\n         x = res.x;\n         y = res.y;\n         z = res.z;\n         w = 0.f;\n      }\n\n      void Cross(const vec_t& v1, const vec_t& v2)\n      {\n         x = v1.y * v2.z - v1.z * v2.y;\n         y = v1.z * v2.x - v1.x * v2.z;\n         z = v1.x * v2.y - v1.y * v2.x;\n         w = 0.f;\n      }\n\n      float Dot(const vec_t& v) const\n      {\n         return (x * v.x) + (y * v.y) + (z * v.z) + (w * v.w);\n      }\n\n      float Dot3(const vec_t& v) const\n      {\n         return (x * v.x) + (y * v.y) + (z * v.z);\n      }\n\n      void Transform(const matrix_t& matrix);\n      void Transform(const vec_t& s, const matrix_t& matrix);\n\n      void TransformVector(const matrix_t& matrix);\n      void TransformPoint(const matrix_t& matrix);\n      void TransformVector(const vec_t& v, const matrix_t& matrix) { (*this) = v; this->TransformVector(matrix); }\n      void TransformPoint(const vec_t& v, const matrix_t& matrix) { (*this) = v; this->TransformPoint(matrix); }\n\n      float& operator [] (size_t index) { return ((float*)&x)[index]; }\n      const float& operator [] (size_t index) const { return ((float*)&x)[index]; }\n      bool operator!=(const vec_t& other) const { return memcmp(this, &other, sizeof(vec_t)); }\n   };\n\n   vec_t makeVect(float _x, float _y, float _z = 0.f, float _w = 0.f) { vec_t res; res.x = _x; res.y = _y; res.z = _z; res.w = _w; return res; }\n   vec_t makeVect(ImVec2 v) { vec_t res; res.x = v.x; res.y = v.y; res.z = 0.f; res.w = 0.f; return res; }\n   vec_t vec_t::operator * (float f) const { return makeVect(x * f, y * f, z * f, w * f); }\n   vec_t vec_t::operator - () const { return makeVect(-x, -y, -z, -w); }\n   vec_t vec_t::operator - (const vec_t& v) const { return makeVect(x - v.x, y - v.y, z - v.z, w - v.w); }\n   vec_t vec_t::operator + (const vec_t& v) const { return makeVect(x + v.x, y + v.y, z + v.z, w + v.w); }\n   vec_t vec_t::operator * (const vec_t& v) const { return makeVect(x * v.x, y * v.y, z * v.z, w * v.w); }\n   vec_t vec_t::Abs() const { return makeVect(fabsf(x), fabsf(y), fabsf(z)); }\n\n   vec_t Normalized(const vec_t& v) { vec_t res; res = v; res.Normalize(); return res; }\n   vec_t Cross(const vec_t& v1, const vec_t& v2)\n   {\n      vec_t res;\n      res.x = v1.y * v2.z - v1.z * v2.y;\n      res.y = v1.z * v2.x - v1.x * v2.z;\n      res.z = v1.x * v2.y - v1.y * v2.x;\n      res.w = 0.f;\n      return res;\n   }\n\n   float Dot(const vec_t& v1, const vec_t& v2)\n   {\n      return (v1.x * v2.x) + (v1.y * v2.y) + (v1.z * v2.z);\n   }\n\n   vec_t BuildPlan(const vec_t& p_point1, const vec_t& p_normal)\n   {\n      vec_t normal, res;\n      normal.Normalize(p_normal);\n      res.w = normal.Dot(p_point1);\n      res.x = normal.x;\n      res.y = normal.y;\n      res.z = normal.z;\n      return res;\n   }\n\n   struct matrix_t\n   {\n   public:\n\n      union\n      {\n         float m[4][4];\n         float m16[16];\n         struct\n         {\n            vec_t right, up, dir, position;\n         } v;\n         vec_t component[4];\n      };\n\n      matrix_t(const matrix_t& other) { memcpy(&m16[0], &other.m16[0], sizeof(float) * 16); }\n      matrix_t() {}\n\n      operator float* () { return m16; }\n      operator const float* () const { return m16; }\n      void Translation(float _x, float _y, float _z) { this->Translation(makeVect(_x, _y, _z)); }\n\n      void Translation(const vec_t& vt)\n      {\n         v.right.Set(1.f, 0.f, 0.f, 0.f);\n         v.up.Set(0.f, 1.f, 0.f, 0.f);\n         v.dir.Set(0.f, 0.f, 1.f, 0.f);\n         v.position.Set(vt.x, vt.y, vt.z, 1.f);\n      }\n\n      void Scale(float _x, float _y, float _z)\n      {\n         v.right.Set(_x, 0.f, 0.f, 0.f);\n         v.up.Set(0.f, _y, 0.f, 0.f);\n         v.dir.Set(0.f, 0.f, _z, 0.f);\n         v.position.Set(0.f, 0.f, 0.f, 1.f);\n      }\n      void Scale(const vec_t& s) { Scale(s.x, s.y, s.z); }\n\n      matrix_t& operator *= (const matrix_t& mat)\n      {\n         matrix_t tmpMat;\n         tmpMat = *this;\n         tmpMat.Multiply(mat);\n         *this = tmpMat;\n         return *this;\n      }\n      matrix_t operator * (const matrix_t& mat) const\n      {\n         matrix_t matT;\n         matT.Multiply(*this, mat);\n         return matT;\n      }\n\n      void Multiply(const matrix_t& matrix)\n      {\n         matrix_t tmp;\n         tmp = *this;\n\n         FPU_MatrixF_x_MatrixF((float*)&tmp, (float*)&matrix, (float*)this);\n      }\n\n      void Multiply(const matrix_t& m1, const matrix_t& m2)\n      {\n         FPU_MatrixF_x_MatrixF((float*)&m1, (float*)&m2, (float*)this);\n      }\n\n      float GetDeterminant() const\n      {\n         return m[0][0] * m[1][1] * m[2][2] + m[0][1] * m[1][2] * m[2][0] + m[0][2] * m[1][0] * m[2][1] -\n            m[0][2] * m[1][1] * m[2][0] - m[0][1] * m[1][0] * m[2][2] - m[0][0] * m[1][2] * m[2][1];\n      }\n\n      float Inverse(const matrix_t& srcMatrix, bool affine = false);\n      void SetToIdentity()\n      {\n         v.right.Set(1.f, 0.f, 0.f, 0.f);\n         v.up.Set(0.f, 1.f, 0.f, 0.f);\n         v.dir.Set(0.f, 0.f, 1.f, 0.f);\n         v.position.Set(0.f, 0.f, 0.f, 1.f);\n      }\n      void Transpose()\n      {\n         matrix_t tmpm;\n         for (int l = 0; l < 4; l++)\n         {\n            for (int c = 0; c < 4; c++)\n            {\n               tmpm.m[l][c] = m[c][l];\n            }\n         }\n         (*this) = tmpm;\n      }\n\n      void RotationAxis(const vec_t& axis, float angle);\n\n      void OrthoNormalize()\n      {\n         v.right.Normalize();\n         v.up.Normalize();\n         v.dir.Normalize();\n      }\n   };\n\n   void vec_t::Transform(const matrix_t& matrix)\n   {\n      vec_t out;\n\n      out.x = x * matrix.m[0][0] + y * matrix.m[1][0] + z * matrix.m[2][0] + w * matrix.m[3][0];\n      out.y = x * matrix.m[0][1] + y * matrix.m[1][1] + z * matrix.m[2][1] + w * matrix.m[3][1];\n      out.z = x * matrix.m[0][2] + y * matrix.m[1][2] + z * matrix.m[2][2] + w * matrix.m[3][2];\n      out.w = x * matrix.m[0][3] + y * matrix.m[1][3] + z * matrix.m[2][3] + w * matrix.m[3][3];\n\n      x = out.x;\n      y = out.y;\n      z = out.z;\n      w = out.w;\n   }\n\n   void vec_t::Transform(const vec_t& s, const matrix_t& matrix)\n   {\n      *this = s;\n      Transform(matrix);\n   }\n\n   void vec_t::TransformPoint(const matrix_t& matrix)\n   {\n      vec_t out;\n\n      out.x = x * matrix.m[0][0] + y * matrix.m[1][0] + z * matrix.m[2][0] + matrix.m[3][0];\n      out.y = x * matrix.m[0][1] + y * matrix.m[1][1] + z * matrix.m[2][1] + matrix.m[3][1];\n      out.z = x * matrix.m[0][2] + y * matrix.m[1][2] + z * matrix.m[2][2] + matrix.m[3][2];\n      out.w = x * matrix.m[0][3] + y * matrix.m[1][3] + z * matrix.m[2][3] + matrix.m[3][3];\n\n      x = out.x;\n      y = out.y;\n      z = out.z;\n      w = out.w;\n   }\n\n   void vec_t::TransformVector(const matrix_t& matrix)\n   {\n      vec_t out;\n\n      out.x = x * matrix.m[0][0] + y * matrix.m[1][0] + z * matrix.m[2][0];\n      out.y = x * matrix.m[0][1] + y * matrix.m[1][1] + z * matrix.m[2][1];\n      out.z = x * matrix.m[0][2] + y * matrix.m[1][2] + z * matrix.m[2][2];\n      out.w = x * matrix.m[0][3] + y * matrix.m[1][3] + z * matrix.m[2][3];\n\n      x = out.x;\n      y = out.y;\n      z = out.z;\n      w = out.w;\n   }\n\n   float matrix_t::Inverse(const matrix_t& srcMatrix, bool affine)\n   {\n      float det = 0;\n\n      if (affine)\n      {\n         det = GetDeterminant();\n         float s = 1 / det;\n         m[0][0] = (srcMatrix.m[1][1] * srcMatrix.m[2][2] - srcMatrix.m[1][2] * srcMatrix.m[2][1]) * s;\n         m[0][1] = (srcMatrix.m[2][1] * srcMatrix.m[0][2] - srcMatrix.m[2][2] * srcMatrix.m[0][1]) * s;\n         m[0][2] = (srcMatrix.m[0][1] * srcMatrix.m[1][2] - srcMatrix.m[0][2] * srcMatrix.m[1][1]) * s;\n         m[1][0] = (srcMatrix.m[1][2] * srcMatrix.m[2][0] - srcMatrix.m[1][0] * srcMatrix.m[2][2]) * s;\n         m[1][1] = (srcMatrix.m[2][2] * srcMatrix.m[0][0] - srcMatrix.m[2][0] * srcMatrix.m[0][2]) * s;\n         m[1][2] = (srcMatrix.m[0][2] * srcMatrix.m[1][0] - srcMatrix.m[0][0] * srcMatrix.m[1][2]) * s;\n         m[2][0] = (srcMatrix.m[1][0] * srcMatrix.m[2][1] - srcMatrix.m[1][1] * srcMatrix.m[2][0]) * s;\n         m[2][1] = (srcMatrix.m[2][0] * srcMatrix.m[0][1] - srcMatrix.m[2][1] * srcMatrix.m[0][0]) * s;\n         m[2][2] = (srcMatrix.m[0][0] * srcMatrix.m[1][1] - srcMatrix.m[0][1] * srcMatrix.m[1][0]) * s;\n         m[3][0] = -(m[0][0] * srcMatrix.m[3][0] + m[1][0] * srcMatrix.m[3][1] + m[2][0] * srcMatrix.m[3][2]);\n         m[3][1] = -(m[0][1] * srcMatrix.m[3][0] + m[1][1] * srcMatrix.m[3][1] + m[2][1] * srcMatrix.m[3][2]);\n         m[3][2] = -(m[0][2] * srcMatrix.m[3][0] + m[1][2] * srcMatrix.m[3][1] + m[2][2] * srcMatrix.m[3][2]);\n      }\n      else\n      {\n         // transpose matrix\n         float src[16];\n         for (int i = 0; i < 4; ++i)\n         {\n            src[i] = srcMatrix.m16[i * 4];\n            src[i + 4] = srcMatrix.m16[i * 4 + 1];\n            src[i + 8] = srcMatrix.m16[i * 4 + 2];\n            src[i + 12] = srcMatrix.m16[i * 4 + 3];\n         }\n\n         // calculate pairs for first 8 elements (cofactors)\n         float tmp[12]; // temp array for pairs\n         tmp[0] = src[10] * src[15];\n         tmp[1] = src[11] * src[14];\n         tmp[2] = src[9] * src[15];\n         tmp[3] = src[11] * src[13];\n         tmp[4] = src[9] * src[14];\n         tmp[5] = src[10] * src[13];\n         tmp[6] = src[8] * src[15];\n         tmp[7] = src[11] * src[12];\n         tmp[8] = src[8] * src[14];\n         tmp[9] = src[10] * src[12];\n         tmp[10] = src[8] * src[13];\n         tmp[11] = src[9] * src[12];\n\n         // calculate first 8 elements (cofactors)\n         m16[0] = (tmp[0] * src[5] + tmp[3] * src[6] + tmp[4] * src[7]) - (tmp[1] * src[5] + tmp[2] * src[6] + tmp[5] * src[7]);\n         m16[1] = (tmp[1] * src[4] + tmp[6] * src[6] + tmp[9] * src[7]) - (tmp[0] * src[4] + tmp[7] * src[6] + tmp[8] * src[7]);\n         m16[2] = (tmp[2] * src[4] + tmp[7] * src[5] + tmp[10] * src[7]) - (tmp[3] * src[4] + tmp[6] * src[5] + tmp[11] * src[7]);\n         m16[3] = (tmp[5] * src[4] + tmp[8] * src[5] + tmp[11] * src[6]) - (tmp[4] * src[4] + tmp[9] * src[5] + tmp[10] * src[6]);\n         m16[4] = (tmp[1] * src[1] + tmp[2] * src[2] + tmp[5] * src[3]) - (tmp[0] * src[1] + tmp[3] * src[2] + tmp[4] * src[3]);\n         m16[5] = (tmp[0] * src[0] + tmp[7] * src[2] + tmp[8] * src[3]) - (tmp[1] * src[0] + tmp[6] * src[2] + tmp[9] * src[3]);\n         m16[6] = (tmp[3] * src[0] + tmp[6] * src[1] + tmp[11] * src[3]) - (tmp[2] * src[0] + tmp[7] * src[1] + tmp[10] * src[3]);\n         m16[7] = (tmp[4] * src[0] + tmp[9] * src[1] + tmp[10] * src[2]) - (tmp[5] * src[0] + tmp[8] * src[1] + tmp[11] * src[2]);\n\n         // calculate pairs for second 8 elements (cofactors)\n         tmp[0] = src[2] * src[7];\n         tmp[1] = src[3] * src[6];\n         tmp[2] = src[1] * src[7];\n         tmp[3] = src[3] * src[5];\n         tmp[4] = src[1] * src[6];\n         tmp[5] = src[2] * src[5];\n         tmp[6] = src[0] * src[7];\n         tmp[7] = src[3] * src[4];\n         tmp[8] = src[0] * src[6];\n         tmp[9] = src[2] * src[4];\n         tmp[10] = src[0] * src[5];\n         tmp[11] = src[1] * src[4];\n\n         // calculate second 8 elements (cofactors)\n         m16[8] = (tmp[0] * src[13] + tmp[3] * src[14] + tmp[4] * src[15]) - (tmp[1] * src[13] + tmp[2] * src[14] + tmp[5] * src[15]);\n         m16[9] = (tmp[1] * src[12] + tmp[6] * src[14] + tmp[9] * src[15]) - (tmp[0] * src[12] + tmp[7] * src[14] + tmp[8] * src[15]);\n         m16[10] = (tmp[2] * src[12] + tmp[7] * src[13] + tmp[10] * src[15]) - (tmp[3] * src[12] + tmp[6] * src[13] + tmp[11] * src[15]);\n         m16[11] = (tmp[5] * src[12] + tmp[8] * src[13] + tmp[11] * src[14]) - (tmp[4] * src[12] + tmp[9] * src[13] + tmp[10] * src[14]);\n         m16[12] = (tmp[2] * src[10] + tmp[5] * src[11] + tmp[1] * src[9]) - (tmp[4] * src[11] + tmp[0] * src[9] + tmp[3] * src[10]);\n         m16[13] = (tmp[8] * src[11] + tmp[0] * src[8] + tmp[7] * src[10]) - (tmp[6] * src[10] + tmp[9] * src[11] + tmp[1] * src[8]);\n         m16[14] = (tmp[6] * src[9] + tmp[11] * src[11] + tmp[3] * src[8]) - (tmp[10] * src[11] + tmp[2] * src[8] + tmp[7] * src[9]);\n         m16[15] = (tmp[10] * src[10] + tmp[4] * src[8] + tmp[9] * src[9]) - (tmp[8] * src[9] + tmp[11] * src[10] + tmp[5] * src[8]);\n\n         // calculate determinant\n         det = src[0] * m16[0] + src[1] * m16[1] + src[2] * m16[2] + src[3] * m16[3];\n\n         // calculate matrix inverse\n         float invdet = 1 / det;\n         for (int j = 0; j < 16; ++j)\n         {\n            m16[j] *= invdet;\n         }\n      }\n\n      return det;\n   }\n\n   void matrix_t::RotationAxis(const vec_t& axis, float angle)\n   {\n      float length2 = axis.LengthSq();\n      if (length2 < FLT_EPSILON)\n      {\n         SetToIdentity();\n         return;\n      }\n\n      vec_t n = axis * (1.f / sqrtf(length2));\n      float s = sinf(angle);\n      float c = cosf(angle);\n      float k = 1.f - c;\n\n      float xx = n.x * n.x * k + c;\n      float yy = n.y * n.y * k + c;\n      float zz = n.z * n.z * k + c;\n      float xy = n.x * n.y * k;\n      float yz = n.y * n.z * k;\n      float zx = n.z * n.x * k;\n      float xs = n.x * s;\n      float ys = n.y * s;\n      float zs = n.z * s;\n\n      m[0][0] = xx;\n      m[0][1] = xy + zs;\n      m[0][2] = zx - ys;\n      m[0][3] = 0.f;\n      m[1][0] = xy - zs;\n      m[1][1] = yy;\n      m[1][2] = yz + xs;\n      m[1][3] = 0.f;\n      m[2][0] = zx + ys;\n      m[2][1] = yz - xs;\n      m[2][2] = zz;\n      m[2][3] = 0.f;\n      m[3][0] = 0.f;\n      m[3][1] = 0.f;\n      m[3][2] = 0.f;\n      m[3][3] = 1.f;\n   }\n\n   ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n   //\n\n   enum MOVETYPE\n   {\n      MT_NONE,\n      MT_MOVE_X,\n      MT_MOVE_Y,\n      MT_MOVE_Z,\n      MT_MOVE_YZ,\n      MT_MOVE_ZX,\n      MT_MOVE_XY,\n      MT_MOVE_SCREEN,\n      MT_ROTATE_X,\n      MT_ROTATE_Y,\n      MT_ROTATE_Z,\n      MT_ROTATE_SCREEN,\n      MT_SCALE_X,\n      MT_SCALE_Y,\n      MT_SCALE_Z,\n      MT_SCALE_XYZ\n   };\n\n   static bool IsTranslateType(int type)\n   {\n     return type >= MT_MOVE_X && type <= MT_MOVE_SCREEN;\n   }\n\n   static bool IsRotateType(int type)\n   {\n     return type >= MT_ROTATE_X && type <= MT_ROTATE_SCREEN;\n   }\n\n   static bool IsScaleType(int type)\n   {\n     return type >= MT_SCALE_X && type <= MT_SCALE_XYZ;\n   }\n\n   // Matches MT_MOVE_AB order\n   static const OPERATION TRANSLATE_PLANS[3] = { TRANSLATE_Y | TRANSLATE_Z, TRANSLATE_X | TRANSLATE_Z, TRANSLATE_X | TRANSLATE_Y };\n\n   struct Context\n   {\n      Context() : mbUsing(false), mbEnable(true), mbUsingBounds(false)\n      {\n      }\n\n      ImDrawList* mDrawList;\n\n      MODE mMode;\n      matrix_t mViewMat;\n      matrix_t mProjectionMat;\n      matrix_t mModel;\n      matrix_t mModelLocal; // orthonormalized model\n      matrix_t mModelInverse;\n      matrix_t mModelSource;\n      matrix_t mModelSourceInverse;\n      matrix_t mMVP;\n      matrix_t mMVPLocal; // MVP with full model matrix whereas mMVP's model matrix might only be translation in case of World space edition\n      matrix_t mViewProjection;\n\n      vec_t mModelScaleOrigin;\n      vec_t mCameraEye;\n      vec_t mCameraRight;\n      vec_t mCameraDir;\n      vec_t mCameraUp;\n      vec_t mRayOrigin;\n      vec_t mRayVector;\n\n      float  mRadiusSquareCenter;\n      ImVec2 mScreenSquareCenter;\n      ImVec2 mScreenSquareMin;\n      ImVec2 mScreenSquareMax;\n\n      float mScreenFactor;\n      vec_t mRelativeOrigin;\n\n      bool mbUsing;\n      bool mbEnable;\n      bool mbMouseOver;\n      bool mReversed; // reversed projection matrix\n\n      // translation\n      vec_t mTranslationPlan;\n      vec_t mTranslationPlanOrigin;\n      vec_t mMatrixOrigin;\n      vec_t mTranslationLastDelta;\n\n      // rotation\n      vec_t mRotationVectorSource;\n      float mRotationAngle;\n      float mRotationAngleOrigin;\n      //vec_t mWorldToLocalAxis;\n\n      // scale\n      vec_t mScale;\n      vec_t mScaleValueOrigin;\n      vec_t mScaleLast;\n      float mSaveMousePosx;\n\n      // save axis factor when using gizmo\n      bool mBelowAxisLimit[3];\n      bool mBelowPlaneLimit[3];\n      float mAxisFactor[3];\n\n      // bounds stretching\n      vec_t mBoundsPivot;\n      vec_t mBoundsAnchor;\n      vec_t mBoundsPlan;\n      vec_t mBoundsLocalPivot;\n      int mBoundsBestAxis;\n      int mBoundsAxis[2];\n      bool mbUsingBounds;\n      matrix_t mBoundsMatrix;\n\n      //\n      int mCurrentOperation;\n\n      float mX = 0.f;\n      float mY = 0.f;\n      float mWidth = 0.f;\n      float mHeight = 0.f;\n      float mXMax = 0.f;\n      float mYMax = 0.f;\n      float mDisplayRatio = 1.f;\n\n      bool mIsOrthographic = false;\n\n      int mActualID = -1;\n      int mEditingID = -1;\n      OPERATION mOperation = OPERATION(-1);\n\n      bool mAllowAxisFlip = true;\n      float mGizmoSizeClipSpace = 0.1f;\n   };\n\n   static Context gContext;\n\n   static const vec_t directionUnary[3] = { makeVect(1.f, 0.f, 0.f), makeVect(0.f, 1.f, 0.f), makeVect(0.f, 0.f, 1.f) };\n   static const ImU32 directionColor[3] = { IM_COL32(0xAA, 0, 0, 0xFF), IM_COL32(0, 0xAA, 0, 0xFF), IM_COL32(0, 0, 0xAA, 0XFF) };\n\n   // Alpha: 100%: FF, 87%: DE, 70%: B3, 54%: 8A, 50%: 80, 38%: 61, 12%: 1F\n   static const ImU32 planeColor[3] = { IM_COL32(0xAA, 0, 0, 0x61), IM_COL32(0, 0xAA, 0, 0x61), IM_COL32(0, 0, 0xAA, 0x61) };\n   static const ImU32 selectionColor = IM_COL32(0xFF, 0x80, 0x10, 0x8A);\n   static const ImU32 inactiveColor = IM_COL32(0x99, 0x99, 0x99, 0x99);\n   static const ImU32 translationLineColor = IM_COL32(0xAA, 0xAA, 0xAA, 0xAA);\n   static const char* translationInfoMask[] = { \"X : %5.3f\", \"Y : %5.3f\", \"Z : %5.3f\",\n      \"Y : %5.3f Z : %5.3f\", \"X : %5.3f Z : %5.3f\", \"X : %5.3f Y : %5.3f\",\n      \"X : %5.3f Y : %5.3f Z : %5.3f\" };\n   static const char* scaleInfoMask[] = { \"X : %5.2f\", \"Y : %5.2f\", \"Z : %5.2f\", \"XYZ : %5.2f\" };\n   static const char* rotationInfoMask[] = { \"X : %5.2f deg %5.2f rad\", \"Y : %5.2f deg %5.2f rad\", \"Z : %5.2f deg %5.2f rad\", \"Screen : %5.2f deg %5.2f rad\" };\n   static const int translationInfoIndex[] = { 0,0,0, 1,0,0, 2,0,0, 1,2,0, 0,2,0, 0,1,0, 0,1,2 };\n   static const float quadMin = 0.5f;\n   static const float quadMax = 0.8f;\n   static const float quadUV[8] = { quadMin, quadMin, quadMin, quadMax, quadMax, quadMax, quadMax, quadMin };\n   static const int halfCircleSegmentCount = 64;\n   static const float snapTension = 0.5f;\n\n   ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n   //\n   static int GetMoveType(OPERATION op, vec_t* gizmoHitProportion);\n   static int GetRotateType(OPERATION op);\n   static int GetScaleType(OPERATION op);\n\n   static ImVec2 worldToPos(const vec_t& worldPos, const matrix_t& mat, ImVec2 position = ImVec2(gContext.mX, gContext.mY), ImVec2 size = ImVec2(gContext.mWidth, gContext.mHeight))\n   {\n      vec_t trans;\n      trans.TransformPoint(worldPos, mat);\n      trans *= 0.5f / trans.w;\n      trans += makeVect(0.5f, 0.5f);\n      trans.y = 1.f - trans.y;\n      trans.x *= size.x;\n      trans.y *= size.y;\n      trans.x += position.x;\n      trans.y += position.y;\n      return ImVec2(trans.x, trans.y);\n   }\n\n   static void ComputeCameraRay(vec_t& rayOrigin, vec_t& rayDir, ImVec2 position = ImVec2(gContext.mX, gContext.mY), ImVec2 size = ImVec2(gContext.mWidth, gContext.mHeight))\n   {\n      ImGuiIO& io = ImGui::GetIO();\n\n      matrix_t mViewProjInverse;\n      mViewProjInverse.Inverse(gContext.mViewMat * gContext.mProjectionMat);\n\n      const float mox = ((io.MousePos.x - position.x) / size.x) * 2.f - 1.f;\n      const float moy = (1.f - ((io.MousePos.y - position.y) / size.y)) * 2.f - 1.f;\n\n      const float zNear = gContext.mReversed ? (1.f - FLT_EPSILON) : 0.f;\n      const float zFar = gContext.mReversed ? 0.f : (1.f - FLT_EPSILON);\n\n      rayOrigin.Transform(makeVect(mox, moy, zNear, 1.f), mViewProjInverse);\n      rayOrigin *= 1.f / rayOrigin.w;\n      vec_t rayEnd;\n      rayEnd.Transform(makeVect(mox, moy, zFar, 1.f), mViewProjInverse);\n      rayEnd *= 1.f / rayEnd.w;\n      rayDir = Normalized(rayEnd - rayOrigin);\n   }\n\n   static float GetSegmentLengthClipSpace(const vec_t& start, const vec_t& end, const bool localCoordinates = false)\n   {\n      vec_t startOfSegment = start;\n      const matrix_t& mvp = localCoordinates ? gContext.mMVPLocal : gContext.mMVP;\n      startOfSegment.TransformPoint(mvp);\n      if (fabsf(startOfSegment.w) > FLT_EPSILON) // check for axis aligned with camera direction\n      {\n         startOfSegment *= 1.f / startOfSegment.w;\n      }\n\n      vec_t endOfSegment = end;\n      endOfSegment.TransformPoint(mvp);\n      if (fabsf(endOfSegment.w) > FLT_EPSILON) // check for axis aligned with camera direction\n      {\n         endOfSegment *= 1.f / endOfSegment.w;\n      }\n\n      vec_t clipSpaceAxis = endOfSegment - startOfSegment;\n      clipSpaceAxis.y /= gContext.mDisplayRatio;\n      float segmentLengthInClipSpace = sqrtf(clipSpaceAxis.x * clipSpaceAxis.x + clipSpaceAxis.y * clipSpaceAxis.y);\n      return segmentLengthInClipSpace;\n   }\n\n   static float GetParallelogram(const vec_t& ptO, const vec_t& ptA, const vec_t& ptB)\n   {\n      vec_t pts[] = { ptO, ptA, ptB };\n      for (unsigned int i = 0; i < 3; i++)\n      {\n         pts[i].TransformPoint(gContext.mMVP);\n         if (fabsf(pts[i].w) > FLT_EPSILON) // check for axis aligned with camera direction\n         {\n            pts[i] *= 1.f / pts[i].w;\n         }\n      }\n      vec_t segA = pts[1] - pts[0];\n      vec_t segB = pts[2] - pts[0];\n      segA.y /= gContext.mDisplayRatio;\n      segB.y /= gContext.mDisplayRatio;\n      vec_t segAOrtho = makeVect(-segA.y, segA.x);\n      segAOrtho.Normalize();\n      float dt = segAOrtho.Dot3(segB);\n      float surface = sqrtf(segA.x * segA.x + segA.y * segA.y) * fabsf(dt);\n      return surface;\n   }\n\n   inline vec_t PointOnSegment(const vec_t& point, const vec_t& vertPos1, const vec_t& vertPos2)\n   {\n      vec_t c = point - vertPos1;\n      vec_t V;\n\n      V.Normalize(vertPos2 - vertPos1);\n      float d = (vertPos2 - vertPos1).Length();\n      float t = V.Dot3(c);\n\n      if (t < 0.f)\n      {\n         return vertPos1;\n      }\n\n      if (t > d)\n      {\n         return vertPos2;\n      }\n\n      return vertPos1 + V * t;\n   }\n\n   static float IntersectRayPlane(const vec_t& rOrigin, const vec_t& rVector, const vec_t& plan)\n   {\n      const float numer = plan.Dot3(rOrigin) - plan.w;\n      const float denom = plan.Dot3(rVector);\n\n      if (fabsf(denom) < FLT_EPSILON)  // normal is orthogonal to vector, cant intersect\n      {\n         return -1.0f;\n      }\n\n      return -(numer / denom);\n   }\n\n   static float DistanceToPlane(const vec_t& point, const vec_t& plan)\n   {\n      return plan.Dot3(point) + plan.w;\n   }\n\n   static bool IsInContextRect(ImVec2 p)\n   {\n      return IsWithin(p.x, gContext.mX, gContext.mXMax) && IsWithin(p.y, gContext.mY, gContext.mYMax);\n   }\n\n   static bool IsHoveringWindow()\n   {\n      ImGuiContext& g = *ImGui::GetCurrentContext();\n      ImGuiWindow* window = ImGui::FindWindowByName(gContext.mDrawList->_OwnerName);\n      if (g.HoveredWindow == window)   // Mouse hovering drawlist window\n         return true;\n      if (g.HoveredWindow != NULL)     // Any other window is hovered\n         return false;\n      if (ImGui::IsMouseHoveringRect(window->InnerRect.Min, window->InnerRect.Max, false))   // Hovering drawlist window rect, while no other window is hovered (for _NoInputs windows)\n         return true;\n      return false;\n   }\n\n   void SetRect(float x, float y, float width, float height)\n   {\n      gContext.mX = x;\n      gContext.mY = y;\n      gContext.mWidth = width;\n      gContext.mHeight = height;\n      gContext.mXMax = gContext.mX + gContext.mWidth;\n      gContext.mYMax = gContext.mY + gContext.mXMax;\n      gContext.mDisplayRatio = width / height;\n   }\n\n   void SetOrthographic(bool isOrthographic)\n   {\n      gContext.mIsOrthographic = isOrthographic;\n   }\n\n   void SetDrawlist(ImDrawList* drawlist)\n   {\n      gContext.mDrawList = drawlist ? drawlist : ImGui::GetWindowDrawList();\n   }\n\n   void SetImGuiContext(ImGuiContext* ctx)\n   {\n      ImGui::SetCurrentContext(ctx);\n   }\n\n   void BeginFrame()\n   {\n      const ImU32 flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoBringToFrontOnFocus;\n\n#ifdef IMGUI_HAS_VIEWPORT\n      ImGui::SetNextWindowSize(ImGui::GetMainViewport()->Size);\n      ImGui::SetNextWindowPos(ImGui::GetMainViewport()->Pos);\n#else\n      ImGuiIO& io = ImGui::GetIO();\n      ImGui::SetNextWindowSize(io.DisplaySize);\n      ImGui::SetNextWindowPos(ImVec2(0, 0));\n#endif\n\n      ImGui::PushStyleColor(ImGuiCol_WindowBg, 0);\n      ImGui::PushStyleColor(ImGuiCol_Border, 0);\n      ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);\n\n      ImGui::Begin(\"gizmo\", NULL, flags);\n      gContext.mDrawList = ImGui::GetWindowDrawList();\n      ImGui::End();\n      ImGui::PopStyleVar();\n      ImGui::PopStyleColor(2);\n   }\n\n   bool IsUsing()\n   {\n      return gContext.mbUsing || gContext.mbUsingBounds;\n   }\n\n   bool IsOver()\n   {\n      return (Intersects(gContext.mOperation, TRANSLATE) && GetMoveType(gContext.mOperation, NULL) != MT_NONE) ||\n         (Intersects(gContext.mOperation, ROTATE) && GetRotateType(gContext.mOperation) != MT_NONE) ||\n         (Intersects(gContext.mOperation, SCALE) && GetScaleType(gContext.mOperation) != MT_NONE) || IsUsing();\n   }\n\n   bool IsOver(OPERATION op)\n   {\n      if(IsUsing())\n      {\n         return true;\n      }\n      if(Intersects(op, SCALE) && GetScaleType(op) != MT_NONE)\n      {\n         return true;\n      }\n      if(Intersects(op, ROTATE) && GetRotateType(op) != MT_NONE)\n      {\n         return true;\n      }\n      if(Intersects(op, TRANSLATE) && GetMoveType(op, NULL) != MT_NONE)\n      {\n         return true;\n      }\n      return false;\n   }\n\n   void Enable(bool enable)\n   {\n      gContext.mbEnable = enable;\n      if (!enable)\n      {\n         gContext.mbUsing = false;\n         gContext.mbUsingBounds = false;\n      }\n   }\n\n   static void ComputeContext(const float* view, const float* projection, float* matrix, MODE mode)\n   {\n      gContext.mMode = mode;\n      gContext.mViewMat = *(matrix_t*)view;\n      gContext.mProjectionMat = *(matrix_t*)projection;\n      gContext.mbMouseOver = IsHoveringWindow();\n\n      gContext.mModelLocal = *(matrix_t*)matrix;\n      gContext.mModelLocal.OrthoNormalize();\n\n      if (mode == LOCAL)\n      {\n         gContext.mModel = gContext.mModelLocal;\n      }\n      else\n      {\n         gContext.mModel.Translation(((matrix_t*)matrix)->v.position);\n      }\n      gContext.mModelSource = *(matrix_t*)matrix;\n      gContext.mModelScaleOrigin.Set(gContext.mModelSource.v.right.Length(), gContext.mModelSource.v.up.Length(), gContext.mModelSource.v.dir.Length());\n\n      gContext.mModelInverse.Inverse(gContext.mModel);\n      gContext.mModelSourceInverse.Inverse(gContext.mModelSource);\n      gContext.mViewProjection = gContext.mViewMat * gContext.mProjectionMat;\n      gContext.mMVP = gContext.mModel * gContext.mViewProjection;\n      gContext.mMVPLocal = gContext.mModelLocal * gContext.mViewProjection;\n\n      matrix_t viewInverse;\n      viewInverse.Inverse(gContext.mViewMat);\n      gContext.mCameraDir = viewInverse.v.dir;\n      gContext.mCameraEye = viewInverse.v.position;\n      gContext.mCameraRight = viewInverse.v.right;\n      gContext.mCameraUp = viewInverse.v.up;\n\n      // projection reverse\n       vec_t nearPos, farPos;\n       nearPos.Transform(makeVect(0, 0, 1.f, 1.f), gContext.mProjectionMat);\n       farPos.Transform(makeVect(0, 0, 2.f, 1.f), gContext.mProjectionMat);\n\n       gContext.mReversed = (nearPos.z/nearPos.w) > (farPos.z / farPos.w);\n\n      // compute scale from the size of camera right vector projected on screen at the matrix position\n      vec_t pointRight = viewInverse.v.right;\n      pointRight.TransformPoint(gContext.mViewProjection);\n      gContext.mScreenFactor = gContext.mGizmoSizeClipSpace / (pointRight.x / pointRight.w - gContext.mMVP.v.position.x / gContext.mMVP.v.position.w);\n\n      vec_t rightViewInverse = viewInverse.v.right;\n      rightViewInverse.TransformVector(gContext.mModelInverse);\n      float rightLength = GetSegmentLengthClipSpace(makeVect(0.f, 0.f), rightViewInverse);\n      gContext.mScreenFactor = gContext.mGizmoSizeClipSpace / rightLength;\n\n      ImVec2 centerSSpace = worldToPos(makeVect(0.f, 0.f), gContext.mMVP);\n      gContext.mScreenSquareCenter = centerSSpace;\n      gContext.mScreenSquareMin = ImVec2(centerSSpace.x - 10.f, centerSSpace.y - 10.f);\n      gContext.mScreenSquareMax = ImVec2(centerSSpace.x + 10.f, centerSSpace.y + 10.f);\n\n      ComputeCameraRay(gContext.mRayOrigin, gContext.mRayVector);\n   }\n\n   static void ComputeColors(ImU32* colors, int type, OPERATION operation)\n   {\n      if (gContext.mbEnable)\n      {\n         switch (operation)\n         {\n         case TRANSLATE:\n            colors[0] = (type == MT_MOVE_SCREEN) ? selectionColor : IM_COL32_WHITE;\n            for (int i = 0; i < 3; i++)\n            {\n               colors[i + 1] = (type == (int)(MT_MOVE_X + i)) ? selectionColor : directionColor[i];\n               colors[i + 4] = (type == (int)(MT_MOVE_YZ + i)) ? selectionColor : planeColor[i];\n               colors[i + 4] = (type == MT_MOVE_SCREEN) ? selectionColor : colors[i + 4];\n            }\n            break;\n         case ROTATE:\n            colors[0] = (type == MT_ROTATE_SCREEN) ? selectionColor : IM_COL32_WHITE;\n            for (int i = 0; i < 3; i++)\n            {\n               colors[i + 1] = (type == (int)(MT_ROTATE_X + i)) ? selectionColor : directionColor[i];\n            }\n            break;\n         case SCALEU:\n         case SCALE:\n            colors[0] = (type == MT_SCALE_XYZ) ? selectionColor : IM_COL32_WHITE;\n            for (int i = 0; i < 3; i++)\n            {\n               colors[i + 1] = (type == (int)(MT_SCALE_X + i)) ? selectionColor : directionColor[i];\n            }\n            break;\n         // note: this internal function is only called with three possible values for operation\n         default:\n            break;\n         }\n      }\n      else\n      {\n         for (int i = 0; i < 7; i++)\n         {\n            colors[i] = inactiveColor;\n         }\n      }\n   }\n\n   static void ComputeTripodAxisAndVisibility(const int axisIndex, vec_t& dirAxis, vec_t& dirPlaneX, vec_t& dirPlaneY, bool& belowAxisLimit, bool& belowPlaneLimit, const bool localCoordinates = false)\n   {\n      dirAxis = directionUnary[axisIndex];\n      dirPlaneX = directionUnary[(axisIndex + 1) % 3];\n      dirPlaneY = directionUnary[(axisIndex + 2) % 3];\n\n      if (gContext.mbUsing && (gContext.mActualID == -1 || gContext.mActualID == gContext.mEditingID))\n      {\n         // when using, use stored factors so the gizmo doesn't flip when we translate\n         belowAxisLimit = gContext.mBelowAxisLimit[axisIndex];\n         belowPlaneLimit = gContext.mBelowPlaneLimit[axisIndex];\n\n         dirAxis *= gContext.mAxisFactor[axisIndex];\n         dirPlaneX *= gContext.mAxisFactor[(axisIndex + 1) % 3];\n         dirPlaneY *= gContext.mAxisFactor[(axisIndex + 2) % 3];\n      }\n      else\n      {\n         // new method\n         float lenDir = GetSegmentLengthClipSpace(makeVect(0.f, 0.f, 0.f), dirAxis, localCoordinates);\n         float lenDirMinus = GetSegmentLengthClipSpace(makeVect(0.f, 0.f, 0.f), -dirAxis, localCoordinates);\n\n         float lenDirPlaneX = GetSegmentLengthClipSpace(makeVect(0.f, 0.f, 0.f), dirPlaneX, localCoordinates);\n         float lenDirMinusPlaneX = GetSegmentLengthClipSpace(makeVect(0.f, 0.f, 0.f), -dirPlaneX, localCoordinates);\n\n         float lenDirPlaneY = GetSegmentLengthClipSpace(makeVect(0.f, 0.f, 0.f), dirPlaneY, localCoordinates);\n         float lenDirMinusPlaneY = GetSegmentLengthClipSpace(makeVect(0.f, 0.f, 0.f), -dirPlaneY, localCoordinates);\n\n         // For readability\n         bool & allowFlip = gContext.mAllowAxisFlip;\n         float mulAxis = (allowFlip && lenDir < lenDirMinus&& fabsf(lenDir - lenDirMinus) > FLT_EPSILON) ? -1.f : 1.f;\n         float mulAxisX = (allowFlip && lenDirPlaneX < lenDirMinusPlaneX&& fabsf(lenDirPlaneX - lenDirMinusPlaneX) > FLT_EPSILON) ? -1.f : 1.f;\n         float mulAxisY = (allowFlip && lenDirPlaneY < lenDirMinusPlaneY&& fabsf(lenDirPlaneY - lenDirMinusPlaneY) > FLT_EPSILON) ? -1.f : 1.f;\n         dirAxis *= mulAxis;\n         dirPlaneX *= mulAxisX;\n         dirPlaneY *= mulAxisY;\n\n         // for axis\n         float axisLengthInClipSpace = GetSegmentLengthClipSpace(makeVect(0.f, 0.f, 0.f), dirAxis * gContext.mScreenFactor, localCoordinates);\n\n         float paraSurf = GetParallelogram(makeVect(0.f, 0.f, 0.f), dirPlaneX * gContext.mScreenFactor, dirPlaneY * gContext.mScreenFactor);\n         belowPlaneLimit = (paraSurf > 0.0025f);\n         belowAxisLimit = (axisLengthInClipSpace > 0.02f);\n\n         // and store values\n         gContext.mAxisFactor[axisIndex] = mulAxis;\n         gContext.mAxisFactor[(axisIndex + 1) % 3] = mulAxisX;\n         gContext.mAxisFactor[(axisIndex + 2) % 3] = mulAxisY;\n         gContext.mBelowAxisLimit[axisIndex] = belowAxisLimit;\n         gContext.mBelowPlaneLimit[axisIndex] = belowPlaneLimit;\n      }\n   }\n\n   static void ComputeSnap(float* value, float snap)\n   {\n      if (snap <= FLT_EPSILON)\n      {\n         return;\n      }\n\n      float modulo = fmodf(*value, snap);\n      float moduloRatio = fabsf(modulo) / snap;\n      if (moduloRatio < snapTension)\n      {\n         *value -= modulo;\n      }\n      else if (moduloRatio > (1.f - snapTension))\n      {\n         *value = *value - modulo + snap * ((*value < 0.f) ? -1.f : 1.f);\n      }\n   }\n   static void ComputeSnap(vec_t& value, const float* snap)\n   {\n      for (int i = 0; i < 3; i++)\n      {\n         ComputeSnap(&value[i], snap[i]);\n      }\n   }\n\n   static float ComputeAngleOnPlan()\n   {\n      const float len = IntersectRayPlane(gContext.mRayOrigin, gContext.mRayVector, gContext.mTranslationPlan);\n      vec_t localPos = Normalized(gContext.mRayOrigin + gContext.mRayVector * len - gContext.mModel.v.position);\n\n      vec_t perpendicularVector;\n      perpendicularVector.Cross(gContext.mRotationVectorSource, gContext.mTranslationPlan);\n      perpendicularVector.Normalize();\n      float acosAngle = Clamp(Dot(localPos, gContext.mRotationVectorSource), -1.f, 1.f);\n      float angle = acosf(acosAngle);\n      angle *= (Dot(localPos, perpendicularVector) < 0.f) ? 1.f : -1.f;\n      return angle;\n   }\n\n   static void DrawRotationGizmo(OPERATION op, int type)\n   {\n      if(!Intersects(op, ROTATE))\n      {\n         return;\n      }\n      ImDrawList* drawList = gContext.mDrawList;\n\n      // colors\n      ImU32 colors[7];\n      ComputeColors(colors, type, ROTATE);\n\n      vec_t cameraToModelNormalized;\n      if (gContext.mIsOrthographic)\n      {\n         matrix_t viewInverse;\n         viewInverse.Inverse(*(matrix_t*)&gContext.mViewMat);\n         cameraToModelNormalized = viewInverse.v.dir;\n      }\n      else\n      {\n         cameraToModelNormalized = Normalized(gContext.mModel.v.position - gContext.mCameraEye);\n      }\n\n      cameraToModelNormalized.TransformVector(gContext.mModelInverse);\n\n      gContext.mRadiusSquareCenter = screenRotateSize * gContext.mHeight;\n\n      bool hasRSC = Intersects(op, ROTATE_SCREEN);\n      for (int axis = 0; axis < 3; axis++)\n      {\n         if(!Intersects(op, static_cast<OPERATION>(ROTATE_Z >> axis)))\n         {\n            continue;\n         }\n         const bool usingAxis = (gContext.mbUsing && type == MT_ROTATE_Z - axis);\n         const int circleMul = (hasRSC && !usingAxis ) ? 1 : 2;\n         \n         ImVec2* circlePos = (ImVec2*)alloca(sizeof(ImVec2) * (circleMul * halfCircleSegmentCount + 1));\n\n         float angleStart = atan2f(cameraToModelNormalized[(4 - axis) % 3], cameraToModelNormalized[(3 - axis) % 3]) + ZPI * 0.5f;\n\n         for (int i = 0; i < circleMul * halfCircleSegmentCount + 1; i++)\n         {\n            float ng = angleStart + circleMul * ZPI * ((float)i / (float)halfCircleSegmentCount);\n            vec_t axisPos = makeVect(cosf(ng), sinf(ng), 0.f);\n            vec_t pos = makeVect(axisPos[axis], axisPos[(axis + 1) % 3], axisPos[(axis + 2) % 3]) * gContext.mScreenFactor * rotationDisplayFactor;\n            circlePos[i] = worldToPos(pos, gContext.mMVP);\n         }\n         if (!gContext.mbUsing || usingAxis)\n         {\n            drawList->AddPolyline(circlePos, circleMul* halfCircleSegmentCount + 1, colors[3 - axis], false, 2);\n         }\n\n         float radiusAxis = sqrtf((ImLengthSqr(worldToPos(gContext.mModel.v.position, gContext.mViewProjection) - circlePos[0])));\n         if (radiusAxis > gContext.mRadiusSquareCenter)\n         {\n            gContext.mRadiusSquareCenter = radiusAxis;\n         }\n      }\n      if(hasRSC && (!gContext.mbUsing || type == MT_ROTATE_SCREEN))\n      {\n         drawList->AddCircle(worldToPos(gContext.mModel.v.position, gContext.mViewProjection), gContext.mRadiusSquareCenter, colors[0], 64, 3.f);\n      }\n\n      if (gContext.mbUsing && (gContext.mActualID == -1 || gContext.mActualID == gContext.mEditingID) && IsRotateType(type))\n      {\n         ImVec2 circlePos[halfCircleSegmentCount + 1];\n\n         circlePos[0] = worldToPos(gContext.mModel.v.position, gContext.mViewProjection);\n         for (unsigned int i = 1; i < halfCircleSegmentCount; i++)\n         {\n            float ng = gContext.mRotationAngle * ((float)(i - 1) / (float)(halfCircleSegmentCount - 1));\n            matrix_t rotateVectorMatrix;\n            rotateVectorMatrix.RotationAxis(gContext.mTranslationPlan, ng);\n            vec_t pos;\n            pos.TransformPoint(gContext.mRotationVectorSource, rotateVectorMatrix);\n            pos *= gContext.mScreenFactor * rotationDisplayFactor;\n            circlePos[i] = worldToPos(pos + gContext.mModel.v.position, gContext.mViewProjection);\n         }\n         drawList->AddConvexPolyFilled(circlePos, halfCircleSegmentCount, IM_COL32(0xFF, 0x80, 0x10, 0x80));\n         drawList->AddPolyline(circlePos, halfCircleSegmentCount, IM_COL32(0xFF, 0x80, 0x10, 0xFF), true, 2);\n\n         ImVec2 destinationPosOnScreen = circlePos[1];\n         char tmps[512];\n         ImFormatString(tmps, sizeof(tmps), rotationInfoMask[type - MT_ROTATE_X], (gContext.mRotationAngle / ZPI) * 180.f, gContext.mRotationAngle);\n         drawList->AddText(ImVec2(destinationPosOnScreen.x + 15, destinationPosOnScreen.y + 15), IM_COL32_BLACK, tmps);\n         drawList->AddText(ImVec2(destinationPosOnScreen.x + 14, destinationPosOnScreen.y + 14), IM_COL32_WHITE, tmps);\n      }\n   }\n\n   static void DrawHatchedAxis(const vec_t& axis)\n   {\n      for (int j = 1; j < 10; j++)\n      {\n         ImVec2 baseSSpace2 = worldToPos(axis * 0.05f * (float)(j * 2) * gContext.mScreenFactor, gContext.mMVP);\n         ImVec2 worldDirSSpace2 = worldToPos(axis * 0.05f * (float)(j * 2 + 1) * gContext.mScreenFactor, gContext.mMVP);\n         gContext.mDrawList->AddLine(baseSSpace2, worldDirSSpace2, IM_COL32(0, 0, 0, 0x80), 6.f);\n      }\n   }\n\n   static void DrawScaleGizmo(OPERATION op, int type)\n   {\n      ImDrawList* drawList = gContext.mDrawList;\n\n      if(!Intersects(op, SCALE))\n      {\n        return;\n      }\n\n      // colors\n      ImU32 colors[7];\n      ComputeColors(colors, type, SCALE);\n\n      // draw\n      vec_t scaleDisplay = { 1.f, 1.f, 1.f, 1.f };\n\n      if (gContext.mbUsing && (gContext.mActualID == -1 || gContext.mActualID == gContext.mEditingID))\n      {\n         scaleDisplay = gContext.mScale;\n      }\n\n      for (unsigned int i = 0; i < 3; i++)\n      {\n         if(!Intersects(op, static_cast<OPERATION>(SCALE_X << i)))\n         {\n            continue;\n         }\n         const bool usingAxis = (gContext.mbUsing && type == MT_SCALE_X + i);\n         if (!gContext.mbUsing || usingAxis)\n         {\n            vec_t dirPlaneX, dirPlaneY, dirAxis;\n            bool belowAxisLimit, belowPlaneLimit;\n            ComputeTripodAxisAndVisibility(i, dirAxis, dirPlaneX, dirPlaneY, belowAxisLimit, belowPlaneLimit, true);\n\n            // draw axis\n            if (belowAxisLimit)\n            {\n               bool hasTranslateOnAxis = Contains(op, static_cast<OPERATION>(TRANSLATE_X << i));\n               float markerScale = hasTranslateOnAxis ? 1.4f : 1.0f;\n               ImVec2 baseSSpace = worldToPos(dirAxis * 0.1f * gContext.mScreenFactor, gContext.mMVP);\n               ImVec2 worldDirSSpaceNoScale = worldToPos(dirAxis * markerScale * gContext.mScreenFactor, gContext.mMVP);\n               ImVec2 worldDirSSpace = worldToPos((dirAxis * markerScale * scaleDisplay[i]) * gContext.mScreenFactor, gContext.mMVP);\n\n               if (gContext.mbUsing && (gContext.mActualID == -1 || gContext.mActualID == gContext.mEditingID))\n               {\n                  drawList->AddLine(baseSSpace, worldDirSSpaceNoScale, IM_COL32(0x40, 0x40, 0x40, 0xFF), 3.f);\n                  drawList->AddCircleFilled(worldDirSSpaceNoScale, 6.f, IM_COL32(0x40, 0x40, 0x40, 0xFF));\n               }\n\n               if (!hasTranslateOnAxis || gContext.mbUsing)\n               {\n                  drawList->AddLine(baseSSpace, worldDirSSpace, colors[i + 1], 3.f);\n               }\n               drawList->AddCircleFilled(worldDirSSpace, 6.f, colors[i + 1]);\n\n               if (gContext.mAxisFactor[i] < 0.f)\n               {\n                  DrawHatchedAxis(dirAxis * scaleDisplay[i]);\n               }\n            }\n         }\n      }\n\n      // draw screen cirle\n      drawList->AddCircleFilled(gContext.mScreenSquareCenter, 6.f, colors[0], 32);\n\n      if (gContext.mbUsing && (gContext.mActualID == -1 || gContext.mActualID == gContext.mEditingID) && IsScaleType(type))\n      {\n         //ImVec2 sourcePosOnScreen = worldToPos(gContext.mMatrixOrigin, gContext.mViewProjection);\n         ImVec2 destinationPosOnScreen = worldToPos(gContext.mModel.v.position, gContext.mViewProjection);\n         /*vec_t dif(destinationPosOnScreen.x - sourcePosOnScreen.x, destinationPosOnScreen.y - sourcePosOnScreen.y);\n         dif.Normalize();\n         dif *= 5.f;\n         drawList->AddCircle(sourcePosOnScreen, 6.f, translationLineColor);\n         drawList->AddCircle(destinationPosOnScreen, 6.f, translationLineColor);\n         drawList->AddLine(ImVec2(sourcePosOnScreen.x + dif.x, sourcePosOnScreen.y + dif.y), ImVec2(destinationPosOnScreen.x - dif.x, destinationPosOnScreen.y - dif.y), translationLineColor, 2.f);\n         */\n         char tmps[512];\n         //vec_t deltaInfo = gContext.mModel.v.position - gContext.mMatrixOrigin;\n         int componentInfoIndex = (type - MT_SCALE_X) * 3;\n         ImFormatString(tmps, sizeof(tmps), scaleInfoMask[type - MT_SCALE_X], scaleDisplay[translationInfoIndex[componentInfoIndex]]);\n         drawList->AddText(ImVec2(destinationPosOnScreen.x + 15, destinationPosOnScreen.y + 15), IM_COL32_BLACK, tmps);\n         drawList->AddText(ImVec2(destinationPosOnScreen.x + 14, destinationPosOnScreen.y + 14), IM_COL32_WHITE, tmps);\n      }\n   }\n\n\n   static void DrawScaleUniveralGizmo(OPERATION op, int type)\n   {\n      ImDrawList* drawList = gContext.mDrawList;\n\n      if (!Intersects(op, SCALEU))\n      {\n         return;\n      }\n\n      // colors\n      ImU32 colors[7];\n      ComputeColors(colors, type, SCALEU);\n\n      // draw\n      vec_t scaleDisplay = { 1.f, 1.f, 1.f, 1.f };\n\n      if (gContext.mbUsing && (gContext.mActualID == -1 || gContext.mActualID == gContext.mEditingID))\n      {\n         scaleDisplay = gContext.mScale;\n      }\n\n      for (unsigned int i = 0; i < 3; i++)\n      {\n         if (!Intersects(op, static_cast<OPERATION>(SCALE_XU << i)))\n         {\n            continue;\n         }\n         const bool usingAxis = (gContext.mbUsing && type == MT_SCALE_X + i);\n         if (!gContext.mbUsing || usingAxis)\n         {\n            vec_t dirPlaneX, dirPlaneY, dirAxis;\n            bool belowAxisLimit, belowPlaneLimit;\n            ComputeTripodAxisAndVisibility(i, dirAxis, dirPlaneX, dirPlaneY, belowAxisLimit, belowPlaneLimit, true);\n\n            // draw axis\n            if (belowAxisLimit)\n            {\n               bool hasTranslateOnAxis = Contains(op, static_cast<OPERATION>(TRANSLATE_X << i));\n               float markerScale = hasTranslateOnAxis ? 1.4f : 1.0f;\n               ImVec2 baseSSpace = worldToPos(dirAxis * 0.1f * gContext.mScreenFactor, gContext.mMVPLocal);\n               //ImVec2 worldDirSSpaceNoScale = worldToPos(dirAxis * markerScale * gContext.mScreenFactor, gContext.mMVP);\n               ImVec2 worldDirSSpace = worldToPos((dirAxis * markerScale * scaleDisplay[i]) * gContext.mScreenFactor, gContext.mMVPLocal);\n\n               /*if (gContext.mbUsing && (gContext.mActualID == -1 || gContext.mActualID == gContext.mEditingID))\n               {\n                  drawList->AddLine(baseSSpace, worldDirSSpaceNoScale, IM_COL32(0x40, 0x40, 0x40, 0xFF), 3.f);\n                  drawList->AddCircleFilled(worldDirSSpaceNoScale, 6.f, IM_COL32(0x40, 0x40, 0x40, 0xFF));\n               }\n               /*\n               if (!hasTranslateOnAxis || gContext.mbUsing)\n               {\n                  drawList->AddLine(baseSSpace, worldDirSSpace, colors[i + 1], 3.f);\n               }\n               */\n               drawList->AddCircleFilled(worldDirSSpace, 12.f, colors[i + 1]);\n            }\n         }\n      }\n\n      // draw screen cirle\n      drawList->AddCircle(gContext.mScreenSquareCenter, 20.f, colors[0], 32, 3.f);\n\n      if (gContext.mbUsing && (gContext.mActualID == -1 || gContext.mActualID == gContext.mEditingID) && IsScaleType(type))\n      {\n         //ImVec2 sourcePosOnScreen = worldToPos(gContext.mMatrixOrigin, gContext.mViewProjection);\n         ImVec2 destinationPosOnScreen = worldToPos(gContext.mModel.v.position, gContext.mViewProjection);\n         /*vec_t dif(destinationPosOnScreen.x - sourcePosOnScreen.x, destinationPosOnScreen.y - sourcePosOnScreen.y);\n         dif.Normalize();\n         dif *= 5.f;\n         drawList->AddCircle(sourcePosOnScreen, 6.f, translationLineColor);\n         drawList->AddCircle(destinationPosOnScreen, 6.f, translationLineColor);\n         drawList->AddLine(ImVec2(sourcePosOnScreen.x + dif.x, sourcePosOnScreen.y + dif.y), ImVec2(destinationPosOnScreen.x - dif.x, destinationPosOnScreen.y - dif.y), translationLineColor, 2.f);\n         */\n         char tmps[512];\n         //vec_t deltaInfo = gContext.mModel.v.position - gContext.mMatrixOrigin;\n         int componentInfoIndex = (type - MT_SCALE_X) * 3;\n         ImFormatString(tmps, sizeof(tmps), scaleInfoMask[type - MT_SCALE_X], scaleDisplay[translationInfoIndex[componentInfoIndex]]);\n         drawList->AddText(ImVec2(destinationPosOnScreen.x + 15, destinationPosOnScreen.y + 15), IM_COL32_BLACK, tmps);\n         drawList->AddText(ImVec2(destinationPosOnScreen.x + 14, destinationPosOnScreen.y + 14), IM_COL32_WHITE, tmps);\n      }\n   }\n\n   static void DrawTranslationGizmo(OPERATION op, int type)\n   {\n      ImDrawList* drawList = gContext.mDrawList;\n      if (!drawList)\n      {\n         return;\n      }\n\n      if(!Intersects(op, TRANSLATE))\n      {\n         return;\n      }\n\n      // colors\n      ImU32 colors[7];\n      ComputeColors(colors, type, TRANSLATE);\n\n      const ImVec2 origin = worldToPos(gContext.mModel.v.position, gContext.mViewProjection);\n\n      // draw\n      bool belowAxisLimit = false;\n      bool belowPlaneLimit = false;\n      for (unsigned int i = 0; i < 3; ++i)\n      {\n         vec_t dirPlaneX, dirPlaneY, dirAxis;\n         ComputeTripodAxisAndVisibility(i, dirAxis, dirPlaneX, dirPlaneY, belowAxisLimit, belowPlaneLimit);\n\n         if (!gContext.mbUsing || (gContext.mbUsing && type == MT_MOVE_X + i))\n         {\n            // draw axis\n            if (belowAxisLimit && Intersects(op, static_cast<OPERATION>(TRANSLATE_X << i)))\n            {\n               ImVec2 baseSSpace = worldToPos(dirAxis * 0.1f * gContext.mScreenFactor, gContext.mMVP);\n               ImVec2 worldDirSSpace = worldToPos(dirAxis * gContext.mScreenFactor, gContext.mMVP);\n\n               drawList->AddLine(baseSSpace, worldDirSSpace, colors[i + 1], 3.f);\n\n               // Arrow head begin\n               ImVec2 dir(origin - worldDirSSpace);\n\n               float d = sqrtf(ImLengthSqr(dir));\n               dir /= d; // Normalize\n               dir *= 6.0f;\n\n               ImVec2 ortogonalDir(dir.y, -dir.x); // Perpendicular vector\n               ImVec2 a(worldDirSSpace + dir);\n               drawList->AddTriangleFilled(worldDirSSpace - dir, a + ortogonalDir, a - ortogonalDir, colors[i + 1]);\n               // Arrow head end\n\n               if (gContext.mAxisFactor[i] < 0.f)\n               {\n                  DrawHatchedAxis(dirAxis);\n               }\n            }\n         }\n         // draw plane\n         if (!gContext.mbUsing || (gContext.mbUsing && type == MT_MOVE_YZ + i))\n         {\n            if (belowPlaneLimit && Contains(op, TRANSLATE_PLANS[i]))\n            {\n               ImVec2 screenQuadPts[4];\n               for (int j = 0; j < 4; ++j)\n               {\n                  vec_t cornerWorldPos = (dirPlaneX * quadUV[j * 2] + dirPlaneY * quadUV[j * 2 + 1]) * gContext.mScreenFactor;\n                  screenQuadPts[j] = worldToPos(cornerWorldPos, gContext.mMVP);\n               }\n               drawList->AddPolyline(screenQuadPts, 4, directionColor[i], true, 1.0f);\n               drawList->AddConvexPolyFilled(screenQuadPts, 4, colors[i + 4]);\n            }\n         }\n      }\n\n      drawList->AddCircleFilled(gContext.mScreenSquareCenter, 6.f, colors[0], 32);\n\n      if (gContext.mbUsing && (gContext.mActualID == -1 || gContext.mActualID == gContext.mEditingID) && IsTranslateType(type))\n      {\n         ImVec2 sourcePosOnScreen = worldToPos(gContext.mMatrixOrigin, gContext.mViewProjection);\n         ImVec2 destinationPosOnScreen = worldToPos(gContext.mModel.v.position, gContext.mViewProjection);\n         vec_t dif = { destinationPosOnScreen.x - sourcePosOnScreen.x, destinationPosOnScreen.y - sourcePosOnScreen.y, 0.f, 0.f };\n         dif.Normalize();\n         dif *= 5.f;\n         drawList->AddCircle(sourcePosOnScreen, 6.f, translationLineColor);\n         drawList->AddCircle(destinationPosOnScreen, 6.f, translationLineColor);\n         drawList->AddLine(ImVec2(sourcePosOnScreen.x + dif.x, sourcePosOnScreen.y + dif.y), ImVec2(destinationPosOnScreen.x - dif.x, destinationPosOnScreen.y - dif.y), translationLineColor, 2.f);\n\n         char tmps[512];\n         vec_t deltaInfo = gContext.mModel.v.position - gContext.mMatrixOrigin;\n         int componentInfoIndex = (type - MT_MOVE_X) * 3;\n         ImFormatString(tmps, sizeof(tmps), translationInfoMask[type - MT_MOVE_X], deltaInfo[translationInfoIndex[componentInfoIndex]], deltaInfo[translationInfoIndex[componentInfoIndex + 1]], deltaInfo[translationInfoIndex[componentInfoIndex + 2]]);\n         drawList->AddText(ImVec2(destinationPosOnScreen.x + 15, destinationPosOnScreen.y + 15), IM_COL32_BLACK, tmps);\n         drawList->AddText(ImVec2(destinationPosOnScreen.x + 14, destinationPosOnScreen.y + 14), IM_COL32_WHITE, tmps);\n      }\n   }\n\n   static bool CanActivate()\n   {\n      if (ImGui::IsMouseClicked(0) && !ImGui::IsAnyItemHovered() && !ImGui::IsAnyItemActive())\n      {\n         return true;\n      }\n      return false;\n   }\n\n   static void HandleAndDrawLocalBounds(const float* bounds, matrix_t* matrix, const float* snapValues, OPERATION operation)\n   {\n      ImGuiIO& io = ImGui::GetIO();\n      ImDrawList* drawList = gContext.mDrawList;\n\n      // compute best projection axis\n      vec_t axesWorldDirections[3];\n      vec_t bestAxisWorldDirection = { 0.0f, 0.0f, 0.0f, 0.0f };\n      int axes[3];\n      unsigned int numAxes = 1;\n      axes[0] = gContext.mBoundsBestAxis;\n      int bestAxis = axes[0];\n      if (!gContext.mbUsingBounds)\n      {\n         numAxes = 0;\n         float bestDot = 0.f;\n         for (unsigned int i = 0; i < 3; i++)\n         {\n            vec_t dirPlaneNormalWorld;\n            dirPlaneNormalWorld.TransformVector(directionUnary[i], gContext.mModelSource);\n            dirPlaneNormalWorld.Normalize();\n\n            float dt = fabsf(Dot(Normalized(gContext.mCameraEye - gContext.mModelSource.v.position), dirPlaneNormalWorld));\n            if (dt >= bestDot)\n            {\n               bestDot = dt;\n               bestAxis = i;\n               bestAxisWorldDirection = dirPlaneNormalWorld;\n            }\n\n            if (dt >= 0.1f)\n            {\n               axes[numAxes] = i;\n               axesWorldDirections[numAxes] = dirPlaneNormalWorld;\n               ++numAxes;\n            }\n         }\n      }\n\n      if (numAxes == 0)\n      {\n         axes[0] = bestAxis;\n         axesWorldDirections[0] = bestAxisWorldDirection;\n         numAxes = 1;\n      }\n\n      else if (bestAxis != axes[0])\n      {\n         unsigned int bestIndex = 0;\n         for (unsigned int i = 0; i < numAxes; i++)\n         {\n            if (axes[i] == bestAxis)\n            {\n               bestIndex = i;\n               break;\n            }\n         }\n         int tempAxis = axes[0];\n         axes[0] = axes[bestIndex];\n         axes[bestIndex] = tempAxis;\n         vec_t tempDirection = axesWorldDirections[0];\n         axesWorldDirections[0] = axesWorldDirections[bestIndex];\n         axesWorldDirections[bestIndex] = tempDirection;\n      }\n\n      for (unsigned int axisIndex = 0; axisIndex < numAxes; ++axisIndex)\n      {\n         bestAxis = axes[axisIndex];\n         bestAxisWorldDirection = axesWorldDirections[axisIndex];\n\n         // corners\n         vec_t aabb[4];\n\n         int secondAxis = (bestAxis + 1) % 3;\n         int thirdAxis = (bestAxis + 2) % 3;\n\n         for (int i = 0; i < 4; i++)\n         {\n            aabb[i][3] = aabb[i][bestAxis] = 0.f;\n            aabb[i][secondAxis] = bounds[secondAxis + 3 * (i >> 1)];\n            aabb[i][thirdAxis] = bounds[thirdAxis + 3 * ((i >> 1) ^ (i & 1))];\n         }\n\n         // draw bounds\n         unsigned int anchorAlpha = gContext.mbEnable ? IM_COL32_BLACK : IM_COL32(0, 0, 0, 0x80);\n\n         matrix_t boundsMVP = gContext.mModelSource * gContext.mViewProjection;\n         for (int i = 0; i < 4; i++)\n         {\n            ImVec2 worldBound1 = worldToPos(aabb[i], boundsMVP);\n            ImVec2 worldBound2 = worldToPos(aabb[(i + 1) % 4], boundsMVP);\n            if (!IsInContextRect(worldBound1) || !IsInContextRect(worldBound2))\n            {\n               continue;\n            }\n            float boundDistance = sqrtf(ImLengthSqr(worldBound1 - worldBound2));\n            int stepCount = (int)(boundDistance / 10.f);\n            stepCount = min(stepCount, 1000);\n            float stepLength = 1.f / (float)stepCount;\n            for (int j = 0; j < stepCount; j++)\n            {\n               float t1 = (float)j * stepLength;\n               float t2 = (float)j * stepLength + stepLength * 0.5f;\n               ImVec2 worldBoundSS1 = ImLerp(worldBound1, worldBound2, ImVec2(t1, t1));\n               ImVec2 worldBoundSS2 = ImLerp(worldBound1, worldBound2, ImVec2(t2, t2));\n               //drawList->AddLine(worldBoundSS1, worldBoundSS2, IM_COL32(0, 0, 0, 0) + anchorAlpha, 3.f);\n               drawList->AddLine(worldBoundSS1, worldBoundSS2, IM_COL32(0xAA, 0xAA, 0xAA, 0) + anchorAlpha, 2.f);\n            }\n            vec_t midPoint = (aabb[i] + aabb[(i + 1) % 4]) * 0.5f;\n            ImVec2 midBound = worldToPos(midPoint, boundsMVP);\n            static const float AnchorBigRadius = 8.f;\n            static const float AnchorSmallRadius = 6.f;\n            bool overBigAnchor = ImLengthSqr(worldBound1 - io.MousePos) <= (AnchorBigRadius * AnchorBigRadius);\n            bool overSmallAnchor = ImLengthSqr(midBound - io.MousePos) <= (AnchorBigRadius * AnchorBigRadius);\n\n            int type = MT_NONE;\n            vec_t gizmoHitProportion;\n\n            if(Intersects(operation, TRANSLATE))\n            {\n               type = GetMoveType(operation, &gizmoHitProportion);\n            }\n            if(Intersects(operation, ROTATE) && type == MT_NONE)\n            {\n               type = GetRotateType(operation);\n            }\n            if(Intersects(operation, SCALE) && type == MT_NONE)\n            {\n               type = GetScaleType(operation);\n            }\n\n            if (type != MT_NONE)\n            {\n               overBigAnchor = false;\n               overSmallAnchor = false;\n            }\n\n            unsigned int bigAnchorColor = overBigAnchor ? selectionColor : (IM_COL32(0xAA, 0xAA, 0xAA, 0) + anchorAlpha);\n            unsigned int smallAnchorColor = overSmallAnchor ? selectionColor : (IM_COL32(0xAA, 0xAA, 0xAA, 0) + anchorAlpha);\n\n            drawList->AddCircleFilled(worldBound1, AnchorBigRadius, IM_COL32_BLACK);\n            drawList->AddCircleFilled(worldBound1, AnchorBigRadius - 1.2f, bigAnchorColor);\n\n            drawList->AddCircleFilled(midBound, AnchorSmallRadius, IM_COL32_BLACK);\n            drawList->AddCircleFilled(midBound, AnchorSmallRadius - 1.2f, smallAnchorColor);\n            int oppositeIndex = (i + 2) % 4;\n            // big anchor on corners\n            if (!gContext.mbUsingBounds && gContext.mbEnable && overBigAnchor && CanActivate())\n            {\n               gContext.mBoundsPivot.TransformPoint(aabb[(i + 2) % 4], gContext.mModelSource);\n               gContext.mBoundsAnchor.TransformPoint(aabb[i], gContext.mModelSource);\n               gContext.mBoundsPlan = BuildPlan(gContext.mBoundsAnchor, bestAxisWorldDirection);\n               gContext.mBoundsBestAxis = bestAxis;\n               gContext.mBoundsAxis[0] = secondAxis;\n               gContext.mBoundsAxis[1] = thirdAxis;\n\n               gContext.mBoundsLocalPivot.Set(0.f);\n               gContext.mBoundsLocalPivot[secondAxis] = aabb[oppositeIndex][secondAxis];\n               gContext.mBoundsLocalPivot[thirdAxis] = aabb[oppositeIndex][thirdAxis];\n\n               gContext.mbUsingBounds = true;\n               gContext.mEditingID = gContext.mActualID;\n               gContext.mBoundsMatrix = gContext.mModelSource;\n            }\n            // small anchor on middle of segment\n            if (!gContext.mbUsingBounds && gContext.mbEnable && overSmallAnchor && CanActivate())\n            {\n               vec_t midPointOpposite = (aabb[(i + 2) % 4] + aabb[(i + 3) % 4]) * 0.5f;\n               gContext.mBoundsPivot.TransformPoint(midPointOpposite, gContext.mModelSource);\n               gContext.mBoundsAnchor.TransformPoint(midPoint, gContext.mModelSource);\n               gContext.mBoundsPlan = BuildPlan(gContext.mBoundsAnchor, bestAxisWorldDirection);\n               gContext.mBoundsBestAxis = bestAxis;\n               int indices[] = { secondAxis , thirdAxis };\n               gContext.mBoundsAxis[0] = indices[i % 2];\n               gContext.mBoundsAxis[1] = -1;\n\n               gContext.mBoundsLocalPivot.Set(0.f);\n               gContext.mBoundsLocalPivot[gContext.mBoundsAxis[0]] = aabb[oppositeIndex][indices[i % 2]];// bounds[gContext.mBoundsAxis[0]] * (((i + 1) & 2) ? 1.f : -1.f);\n\n               gContext.mbUsingBounds = true;\n               gContext.mEditingID = gContext.mActualID;\n               gContext.mBoundsMatrix = gContext.mModelSource;\n            }\n         }\n\n         if (gContext.mbUsingBounds && (gContext.mActualID == -1 || gContext.mActualID == gContext.mEditingID))\n         {\n            matrix_t scale;\n            scale.SetToIdentity();\n\n            // compute projected mouse position on plan\n            const float len = IntersectRayPlane(gContext.mRayOrigin, gContext.mRayVector, gContext.mBoundsPlan);\n            vec_t newPos = gContext.mRayOrigin + gContext.mRayVector * len;\n\n            // compute a reference and delta vectors base on mouse move\n            vec_t deltaVector = (newPos - gContext.mBoundsPivot).Abs();\n            vec_t referenceVector = (gContext.mBoundsAnchor - gContext.mBoundsPivot).Abs();\n\n            // for 1 or 2 axes, compute a ratio that's used for scale and snap it based on resulting length\n            for (int i = 0; i < 2; i++)\n            {\n               int axisIndex1 = gContext.mBoundsAxis[i];\n               if (axisIndex1 == -1)\n               {\n                  continue;\n               }\n\n               float ratioAxis = 1.f;\n               vec_t axisDir = gContext.mBoundsMatrix.component[axisIndex1].Abs();\n\n               float dtAxis = axisDir.Dot(referenceVector);\n               float boundSize = bounds[axisIndex1 + 3] - bounds[axisIndex1];\n               if (dtAxis > FLT_EPSILON)\n               {\n                  ratioAxis = axisDir.Dot(deltaVector) / dtAxis;\n               }\n\n               if (snapValues)\n               {\n                  float length = boundSize * ratioAxis;\n                  ComputeSnap(&length, snapValues[axisIndex1]);\n                  if (boundSize > FLT_EPSILON)\n                  {\n                     ratioAxis = length / boundSize;\n                  }\n               }\n               scale.component[axisIndex1] *= ratioAxis;\n            }\n\n            // transform matrix\n            matrix_t preScale, postScale;\n            preScale.Translation(-gContext.mBoundsLocalPivot);\n            postScale.Translation(gContext.mBoundsLocalPivot);\n            matrix_t res = preScale * scale * postScale * gContext.mBoundsMatrix;\n            *matrix = res;\n\n            // info text\n            char tmps[512];\n            ImVec2 destinationPosOnScreen = worldToPos(gContext.mModel.v.position, gContext.mViewProjection);\n            ImFormatString(tmps, sizeof(tmps), \"X: %.2f Y: %.2f Z:%.2f\"\n               , (bounds[3] - bounds[0]) * gContext.mBoundsMatrix.component[0].Length() * scale.component[0].Length()\n               , (bounds[4] - bounds[1]) * gContext.mBoundsMatrix.component[1].Length() * scale.component[1].Length()\n               , (bounds[5] - bounds[2]) * gContext.mBoundsMatrix.component[2].Length() * scale.component[2].Length()\n            );\n            drawList->AddText(ImVec2(destinationPosOnScreen.x + 15, destinationPosOnScreen.y + 15), IM_COL32_BLACK, tmps);\n            drawList->AddText(ImVec2(destinationPosOnScreen.x + 14, destinationPosOnScreen.y + 14), IM_COL32_WHITE, tmps);\n         }\n\n         if (!io.MouseDown[0]) {\n            gContext.mbUsingBounds = false;\n            gContext.mEditingID = -1;\n         }\n         if (gContext.mbUsingBounds)\n         {\n            break;\n         }\n      }\n   }\n\n   ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n   //\n\n   static int GetScaleType(OPERATION op)\n   {\n      if (gContext.mbUsing)\n      {\n         return MT_NONE;\n      }\n      ImGuiIO& io = ImGui::GetIO();\n      int type = MT_NONE;\n\n      // screen\n      if (io.MousePos.x >= gContext.mScreenSquareMin.x && io.MousePos.x <= gContext.mScreenSquareMax.x &&\n         io.MousePos.y >= gContext.mScreenSquareMin.y && io.MousePos.y <= gContext.mScreenSquareMax.y &&\n         Contains(op, SCALE))\n      {\n         type = MT_SCALE_XYZ;\n      }\n\n      // compute\n      for (unsigned int i = 0; i < 3 && type == MT_NONE; i++)\n      {\n         if(!Intersects(op, static_cast<OPERATION>(SCALE_X << i)))\n         {\n            continue;\n         }\n         vec_t dirPlaneX, dirPlaneY, dirAxis;\n         bool belowAxisLimit, belowPlaneLimit;\n         ComputeTripodAxisAndVisibility(i, dirAxis, dirPlaneX, dirPlaneY, belowAxisLimit, belowPlaneLimit, true);\n         dirAxis.TransformVector(gContext.mModelLocal);\n         dirPlaneX.TransformVector(gContext.mModelLocal);\n         dirPlaneY.TransformVector(gContext.mModelLocal);\n\n         const float len = IntersectRayPlane(gContext.mRayOrigin, gContext.mRayVector, BuildPlan(gContext.mModelLocal.v.position, dirAxis));\n         vec_t posOnPlan = gContext.mRayOrigin + gContext.mRayVector * len;\n\n         const float startOffset = Contains(op, static_cast<OPERATION>(TRANSLATE_X << i)) ? 1.0f : 0.1f;\n         const float endOffset = Contains(op, static_cast<OPERATION>(TRANSLATE_X << i)) ? 1.4f : 1.0f;\n         const ImVec2 posOnPlanScreen = worldToPos(posOnPlan, gContext.mViewProjection);\n         const ImVec2 axisStartOnScreen = worldToPos(gContext.mModelLocal.v.position + dirAxis * gContext.mScreenFactor * startOffset, gContext.mViewProjection);\n         const ImVec2 axisEndOnScreen = worldToPos(gContext.mModelLocal.v.position + dirAxis * gContext.mScreenFactor * endOffset, gContext.mViewProjection);\n\n         vec_t closestPointOnAxis = PointOnSegment(makeVect(posOnPlanScreen), makeVect(axisStartOnScreen), makeVect(axisEndOnScreen));\n\n         if ((closestPointOnAxis - makeVect(posOnPlanScreen)).Length() < 12.f) // pixel size\n         {\n            type = MT_SCALE_X + i;\n         }\n      }\n\n      // universal\n\n      vec_t deltaScreen = { io.MousePos.x - gContext.mScreenSquareCenter.x, io.MousePos.y - gContext.mScreenSquareCenter.y, 0.f, 0.f };\n      float dist = deltaScreen.Length();\n      if (Contains(op, SCALEU) && dist >= 17.0f && dist < 23.0f)\n      {\n         type = MT_SCALE_XYZ;\n      }\n\n      for (unsigned int i = 0; i < 3 && type == MT_NONE; i++)\n      {\n         if (!Intersects(op, static_cast<OPERATION>(SCALE_XU << i)))\n         {\n            continue;\n         }\n\n         vec_t dirPlaneX, dirPlaneY, dirAxis;\n         bool belowAxisLimit, belowPlaneLimit;\n         ComputeTripodAxisAndVisibility(i, dirAxis, dirPlaneX, dirPlaneY, belowAxisLimit, belowPlaneLimit, true);\n\n         // draw axis\n         if (belowAxisLimit)\n         {\n            bool hasTranslateOnAxis = Contains(op, static_cast<OPERATION>(TRANSLATE_X << i));\n            float markerScale = hasTranslateOnAxis ? 1.4f : 1.0f;\n            ImVec2 baseSSpace = worldToPos(dirAxis * 0.1f * gContext.mScreenFactor, gContext.mMVPLocal);\n            //ImVec2 worldDirSSpaceNoScale = worldToPos(dirAxis * markerScale * gContext.mScreenFactor, gContext.mMVP);\n            ImVec2 worldDirSSpace = worldToPos((dirAxis * markerScale) * gContext.mScreenFactor, gContext.mMVPLocal);\n\n            float distance = sqrtf(ImLengthSqr(worldDirSSpace - io.MousePos));\n            if (distance < 12.f)\n            {\n               type = MT_SCALE_X + i;\n            }\n         }\n      }\n      return type;\n   }\n\n   static int GetRotateType(OPERATION op)\n   {\n      if (gContext.mbUsing)\n      {\n         return MT_NONE;\n      }\n      ImGuiIO& io = ImGui::GetIO();\n      int type = MT_NONE;\n\n      vec_t deltaScreen = { io.MousePos.x - gContext.mScreenSquareCenter.x, io.MousePos.y - gContext.mScreenSquareCenter.y, 0.f, 0.f };\n      float dist = deltaScreen.Length();\n      if (Intersects(op, ROTATE_SCREEN) && dist >= (gContext.mRadiusSquareCenter - 4.0f) && dist < (gContext.mRadiusSquareCenter + 4.0f))\n      {\n         type = MT_ROTATE_SCREEN;\n      }\n\n      const vec_t planNormals[] = { gContext.mModel.v.right, gContext.mModel.v.up, gContext.mModel.v.dir };\n\n      vec_t modelViewPos;\n      modelViewPos.TransformPoint(gContext.mModel.v.position, gContext.mViewMat);\n\n      for (unsigned int i = 0; i < 3 && type == MT_NONE; i++)\n      {\n         if(!Intersects(op, static_cast<OPERATION>(ROTATE_X << i)))\n         {\n            continue;\n         }\n         // pickup plan\n         vec_t pickupPlan = BuildPlan(gContext.mModel.v.position, planNormals[i]);\n\n         const float len = IntersectRayPlane(gContext.mRayOrigin, gContext.mRayVector, pickupPlan);\n         const vec_t intersectWorldPos = gContext.mRayOrigin + gContext.mRayVector * len;\n         vec_t intersectViewPos;\n         intersectViewPos.TransformPoint(intersectWorldPos, gContext.mViewMat);\n\n         if (ImAbs(modelViewPos.z) - ImAbs(intersectViewPos.z) < -FLT_EPSILON)\n         {\n            continue;\n         }\n\n         const vec_t localPos = intersectWorldPos - gContext.mModel.v.position;\n         vec_t idealPosOnCircle = Normalized(localPos);\n         idealPosOnCircle.TransformVector(gContext.mModelInverse);\n         const ImVec2 idealPosOnCircleScreen = worldToPos(idealPosOnCircle * rotationDisplayFactor * gContext.mScreenFactor, gContext.mMVP);\n\n         //gContext.mDrawList->AddCircle(idealPosOnCircleScreen, 5.f, IM_COL32_WHITE);\n         const ImVec2 distanceOnScreen = idealPosOnCircleScreen - io.MousePos;\n\n         const float distance = makeVect(distanceOnScreen).Length();\n         if (distance < 8.f) // pixel size\n         {\n            type = MT_ROTATE_X + i;\n         }\n      }\n\n      return type;\n   }\n\n   static int GetMoveType(OPERATION op, vec_t* gizmoHitProportion)\n   {\n      if(!Intersects(op, TRANSLATE) || gContext.mbUsing || !gContext.mbMouseOver)\n      {\n        return MT_NONE;\n      }\n      ImGuiIO& io = ImGui::GetIO();\n      int type = MT_NONE;\n\n      // screen\n      if (io.MousePos.x >= gContext.mScreenSquareMin.x && io.MousePos.x <= gContext.mScreenSquareMax.x &&\n         io.MousePos.y >= gContext.mScreenSquareMin.y && io.MousePos.y <= gContext.mScreenSquareMax.y &&\n         Contains(op, TRANSLATE))\n      {\n         type = MT_MOVE_SCREEN;\n      }\n\n      const vec_t screenCoord = makeVect(io.MousePos - ImVec2(gContext.mX, gContext.mY));\n\n      // compute\n      for (unsigned int i = 0; i < 3 && type == MT_NONE; i++)\n      {\n         vec_t dirPlaneX, dirPlaneY, dirAxis;\n         bool belowAxisLimit, belowPlaneLimit;\n         ComputeTripodAxisAndVisibility(i, dirAxis, dirPlaneX, dirPlaneY, belowAxisLimit, belowPlaneLimit);\n         dirAxis.TransformVector(gContext.mModel);\n         dirPlaneX.TransformVector(gContext.mModel);\n         dirPlaneY.TransformVector(gContext.mModel);\n\n         const float len = IntersectRayPlane(gContext.mRayOrigin, gContext.mRayVector, BuildPlan(gContext.mModel.v.position, dirAxis));\n         vec_t posOnPlan = gContext.mRayOrigin + gContext.mRayVector * len;\n\n         const ImVec2 axisStartOnScreen = worldToPos(gContext.mModel.v.position + dirAxis * gContext.mScreenFactor * 0.1f, gContext.mViewProjection) - ImVec2(gContext.mX, gContext.mY);\n         const ImVec2 axisEndOnScreen = worldToPos(gContext.mModel.v.position + dirAxis * gContext.mScreenFactor, gContext.mViewProjection) - ImVec2(gContext.mX, gContext.mY);\n\n         vec_t closestPointOnAxis = PointOnSegment(screenCoord, makeVect(axisStartOnScreen), makeVect(axisEndOnScreen));\n         if ((closestPointOnAxis - screenCoord).Length() < 12.f && Intersects(op, static_cast<OPERATION>(TRANSLATE_X << i))) // pixel size\n         {\n            type = MT_MOVE_X + i;\n         }\n\n         const float dx = dirPlaneX.Dot3((posOnPlan - gContext.mModel.v.position) * (1.f / gContext.mScreenFactor));\n         const float dy = dirPlaneY.Dot3((posOnPlan - gContext.mModel.v.position) * (1.f / gContext.mScreenFactor));\n         if (belowPlaneLimit && dx >= quadUV[0] && dx <= quadUV[4] && dy >= quadUV[1] && dy <= quadUV[3] && Contains(op, TRANSLATE_PLANS[i]))\n         {\n            type = MT_MOVE_YZ + i;\n         }\n\n         if (gizmoHitProportion)\n         {\n            *gizmoHitProportion = makeVect(dx, dy, 0.f);\n         }\n      }\n      return type;\n   }\n\n   static bool HandleTranslation(float* matrix, float* deltaMatrix, OPERATION op, int& type, const float* snap)\n   {\n      if(!Intersects(op, TRANSLATE) || type != MT_NONE)\n      {\n        return false;\n      }\n      const ImGuiIO& io = ImGui::GetIO();\n      const bool applyRotationLocaly = gContext.mMode == LOCAL || type == MT_MOVE_SCREEN;\n      bool modified = false;\n\n      // move\n      if (gContext.mbUsing && (gContext.mActualID == -1 || gContext.mActualID == gContext.mEditingID) && IsTranslateType(gContext.mCurrentOperation))\n      {\n         ImGui::CaptureMouseFromApp();\n         const float signedLength = IntersectRayPlane(gContext.mRayOrigin, gContext.mRayVector, gContext.mTranslationPlan);\n         const float len = fabsf(signedLength); // near plan\n         const vec_t newPos = gContext.mRayOrigin + gContext.mRayVector * len;\n\n         // compute delta\n         const vec_t newOrigin = newPos - gContext.mRelativeOrigin * gContext.mScreenFactor;\n         vec_t delta = newOrigin - gContext.mModel.v.position;\n\n         // 1 axis constraint\n         if (gContext.mCurrentOperation >= MT_MOVE_X && gContext.mCurrentOperation <= MT_MOVE_Z)\n         {\n            const int axisIndex = gContext.mCurrentOperation - MT_MOVE_X;\n            const vec_t& axisValue = *(vec_t*)&gContext.mModel.m[axisIndex];\n            const float lengthOnAxis = Dot(axisValue, delta);\n            delta = axisValue * lengthOnAxis;\n         }\n\n         // snap\n         if (snap)\n         {\n            vec_t cumulativeDelta = gContext.mModel.v.position + delta - gContext.mMatrixOrigin;\n            if (applyRotationLocaly)\n            {\n               matrix_t modelSourceNormalized = gContext.mModelSource;\n               modelSourceNormalized.OrthoNormalize();\n               matrix_t modelSourceNormalizedInverse;\n               modelSourceNormalizedInverse.Inverse(modelSourceNormalized);\n               cumulativeDelta.TransformVector(modelSourceNormalizedInverse);\n               ComputeSnap(cumulativeDelta, snap);\n               cumulativeDelta.TransformVector(modelSourceNormalized);\n            }\n            else\n            {\n               ComputeSnap(cumulativeDelta, snap);\n            }\n            delta = gContext.mMatrixOrigin + cumulativeDelta - gContext.mModel.v.position;\n\n         }\n\n         if (delta != gContext.mTranslationLastDelta)\n         {\n            modified = true;\n         }\n         gContext.mTranslationLastDelta = delta;\n\n         // compute matrix & delta\n         matrix_t deltaMatrixTranslation;\n         deltaMatrixTranslation.Translation(delta);\n         if (deltaMatrix)\n         {\n            memcpy(deltaMatrix, deltaMatrixTranslation.m16, sizeof(float) * 16);\n         }\n\n         const matrix_t res = gContext.mModelSource * deltaMatrixTranslation;\n         *(matrix_t*)matrix = res;\n\n         if (!io.MouseDown[0])\n         {\n            gContext.mbUsing = false;\n         }\n\n         type = gContext.mCurrentOperation;\n      }\n      else\n      {\n         // find new possible way to move\n         vec_t gizmoHitProportion;\n         type = GetMoveType(op, &gizmoHitProportion);\n         if (type != MT_NONE)\n         {\n            ImGui::CaptureMouseFromApp();\n         }\n         if (CanActivate() && type != MT_NONE)\n         {\n            gContext.mbUsing = true;\n            gContext.mEditingID = gContext.mActualID;\n            gContext.mCurrentOperation = type;\n            vec_t movePlanNormal[] = { gContext.mModel.v.right, gContext.mModel.v.up, gContext.mModel.v.dir,\n               gContext.mModel.v.right, gContext.mModel.v.up, gContext.mModel.v.dir,\n               -gContext.mCameraDir };\n\n            vec_t cameraToModelNormalized = Normalized(gContext.mModel.v.position - gContext.mCameraEye);\n            for (unsigned int i = 0; i < 3; i++)\n            {\n               vec_t orthoVector = Cross(movePlanNormal[i], cameraToModelNormalized);\n               movePlanNormal[i].Cross(orthoVector);\n               movePlanNormal[i].Normalize();\n            }\n            // pickup plan\n            gContext.mTranslationPlan = BuildPlan(gContext.mModel.v.position, movePlanNormal[type - MT_MOVE_X]);\n            const float len = IntersectRayPlane(gContext.mRayOrigin, gContext.mRayVector, gContext.mTranslationPlan);\n            gContext.mTranslationPlanOrigin = gContext.mRayOrigin + gContext.mRayVector * len;\n            gContext.mMatrixOrigin = gContext.mModel.v.position;\n\n            gContext.mRelativeOrigin = (gContext.mTranslationPlanOrigin - gContext.mModel.v.position) * (1.f / gContext.mScreenFactor);\n         }\n      }\n      return modified;\n   }\n\n   static bool HandleScale(float* matrix, float* deltaMatrix, OPERATION op, int& type, const float* snap)\n   {\n      if((!Intersects(op, SCALE) && !Intersects(op, SCALEU)) || type != MT_NONE || !gContext.mbMouseOver)\n      {\n         return false;\n      }\n      ImGuiIO& io = ImGui::GetIO();\n      bool modified = false;\n\n      if (!gContext.mbUsing)\n      {\n         // find new possible way to scale\n         type = GetScaleType(op);\n         if (type != MT_NONE)\n         {\n            ImGui::CaptureMouseFromApp();\n         }\n         if (CanActivate() && type != MT_NONE)\n         {\n            gContext.mbUsing = true;\n            gContext.mEditingID = gContext.mActualID;\n            gContext.mCurrentOperation = type;\n            const vec_t movePlanNormal[] = { gContext.mModel.v.up, gContext.mModel.v.dir, gContext.mModel.v.right, gContext.mModel.v.dir, gContext.mModel.v.up, gContext.mModel.v.right, -gContext.mCameraDir };\n            // pickup plan\n\n            gContext.mTranslationPlan = BuildPlan(gContext.mModel.v.position, movePlanNormal[type - MT_SCALE_X]);\n            const float len = IntersectRayPlane(gContext.mRayOrigin, gContext.mRayVector, gContext.mTranslationPlan);\n            gContext.mTranslationPlanOrigin = gContext.mRayOrigin + gContext.mRayVector * len;\n            gContext.mMatrixOrigin = gContext.mModel.v.position;\n            gContext.mScale.Set(1.f, 1.f, 1.f);\n            gContext.mRelativeOrigin = (gContext.mTranslationPlanOrigin - gContext.mModel.v.position) * (1.f / gContext.mScreenFactor);\n            gContext.mScaleValueOrigin = makeVect(gContext.mModelSource.v.right.Length(), gContext.mModelSource.v.up.Length(), gContext.mModelSource.v.dir.Length());\n            gContext.mSaveMousePosx = io.MousePos.x;\n         }\n      }\n      // scale\n      if (gContext.mbUsing && (gContext.mActualID == -1 || gContext.mActualID == gContext.mEditingID) && IsScaleType(gContext.mCurrentOperation))\n      {\n         ImGui::CaptureMouseFromApp();\n         const float len = IntersectRayPlane(gContext.mRayOrigin, gContext.mRayVector, gContext.mTranslationPlan);\n         vec_t newPos = gContext.mRayOrigin + gContext.mRayVector * len;\n         vec_t newOrigin = newPos - gContext.mRelativeOrigin * gContext.mScreenFactor;\n         vec_t delta = newOrigin - gContext.mModelLocal.v.position;\n\n         // 1 axis constraint\n         if (gContext.mCurrentOperation >= MT_SCALE_X && gContext.mCurrentOperation <= MT_SCALE_Z)\n         {\n            int axisIndex = gContext.mCurrentOperation - MT_SCALE_X;\n            const vec_t& axisValue = *(vec_t*)&gContext.mModelLocal.m[axisIndex];\n            float lengthOnAxis = Dot(axisValue, delta);\n            delta = axisValue * lengthOnAxis;\n\n            vec_t baseVector = gContext.mTranslationPlanOrigin - gContext.mModelLocal.v.position;\n            float ratio = Dot(axisValue, baseVector + delta) / Dot(axisValue, baseVector);\n\n            gContext.mScale[axisIndex] = max(ratio, 0.001f);\n         }\n         else\n         {\n            float scaleDelta = (io.MousePos.x - gContext.mSaveMousePosx) * 0.01f;\n            gContext.mScale.Set(max(1.f + scaleDelta, 0.001f));\n         }\n\n         // snap\n         if (snap)\n         {\n            float scaleSnap[] = { snap[0], snap[0], snap[0] };\n            ComputeSnap(gContext.mScale, scaleSnap);\n         }\n\n         // no 0 allowed\n         for (int i = 0; i < 3; i++)\n            gContext.mScale[i] = max(gContext.mScale[i], 0.001f);\n\n         if (gContext.mScaleLast != gContext.mScale)\n         {\n            modified = true;\n         }\n         gContext.mScaleLast = gContext.mScale;\n\n         // compute matrix & delta\n         matrix_t deltaMatrixScale;\n         deltaMatrixScale.Scale(gContext.mScale * gContext.mScaleValueOrigin);\n\n         matrix_t res = deltaMatrixScale * gContext.mModelLocal;\n         *(matrix_t*)matrix = res;\n\n         if (deltaMatrix)\n         {\n            vec_t deltaScale = gContext.mScale * gContext.mScaleValueOrigin;\n\n            vec_t originalScaleDivider;\n            originalScaleDivider.x = 1 / gContext.mModelScaleOrigin.x;\n            originalScaleDivider.y = 1 / gContext.mModelScaleOrigin.y;\n            originalScaleDivider.z = 1 / gContext.mModelScaleOrigin.z;\n\n            deltaScale = deltaScale * originalScaleDivider;\n\n            deltaMatrixScale.Scale(deltaScale);\n            memcpy(deltaMatrix, deltaMatrixScale.m16, sizeof(float) * 16);\n         }\n\n         if (!io.MouseDown[0])\n         {\n            gContext.mbUsing = false;\n            gContext.mScale.Set(1.f, 1.f, 1.f);\n         }\n\n         type = gContext.mCurrentOperation;\n      }\n      return modified;\n   }\n\n   static bool HandleRotation(float* matrix, float* deltaMatrix, OPERATION op, int& type, const float* snap)\n   {\n      if(!Intersects(op, ROTATE) || type != MT_NONE || !gContext.mbMouseOver)\n      {\n        return false;\n      }\n      ImGuiIO& io = ImGui::GetIO();\n      bool applyRotationLocaly = gContext.mMode == LOCAL;\n      bool modified = false;\n\n      if (!gContext.mbUsing)\n      {\n         type = GetRotateType(op);\n\n         if (type != MT_NONE)\n         {\n            ImGui::CaptureMouseFromApp();\n         }\n\n         if (type == MT_ROTATE_SCREEN)\n         {\n            applyRotationLocaly = true;\n         }\n\n         if (CanActivate() && type != MT_NONE)\n         {\n            gContext.mbUsing = true;\n            gContext.mEditingID = gContext.mActualID;\n            gContext.mCurrentOperation = type;\n            const vec_t rotatePlanNormal[] = { gContext.mModel.v.right, gContext.mModel.v.up, gContext.mModel.v.dir, -gContext.mCameraDir };\n            // pickup plan\n            if (applyRotationLocaly)\n            {\n               gContext.mTranslationPlan = BuildPlan(gContext.mModel.v.position, rotatePlanNormal[type - MT_ROTATE_X]);\n            }\n            else\n            {\n               gContext.mTranslationPlan = BuildPlan(gContext.mModelSource.v.position, directionUnary[type - MT_ROTATE_X]);\n            }\n\n            const float len = IntersectRayPlane(gContext.mRayOrigin, gContext.mRayVector, gContext.mTranslationPlan);\n            vec_t localPos = gContext.mRayOrigin + gContext.mRayVector * len - gContext.mModel.v.position;\n            gContext.mRotationVectorSource = Normalized(localPos);\n            gContext.mRotationAngleOrigin = ComputeAngleOnPlan();\n         }\n      }\n\n      // rotation\n      if (gContext.mbUsing && (gContext.mActualID == -1 || gContext.mActualID == gContext.mEditingID) && IsRotateType(gContext.mCurrentOperation))\n      {\n         ImGui::CaptureMouseFromApp();\n         gContext.mRotationAngle = ComputeAngleOnPlan();\n         if (snap)\n         {\n            float snapInRadian = snap[0] * DEG2RAD;\n            ComputeSnap(&gContext.mRotationAngle, snapInRadian);\n         }\n         vec_t rotationAxisLocalSpace;\n\n         rotationAxisLocalSpace.TransformVector(makeVect(gContext.mTranslationPlan.x, gContext.mTranslationPlan.y, gContext.mTranslationPlan.z, 0.f), gContext.mModelInverse);\n         rotationAxisLocalSpace.Normalize();\n\n         matrix_t deltaRotation;\n         deltaRotation.RotationAxis(rotationAxisLocalSpace, gContext.mRotationAngle - gContext.mRotationAngleOrigin);\n         if (gContext.mRotationAngle != gContext.mRotationAngleOrigin)\n         {\n            modified = true;\n         }\n         gContext.mRotationAngleOrigin = gContext.mRotationAngle;\n\n         matrix_t scaleOrigin;\n         scaleOrigin.Scale(gContext.mModelScaleOrigin);\n\n         if (applyRotationLocaly)\n         {\n            *(matrix_t*)matrix = scaleOrigin * deltaRotation * gContext.mModelLocal;\n         }\n         else\n         {\n            matrix_t res = gContext.mModelSource;\n            res.v.position.Set(0.f);\n\n            *(matrix_t*)matrix = res * deltaRotation;\n            ((matrix_t*)matrix)->v.position = gContext.mModelSource.v.position;\n         }\n\n         if (deltaMatrix)\n         {\n            *(matrix_t*)deltaMatrix = gContext.mModelInverse * deltaRotation * gContext.mModel;\n         }\n\n         if (!io.MouseDown[0])\n         {\n            gContext.mbUsing = false;\n            gContext.mEditingID = -1;\n         }\n         type = gContext.mCurrentOperation;\n      }\n      return modified;\n   }\n\n   void DecomposeMatrixToComponents(const float* matrix, float* translation, float* rotation, float* scale)\n   {\n      matrix_t mat = *(matrix_t*)matrix;\n\n      scale[0] = mat.v.right.Length();\n      scale[1] = mat.v.up.Length();\n      scale[2] = mat.v.dir.Length();\n\n      mat.OrthoNormalize();\n\n      rotation[0] = RAD2DEG * atan2f(mat.m[1][2], mat.m[2][2]);\n      rotation[1] = RAD2DEG * atan2f(-mat.m[0][2], sqrtf(mat.m[1][2] * mat.m[1][2] + mat.m[2][2] * mat.m[2][2]));\n      rotation[2] = RAD2DEG * atan2f(mat.m[0][1], mat.m[0][0]);\n\n      translation[0] = mat.v.position.x;\n      translation[1] = mat.v.position.y;\n      translation[2] = mat.v.position.z;\n   }\n\n   void RecomposeMatrixFromComponents(const float* translation, const float* rotation, const float* scale, float* matrix)\n   {\n      matrix_t& mat = *(matrix_t*)matrix;\n\n      matrix_t rot[3];\n      for (int i = 0; i < 3; i++)\n      {\n         rot[i].RotationAxis(directionUnary[i], rotation[i] * DEG2RAD);\n      }\n\n      mat = rot[0] * rot[1] * rot[2];\n\n      float validScale[3];\n      for (int i = 0; i < 3; i++)\n      {\n         if (fabsf(scale[i]) < FLT_EPSILON)\n         {\n            validScale[i] = 0.001f;\n         }\n         else\n         {\n            validScale[i] = scale[i];\n         }\n      }\n      mat.v.right *= validScale[0];\n      mat.v.up *= validScale[1];\n      mat.v.dir *= validScale[2];\n      mat.v.position.Set(translation[0], translation[1], translation[2], 1.f);\n   }\n\n   void SetID(int id)\n   {\n      gContext.mActualID = id;\n   }\n\n   void AllowAxisFlip(bool value)\n   {\n     gContext.mAllowAxisFlip = value;\n   }\n\n   bool Manipulate(const float* view, const float* projection, OPERATION operation, MODE mode, float* matrix, float* deltaMatrix, const float* snap, const float* localBounds, const float* boundsSnap)\n   {\n      // Scale is always local or matrix will be skewed when applying world scale or oriented matrix\n      ComputeContext(view, projection, matrix, (operation & SCALE) ? LOCAL : mode);\n\n      // set delta to identity\n      if (deltaMatrix)\n      {\n         ((matrix_t*)deltaMatrix)->SetToIdentity();\n      }\n\n      // behind camera\n      vec_t camSpacePosition;\n      camSpacePosition.TransformPoint(makeVect(0.f, 0.f, 0.f), gContext.mMVP);\n      if (!gContext.mIsOrthographic && camSpacePosition.z < 0.001f)\n      {\n         return false;\n      }\n\n      // --\n      int type = MT_NONE;\n      bool manipulated = false;\n      if (gContext.mbEnable)\n      {\n         if (!gContext.mbUsingBounds)\n         {\n            manipulated = HandleTranslation(matrix, deltaMatrix, operation, type, snap) ||\n                          HandleScale(matrix, deltaMatrix, operation, type, snap) ||\n                          HandleRotation(matrix, deltaMatrix, operation, type, snap);\n         }\n      }\n\n      if (localBounds && !gContext.mbUsing)\n      {\n         HandleAndDrawLocalBounds(localBounds, (matrix_t*)matrix, boundsSnap, operation);\n      }\n\n      gContext.mOperation = operation;\n      if (!gContext.mbUsingBounds)\n      {\n         DrawRotationGizmo(operation, type);\n         DrawTranslationGizmo(operation, type);\n         DrawScaleGizmo(operation, type);\n         DrawScaleUniveralGizmo(operation, type);\n      }\n      return manipulated;\n   }\n\n   void SetGizmoSizeClipSpace(float value)\n   {\n      gContext.mGizmoSizeClipSpace = value;\n   }\n\n   ///////////////////////////////////////////////////////////////////////////////////////////////////\n   void ComputeFrustumPlanes(vec_t* frustum, const float* clip)\n   {\n      frustum[0].x = clip[3] - clip[0];\n      frustum[0].y = clip[7] - clip[4];\n      frustum[0].z = clip[11] - clip[8];\n      frustum[0].w = clip[15] - clip[12];\n\n      frustum[1].x = clip[3] + clip[0];\n      frustum[1].y = clip[7] + clip[4];\n      frustum[1].z = clip[11] + clip[8];\n      frustum[1].w = clip[15] + clip[12];\n\n      frustum[2].x = clip[3] + clip[1];\n      frustum[2].y = clip[7] + clip[5];\n      frustum[2].z = clip[11] + clip[9];\n      frustum[2].w = clip[15] + clip[13];\n\n      frustum[3].x = clip[3] - clip[1];\n      frustum[3].y = clip[7] - clip[5];\n      frustum[3].z = clip[11] - clip[9];\n      frustum[3].w = clip[15] - clip[13];\n\n      frustum[4].x = clip[3] - clip[2];\n      frustum[4].y = clip[7] - clip[6];\n      frustum[4].z = clip[11] - clip[10];\n      frustum[4].w = clip[15] - clip[14];\n\n      frustum[5].x = clip[3] + clip[2];\n      frustum[5].y = clip[7] + clip[6];\n      frustum[5].z = clip[11] + clip[10];\n      frustum[5].w = clip[15] + clip[14];\n\n      for (int i = 0; i < 6; i++)\n      {\n         frustum[i].Normalize();\n      }\n   }\n\n   void DrawCubes(const float* view, const float* projection, const float* matrices, int matrixCount)\n   {\n      matrix_t viewInverse;\n      viewInverse.Inverse(*(matrix_t*)view);\n\n      struct CubeFace\n      {\n         float z;\n         ImVec2 faceCoordsScreen[4];\n         ImU32 color;\n      };\n      CubeFace* faces = (CubeFace*)_malloca(sizeof(CubeFace) * matrixCount * 6);\n\n      if (!faces)\n      {\n         return;\n      }\n\n      vec_t frustum[6];\n      matrix_t viewProjection = *(matrix_t*)view * *(matrix_t*)projection;\n      ComputeFrustumPlanes(frustum, viewProjection.m16);\n\n      int cubeFaceCount = 0;\n      for (int cube = 0; cube < matrixCount; cube++)\n      {\n         const float* matrix = &matrices[cube * 16];\n\n         matrix_t res = *(matrix_t*)matrix * *(matrix_t*)view * *(matrix_t*)projection;\n\n         for (int iFace = 0; iFace < 6; iFace++)\n         {\n            const int normalIndex = (iFace % 3);\n            const int perpXIndex = (normalIndex + 1) % 3;\n            const int perpYIndex = (normalIndex + 2) % 3;\n            const float invert = (iFace > 2) ? -1.f : 1.f;\n\n            const vec_t faceCoords[4] = { directionUnary[normalIndex] + directionUnary[perpXIndex] + directionUnary[perpYIndex],\n               directionUnary[normalIndex] + directionUnary[perpXIndex] - directionUnary[perpYIndex],\n               directionUnary[normalIndex] - directionUnary[perpXIndex] - directionUnary[perpYIndex],\n               directionUnary[normalIndex] - directionUnary[perpXIndex] + directionUnary[perpYIndex],\n            };\n\n            // clipping\n            /*\n            bool skipFace = false;\n            for (unsigned int iCoord = 0; iCoord < 4; iCoord++)\n            {\n               vec_t camSpacePosition;\n               camSpacePosition.TransformPoint(faceCoords[iCoord] * 0.5f * invert, res);\n               if (camSpacePosition.z < 0.001f)\n               {\n                  skipFace = true;\n                  break;\n               }\n            }\n            if (skipFace)\n            {\n               continue;\n            }\n            */\n            vec_t centerPosition, centerPositionVP;\n            centerPosition.TransformPoint(directionUnary[normalIndex] * 0.5f * invert, *(matrix_t*)matrix);\n            centerPositionVP.TransformPoint(directionUnary[normalIndex] * 0.5f * invert, res);\n\n            bool inFrustum = true;\n            for (int iFrustum = 0; iFrustum < 6; iFrustum++)\n            {\n               float dist = DistanceToPlane(centerPosition, frustum[iFrustum]);\n               if (dist < 0.f)\n               {\n                  inFrustum = false;\n                  break;\n               }\n            }\n\n            if (!inFrustum)\n            {\n               continue;\n            }\n            CubeFace& cubeFace = faces[cubeFaceCount];\n\n            // 3D->2D\n            //ImVec2 faceCoordsScreen[4];\n            for (unsigned int iCoord = 0; iCoord < 4; iCoord++)\n            {\n               cubeFace.faceCoordsScreen[iCoord] = worldToPos(faceCoords[iCoord] * 0.5f * invert, res);\n            }\n            cubeFace.color = directionColor[normalIndex] | IM_COL32(0x80, 0x80, 0x80, 0);\n\n            cubeFace.z = centerPositionVP.z / centerPositionVP.w;\n            cubeFaceCount++;\n         }\n      }\n      qsort(faces, cubeFaceCount, sizeof(CubeFace), [](void const* _a, void const* _b) {\n         CubeFace* a = (CubeFace*)_a;\n         CubeFace* b = (CubeFace*)_b;\n         if (a->z < b->z)\n         {\n            return 1;\n         }\n         return -1;\n         });\n      // draw face with lighter color\n      for (int iFace = 0; iFace < cubeFaceCount; iFace++)\n      {\n         const CubeFace& cubeFace = faces[iFace];\n         gContext.mDrawList->AddConvexPolyFilled(cubeFace.faceCoordsScreen, 4, cubeFace.color);\n      }\n\n      _freea(faces);\n   }\n\n   void DrawGrid(const float* view, const float* projection, const float* matrix, const float gridSize)\n   {\n      matrix_t viewProjection = *(matrix_t*)view * *(matrix_t*)projection;\n      vec_t frustum[6];\n      ComputeFrustumPlanes(frustum, viewProjection.m16);\n      matrix_t res = *(matrix_t*)matrix * viewProjection;\n\n      for (float f = -gridSize; f <= gridSize; f += 1.f)\n      {\n         for (int dir = 0; dir < 2; dir++)\n         {\n            vec_t ptA = makeVect(dir ? -gridSize : f, 0.f, dir ? f : -gridSize);\n            vec_t ptB = makeVect(dir ? gridSize : f, 0.f, dir ? f : gridSize);\n            bool visible = true;\n            for (int i = 0; i < 6; i++)\n            {\n               float dA = DistanceToPlane(ptA, frustum[i]);\n               float dB = DistanceToPlane(ptB, frustum[i]);\n               if (dA < 0.f && dB < 0.f)\n               {\n                  visible = false;\n                  break;\n               }\n               if (dA > 0.f && dB > 0.f)\n               {\n                  continue;\n               }\n               if (dA < 0.f)\n               {\n                  float len = fabsf(dA - dB);\n                  float t = fabsf(dA) / len;\n                  ptA.Lerp(ptB, t);\n               }\n               if (dB < 0.f)\n               {\n                  float len = fabsf(dB - dA);\n                  float t = fabsf(dB) / len;\n                  ptB.Lerp(ptA, t);\n               }\n            }\n            if (visible)\n            {\n               ImU32 col = IM_COL32(0x80, 0x80, 0x80, 0xFF);\n               col = (fmodf(fabsf(f), 10.f) < FLT_EPSILON) ? IM_COL32(0x90, 0x90, 0x90, 0xFF) : col;\n               col = (fabsf(f) < FLT_EPSILON) ? IM_COL32(0x40, 0x40, 0x40, 0xFF): col;\n\n               float thickness = 1.f;\n               thickness = (fmodf(fabsf(f), 10.f) < FLT_EPSILON) ? 1.5f : thickness;\n               thickness = (fabsf(f) < FLT_EPSILON) ? 2.3f : thickness;\n\n               gContext.mDrawList->AddLine(worldToPos(ptA, res), worldToPos(ptB, res), col, thickness);\n            }\n         }\n      }\n   }\n\n   void ViewManipulate(float* view, float length, ImVec2 position, ImVec2 size, ImU32 backgroundColor)\n   {\n      static bool isDraging = false;\n      static bool isClicking = false;\n      static bool isInside = false;\n      static vec_t interpolationUp;\n      static vec_t interpolationDir;\n      static int interpolationFrames = 0;\n      const vec_t referenceUp = makeVect(0.f, 1.f, 0.f);\n\n      matrix_t svgView, svgProjection;\n      svgView = gContext.mViewMat;\n      svgProjection = gContext.mProjectionMat;\n\n      ImGuiIO& io = ImGui::GetIO();\n      gContext.mDrawList->AddRectFilled(position, position + size, backgroundColor);\n      matrix_t viewInverse;\n      viewInverse.Inverse(*(matrix_t*)view);\n\n      const vec_t camTarget = viewInverse.v.position - viewInverse.v.dir * length;\n\n      // view/projection matrices\n      const float distance = 3.f;\n      matrix_t cubeProjection, cubeView;\n      float fov = acosf(distance / (sqrtf(distance * distance + 3.f))) * RAD2DEG;\n      Perspective(fov / sqrtf(2.f), size.x / size.y, 0.01f, 1000.f, cubeProjection.m16);\n\n      vec_t dir = makeVect(viewInverse.m[2][0], viewInverse.m[2][1], viewInverse.m[2][2]);\n      vec_t up = makeVect(viewInverse.m[1][0], viewInverse.m[1][1], viewInverse.m[1][2]);\n      vec_t eye = dir * distance;\n      vec_t zero = makeVect(0.f, 0.f);\n      LookAt(&eye.x, &zero.x, &up.x, cubeView.m16);\n\n      // set context\n      gContext.mViewMat = cubeView;\n      gContext.mProjectionMat = cubeProjection;\n      ComputeCameraRay(gContext.mRayOrigin, gContext.mRayVector, position, size);\n\n      const matrix_t res = cubeView * cubeProjection;\n\n      // panels\n      static const ImVec2 panelPosition[9] = { ImVec2(0.75f,0.75f), ImVec2(0.25f, 0.75f), ImVec2(0.f, 0.75f),\n         ImVec2(0.75f, 0.25f), ImVec2(0.25f, 0.25f), ImVec2(0.f, 0.25f),\n         ImVec2(0.75f, 0.f), ImVec2(0.25f, 0.f), ImVec2(0.f, 0.f) };\n\n      static const ImVec2 panelSize[9] = { ImVec2(0.25f,0.25f), ImVec2(0.5f, 0.25f), ImVec2(0.25f, 0.25f),\n         ImVec2(0.25f, 0.5f), ImVec2(0.5f, 0.5f), ImVec2(0.25f, 0.5f),\n         ImVec2(0.25f, 0.25f), ImVec2(0.5f, 0.25f), ImVec2(0.25f, 0.25f) };\n\n      // tag faces\n      bool boxes[27]{};\n      for (int iPass = 0; iPass < 2; iPass++)\n      {\n         for (int iFace = 0; iFace < 6; iFace++)\n         {\n            const int normalIndex = (iFace % 3);\n            const int perpXIndex = (normalIndex + 1) % 3;\n            const int perpYIndex = (normalIndex + 2) % 3;\n            const float invert = (iFace > 2) ? -1.f : 1.f;\n            const vec_t indexVectorX = directionUnary[perpXIndex] * invert;\n            const vec_t indexVectorY = directionUnary[perpYIndex] * invert;\n            const vec_t boxOrigin = directionUnary[normalIndex] * -invert - indexVectorX - indexVectorY;\n\n            // plan local space\n            const vec_t n = directionUnary[normalIndex] * invert;\n            vec_t viewSpaceNormal = n;\n            vec_t viewSpacePoint = n * 0.5f;\n            viewSpaceNormal.TransformVector(cubeView);\n            viewSpaceNormal.Normalize();\n            viewSpacePoint.TransformPoint(cubeView);\n            const vec_t viewSpaceFacePlan = BuildPlan(viewSpacePoint, viewSpaceNormal);\n\n            // back face culling\n            if (viewSpaceFacePlan.w > 0.f)\n            {\n               continue;\n            }\n\n            const vec_t facePlan = BuildPlan(n * 0.5f, n);\n\n            const float len = IntersectRayPlane(gContext.mRayOrigin, gContext.mRayVector, facePlan);\n            vec_t posOnPlan = gContext.mRayOrigin + gContext.mRayVector * len - (n * 0.5f);\n\n            float localx = Dot(directionUnary[perpXIndex], posOnPlan) * invert + 0.5f;\n            float localy = Dot(directionUnary[perpYIndex], posOnPlan) * invert + 0.5f;\n\n            // panels\n            const vec_t dx = directionUnary[perpXIndex];\n            const vec_t dy = directionUnary[perpYIndex];\n            const vec_t origin = directionUnary[normalIndex] - dx - dy;\n            for (int iPanel = 0; iPanel < 9; iPanel++)\n            {\n               vec_t boxCoord = boxOrigin + indexVectorX * float(iPanel % 3) + indexVectorY * float(iPanel / 3) + makeVect(1.f, 1.f, 1.f);\n               const ImVec2 p = panelPosition[iPanel] * 2.f;\n               const ImVec2 s = panelSize[iPanel] * 2.f;\n               ImVec2 faceCoordsScreen[4];\n               vec_t panelPos[4] = { dx * p.x + dy * p.y,\n                                     dx * p.x + dy * (p.y + s.y),\n                                     dx * (p.x + s.x) + dy * (p.y + s.y),\n                                     dx * (p.x + s.x) + dy * p.y };\n\n               for (unsigned int iCoord = 0; iCoord < 4; iCoord++)\n               {\n                  faceCoordsScreen[iCoord] = worldToPos((panelPos[iCoord] + origin) * 0.5f * invert, res, position, size);\n               }\n\n               const ImVec2 panelCorners[2] = { panelPosition[iPanel], panelPosition[iPanel] + panelSize[iPanel] };\n               bool insidePanel = localx > panelCorners[0].x && localx < panelCorners[1].x&& localy > panelCorners[0].y && localy < panelCorners[1].y;\n               int boxCoordInt = int(boxCoord.x * 9.f + boxCoord.y * 3.f + boxCoord.z);\n               assert(boxCoordInt < 27);\n               boxes[boxCoordInt] |= insidePanel && (!isDraging) && gContext.mbMouseOver;\n\n               // draw face with lighter color\n               if (iPass)\n               {\n                  gContext.mDrawList->AddConvexPolyFilled(faceCoordsScreen, 4, (directionColor[normalIndex] | IM_COL32(0x80, 0x80, 0x80, 0x80)) | (isInside ? IM_COL32(0x08, 0x08, 0x08, 0) : 0));\n                  if (boxes[boxCoordInt])\n                  {\n                     gContext.mDrawList->AddConvexPolyFilled(faceCoordsScreen, 4, IM_COL32(0xF0, 0xA0, 0x60, 0x80));\n\n                     if (!io.MouseDown[0] && !isDraging && isClicking)\n                     {\n                        // apply new view direction\n                        int cx = boxCoordInt / 9;\n                        int cy = (boxCoordInt - cx * 9) / 3;\n                        int cz = boxCoordInt % 3;\n                        interpolationDir = makeVect(1.f - cx, 1.f - cy, 1.f - cz);\n                        interpolationDir.Normalize();\n\n                        if (fabsf(Dot(interpolationDir, referenceUp)) > 1.0f - 0.01f)\n                        {\n                           vec_t right = viewInverse.v.right;\n                           if (fabsf(right.x) > fabsf(right.z))\n                           {\n                              right.z = 0.f;\n                           }\n                           else\n                           {\n                              right.x = 0.f;\n                           }\n                           right.Normalize();\n                           interpolationUp = Cross(interpolationDir, right);\n                           interpolationUp.Normalize();\n                        }\n                        else\n                        {\n                           interpolationUp = referenceUp;\n                        }\n                        interpolationFrames = 40;\n                        isClicking = false;\n                     }\n                     if (io.MouseClicked[0] && !isDraging)\n                     {\n                        isClicking = true;\n                     }\n                  }\n               }\n            }\n         }\n      }\n      if (interpolationFrames)\n      {\n         interpolationFrames--;\n         vec_t newDir = viewInverse.v.dir;\n         newDir.Lerp(interpolationDir, 0.2f);\n         newDir.Normalize();\n\n         vec_t newUp = viewInverse.v.up;\n         newUp.Lerp(interpolationUp, 0.3f);\n         newUp.Normalize();\n         newUp = interpolationUp;\n         vec_t newEye = camTarget + newDir * length;\n         LookAt(&newEye.x, &camTarget.x, &newUp.x, view);\n      }\n      isInside = gContext.mbMouseOver && ImRect(position, position + size).Contains(io.MousePos);\n\n      // drag view\n      if (!isDraging && io.MouseClicked[0] && isInside)\n      {\n         isDraging = true;\n         isClicking = false;\n      }\n      else if (isDraging && !io.MouseDown[0])\n      {\n         isDraging = false;\n      }\n\n      if (isDraging)\n      {\n         matrix_t rx, ry, roll;\n\n         rx.RotationAxis(referenceUp, -io.MouseDelta.x * 0.01f);\n         ry.RotationAxis(viewInverse.v.right, -io.MouseDelta.y * 0.01f);\n\n         roll = rx * ry;\n\n         vec_t newDir = viewInverse.v.dir;\n         newDir.TransformVector(roll);\n         newDir.Normalize();\n\n         // clamp\n         vec_t planDir = Cross(viewInverse.v.right, referenceUp);\n         planDir.y = 0.f;\n         planDir.Normalize();\n         float dt = Dot(planDir, newDir);\n         if (dt < 0.0f)\n         {\n            newDir += planDir * dt;\n            newDir.Normalize();\n         }\n\n         vec_t newEye = camTarget + newDir * length;\n         LookAt(&newEye.x, &camTarget.x, &referenceUp.x, view);\n      }\n\n      // restore view/projection because it was used to compute ray\n      ComputeContext(svgView.m16, svgProjection.m16, gContext.mModelSource.m16, gContext.mMode);\n   }\n};\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/ImGuizmo/ImGuizmo.h",
    "content": "// https://github.com/CedricGuillemet/ImGuizmo\r\n// v 1.84 WIP\r\n//\r\n// The MIT License(MIT)\r\n//\r\n// Copyright(c) 2021 Cedric Guillemet\r\n//\r\n// Permission is hereby granted, free of charge, to any person obtaining a copy\r\n// of this software and associated documentation files(the \"Software\"), to deal\r\n// in the Software without restriction, including without limitation the rights\r\n// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell\r\n// copies of the Software, and to permit persons to whom the Software is\r\n// furnished to do so, subject to the following conditions :\r\n//\r\n// The above copyright notice and this permission notice shall be included in all\r\n// copies or substantial portions of the Software.\r\n//\r\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE\r\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n// SOFTWARE.\r\n//\r\n// -------------------------------------------------------------------------------------------\r\n// History :\r\n// 2019/11/03 View gizmo\r\n// 2016/09/11 Behind camera culling. Scaling Delta matrix not multiplied by source matrix scales. local/world rotation and translation fixed. Display message is incorrect (X: ... Y:...) in local mode.\r\n// 2016/09/09 Hatched negative axis. Snapping. Documentation update.\r\n// 2016/09/04 Axis switch and translation plan autohiding. Scale transform stability improved\r\n// 2016/09/01 Mogwai changed to Manipulate. Draw debug cube. Fixed inverted scale. Mixing scale and translation/rotation gives bad results.\r\n// 2016/08/31 First version\r\n//\r\n// -------------------------------------------------------------------------------------------\r\n// Future (no order):\r\n//\r\n// - Multi view\r\n// - display rotation/translation/scale infos in local/world space and not only local\r\n// - finish local/world matrix application\r\n// - OPERATION as bitmask\r\n// \r\n// -------------------------------------------------------------------------------------------\r\n// Example \r\n#if 0\r\nvoid EditTransform(const Camera& camera, matrix_t& matrix)\r\n{\r\n   static ImGuizmo::OPERATION mCurrentGizmoOperation(ImGuizmo::ROTATE);\r\n   static ImGuizmo::MODE mCurrentGizmoMode(ImGuizmo::WORLD);\r\n   if (ImGui::IsKeyPressed(90))\r\n      mCurrentGizmoOperation = ImGuizmo::TRANSLATE;\r\n   if (ImGui::IsKeyPressed(69))\r\n      mCurrentGizmoOperation = ImGuizmo::ROTATE;\r\n   if (ImGui::IsKeyPressed(82)) // r Key\r\n      mCurrentGizmoOperation = ImGuizmo::SCALE;\r\n   if (ImGui::RadioButton(\"Translate\", mCurrentGizmoOperation == ImGuizmo::TRANSLATE))\r\n      mCurrentGizmoOperation = ImGuizmo::TRANSLATE;\r\n   ImGui::SameLine();\r\n   if (ImGui::RadioButton(\"Rotate\", mCurrentGizmoOperation == ImGuizmo::ROTATE))\r\n      mCurrentGizmoOperation = ImGuizmo::ROTATE;\r\n   ImGui::SameLine();\r\n   if (ImGui::RadioButton(\"Scale\", mCurrentGizmoOperation == ImGuizmo::SCALE))\r\n      mCurrentGizmoOperation = ImGuizmo::SCALE;\r\n   float matrixTranslation[3], matrixRotation[3], matrixScale[3];\r\n   ImGuizmo::DecomposeMatrixToComponents(matrix.m16, matrixTranslation, matrixRotation, matrixScale);\r\n   ImGui::InputFloat3(\"Tr\", matrixTranslation, 3);\r\n   ImGui::InputFloat3(\"Rt\", matrixRotation, 3);\r\n   ImGui::InputFloat3(\"Sc\", matrixScale, 3);\r\n   ImGuizmo::RecomposeMatrixFromComponents(matrixTranslation, matrixRotation, matrixScale, matrix.m16);\r\n\r\n   if (mCurrentGizmoOperation != ImGuizmo::SCALE)\r\n   {\r\n      if (ImGui::RadioButton(\"Local\", mCurrentGizmoMode == ImGuizmo::LOCAL))\r\n         mCurrentGizmoMode = ImGuizmo::LOCAL;\r\n      ImGui::SameLine();\r\n      if (ImGui::RadioButton(\"World\", mCurrentGizmoMode == ImGuizmo::WORLD))\r\n         mCurrentGizmoMode = ImGuizmo::WORLD;\r\n   }\r\n   static bool useSnap(false);\r\n   if (ImGui::IsKeyPressed(83))\r\n      useSnap = !useSnap;\r\n   ImGui::Checkbox(\"\", &useSnap);\r\n   ImGui::SameLine();\r\n   vec_t snap;\r\n   switch (mCurrentGizmoOperation)\r\n   {\r\n   case ImGuizmo::TRANSLATE:\r\n      snap = config.mSnapTranslation;\r\n      ImGui::InputFloat3(\"Snap\", &snap.x);\r\n      break;\r\n   case ImGuizmo::ROTATE:\r\n      snap = config.mSnapRotation;\r\n      ImGui::InputFloat(\"Angle Snap\", &snap.x);\r\n      break;\r\n   case ImGuizmo::SCALE:\r\n      snap = config.mSnapScale;\r\n      ImGui::InputFloat(\"Scale Snap\", &snap.x);\r\n      break;\r\n   }\r\n   ImGuiIO& io = ImGui::GetIO();\r\n   ImGuizmo::SetRect(0, 0, io.DisplaySize.x, io.DisplaySize.y);\r\n   ImGuizmo::Manipulate(camera.mView.m16, camera.mProjection.m16, mCurrentGizmoOperation, mCurrentGizmoMode, matrix.m16, NULL, useSnap ? &snap.x : NULL);\r\n}\r\n#endif\r\n#pragma once\r\n\r\n#ifdef USE_IMGUI_API\r\n#include \"imconfig.h\"\r\n#endif\r\n#ifndef IMGUI_API\r\n#define IMGUI_API\r\n#endif\n\n#ifndef IMGUIZMO_NAMESPACE\n#define IMGUIZMO_NAMESPACE ImGuizmo\n#endif\r\n\r\nnamespace IMGUIZMO_NAMESPACE\r\n{\r\n   // call inside your own window and before Manipulate() in order to draw gizmo to that window.\r\n   // Or pass a specific ImDrawList to draw to (e.g. ImGui::GetForegroundDrawList()).\r\n   IMGUI_API void SetDrawlist(ImDrawList* drawlist = nullptr);\r\n\r\n   // call BeginFrame right after ImGui_XXXX_NewFrame();\r\n   IMGUI_API void BeginFrame();\r\n\r\n   // this is necessary because when imguizmo is compiled into a dll, and imgui into another\r\n   // globals are not shared between them.\r\n   // More details at https://stackoverflow.com/questions/19373061/what-happens-to-global-and-static-variables-in-a-shared-library-when-it-is-dynam\r\n   // expose method to set imgui context\r\n   IMGUI_API void SetImGuiContext(ImGuiContext* ctx);\r\n\r\n   // return true if mouse cursor is over any gizmo control (axis, plan or screen component)\r\n   IMGUI_API bool IsOver();\r\n\r\n   // return true if mouse IsOver or if the gizmo is in moving state\r\n   IMGUI_API bool IsUsing();\r\n\r\n   // enable/disable the gizmo. Stay in the state until next call to Enable.\r\n   // gizmo is rendered with gray half transparent color when disabled\r\n   IMGUI_API void Enable(bool enable);\r\n\r\n   // helper functions for manualy editing translation/rotation/scale with an input float\r\n   // translation, rotation and scale float points to 3 floats each\r\n   // Angles are in degrees (more suitable for human editing)\r\n   // example:\r\n   // float matrixTranslation[3], matrixRotation[3], matrixScale[3];\r\n   // ImGuizmo::DecomposeMatrixToComponents(gizmoMatrix.m16, matrixTranslation, matrixRotation, matrixScale);\r\n   // ImGui::InputFloat3(\"Tr\", matrixTranslation, 3);\r\n   // ImGui::InputFloat3(\"Rt\", matrixRotation, 3);\r\n   // ImGui::InputFloat3(\"Sc\", matrixScale, 3);\r\n   // ImGuizmo::RecomposeMatrixFromComponents(matrixTranslation, matrixRotation, matrixScale, gizmoMatrix.m16);\r\n   //\r\n   // These functions have some numerical stability issues for now. Use with caution.\r\n   IMGUI_API void DecomposeMatrixToComponents(const float* matrix, float* translation, float* rotation, float* scale);\r\n   IMGUI_API void RecomposeMatrixFromComponents(const float* translation, const float* rotation, const float* scale, float* matrix);\r\n\r\n   IMGUI_API void SetRect(float x, float y, float width, float height);\r\n   // default is false\r\n   IMGUI_API void SetOrthographic(bool isOrthographic);\r\n\r\n   // Render a cube with face color corresponding to face normal. Usefull for debug/tests\r\n   IMGUI_API void DrawCubes(const float* view, const float* projection, const float* matrices, int matrixCount);\r\n   IMGUI_API void DrawGrid(const float* view, const float* projection, const float* matrix, const float gridSize);\r\n\r\n   // call it when you want a gizmo\r\n   // Needs view and projection matrices. \r\n   // matrix parameter is the source matrix (where will be gizmo be drawn) and might be transformed by the function. Return deltaMatrix is optional\r\n   // translation is applied in world space\r\n   enum OPERATION\r\n   {\r\n      TRANSLATE_X      = (1u << 0),\r\n      TRANSLATE_Y      = (1u << 1),\r\n      TRANSLATE_Z      = (1u << 2),\r\n      ROTATE_X         = (1u << 3),\r\n      ROTATE_Y         = (1u << 4),\r\n      ROTATE_Z         = (1u << 5),\r\n      ROTATE_SCREEN    = (1u << 6),\r\n      SCALE_X          = (1u << 7),\r\n      SCALE_Y          = (1u << 8),\r\n      SCALE_Z          = (1u << 9),\r\n      BOUNDS           = (1u << 10),\n      SCALE_XU         = (1u << 11),\r\n      SCALE_YU         = (1u << 12),\r\n      SCALE_ZU         = (1u << 13),\r\n\r\n      TRANSLATE = TRANSLATE_X | TRANSLATE_Y | TRANSLATE_Z,\r\n      ROTATE = ROTATE_X | ROTATE_Y | ROTATE_Z | ROTATE_SCREEN,\r\n      SCALE = SCALE_X | SCALE_Y | SCALE_Z,\n      SCALEU = SCALE_XU | SCALE_YU | SCALE_ZU, // universal\n      UNIVERSAL = TRANSLATE | ROTATE | SCALEU\r\n   };\r\n\r\n   inline OPERATION operator|(OPERATION lhs, OPERATION rhs)\r\n   {\r\n     return static_cast<OPERATION>(static_cast<int>(lhs) | static_cast<int>(rhs));\r\n   }\r\n\r\n   enum MODE\r\n   {\r\n      LOCAL,\r\n      WORLD\r\n   };\r\n\r\n   IMGUI_API bool Manipulate(const float* view, const float* projection, OPERATION operation, MODE mode, float* matrix, float* deltaMatrix = NULL, const float* snap = NULL, const float* localBounds = NULL, const float* boundsSnap = NULL);\r\n   //\r\n   // Please note that this cubeview is patented by Autodesk : https://patents.google.com/patent/US7782319B2/en\r\n   // It seems to be a defensive patent in the US. I don't think it will bring troubles using it as\r\n   // other software are using the same mechanics. But just in case, you are now warned!\r\n   //\r\n   IMGUI_API void ViewManipulate(float* view, float length, ImVec2 position, ImVec2 size, ImU32 backgroundColor);\r\n\r\n   IMGUI_API void SetID(int id);\r\n\r\n   // return true if the cursor is over the operation's gizmo\r\n   IMGUI_API bool IsOver(OPERATION op);\r\n   IMGUI_API void SetGizmoSizeClipSpace(float value);\r\n\r\n   // Allow axis to flip\r\n   // When true (default), the guizmo axis flip for better visibility\r\n   // When false, they always stay along the positive world/local axis\r\n   IMGUI_API void AllowAxisFlip(bool value);\r\n}\r\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/imgui/imconfig.h",
    "content": "//-----------------------------------------------------------------------------\r\n// COMPILE-TIME OPTIONS FOR DEAR IMGUI\r\n// Runtime options (clipboard callbacks, enabling various features, etc.) can generally be set via the ImGuiIO structure.\r\n// You can use ImGui::SetAllocatorFunctions() before calling ImGui::CreateContext() to rewire memory allocation functions.\r\n//-----------------------------------------------------------------------------\r\n// A) You may edit imconfig.h (and not overwrite it when updating Dear ImGui, or maintain a patch/rebased branch with your modifications to it)\r\n// B) or '#define IMGUI_USER_CONFIG \"my_imgui_config.h\"' in your project and then add directives in your own file without touching this template.\r\n//-----------------------------------------------------------------------------\r\n// You need to make sure that configuration settings are defined consistently _everywhere_ Dear ImGui is used, which include the imgui*.cpp\r\n// files but also _any_ of your code that uses Dear ImGui. This is because some compile-time options have an affect on data structures.\r\n// Defining those options in imconfig.h will ensure every compilation unit gets to see the same data structure layouts.\r\n// Call IMGUI_CHECKVERSION() from your .cpp files to verify that the data structures your files are using are matching the ones imgui.cpp is using.\r\n//-----------------------------------------------------------------------------\r\n\r\n#pragma once\r\n\r\n//---- Define assertion handler. Defaults to calling assert().\r\n// If your macro uses multiple statements, make sure is enclosed in a 'do { .. } while (0)' block so it can be used as a single statement.\r\n//#define IM_ASSERT(_EXPR)  MyAssert(_EXPR)\r\n//#define IM_ASSERT(_EXPR)  ((void)(_EXPR))     // Disable asserts\r\n\r\n//---- Define attributes of all API symbols declarations, e.g. for DLL under Windows\r\n// Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility.\r\n// DLL users: heaps and globals are not shared across DLL boundaries! You will need to call SetCurrentContext() + SetAllocatorFunctions()\r\n// for each static/DLL boundary you are calling from. Read \"Context and Memory Allocators\" section of imgui.cpp for more details.\r\n//#define IMGUI_API __declspec( dllexport )\r\n//#define IMGUI_API __declspec( dllimport )\r\n\r\n//---- Don't define obsolete functions/enums/behaviors. Consider enabling from time to time after updating to avoid using soon-to-be obsolete function/names.\r\n//#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS\r\n//#define IMGUI_DISABLE_OBSOLETE_KEYIO                      // 1.87: disable legacy io.KeyMap[]+io.KeysDown[] in favor io.AddKeyEvent(). This will be folded into IMGUI_DISABLE_OBSOLETE_FUNCTIONS in a few versions.\r\n\r\n//---- Disable all of Dear ImGui or don't implement standard windows.\r\n// It is very strongly recommended to NOT disable the demo windows during development. Please read comments in imgui_demo.cpp.\r\n//#define IMGUI_DISABLE                                     // Disable everything: all headers and source files will be empty.\r\n//#define IMGUI_DISABLE_DEMO_WINDOWS                        // Disable demo windows: ShowDemoWindow()/ShowStyleEditor() will be empty. Not recommended.\r\n//#define IMGUI_DISABLE_METRICS_WINDOW                      // Disable metrics/debugger and other debug tools: ShowMetricsWindow() and ShowStackToolWindow() will be empty.\r\n\r\n//---- Don't implement some functions to reduce linkage requirements.\r\n//#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS   // [Win32] Don't implement default clipboard handler. Won't use and link with OpenClipboard/GetClipboardData/CloseClipboard etc. (user32.lib/.a, kernel32.lib/.a)\r\n//#define IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS          // [Win32] [Default with Visual Studio] Implement default IME handler (require imm32.lib/.a, auto-link for Visual Studio, -limm32 on command-line for MinGW)\r\n//#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS         // [Win32] [Default with non-Visual Studio compilers] Don't implement default IME handler (won't require imm32.lib/.a)\r\n//#define IMGUI_DISABLE_WIN32_FUNCTIONS                     // [Win32] Won't use and link with any Win32 function (clipboard, ime).\r\n//#define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS      // [OSX] Implement default OSX clipboard handler (need to link with '-framework ApplicationServices', this is why this is not the default).\r\n//#define IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS            // Don't implement ImFormatString/ImFormatStringV so you can implement them yourself (e.g. if you don't want to link with vsnprintf)\r\n//#define IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS              // Don't implement ImFabs/ImSqrt/ImPow/ImFmod/ImCos/ImSin/ImAcos/ImAtan2 so you can implement them yourself.\r\n//#define IMGUI_DISABLE_FILE_FUNCTIONS                      // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle at all (replace them with dummies)\r\n//#define IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS              // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle so you can implement them yourself if you don't want to link with fopen/fclose/fread/fwrite. This will also disable the LogToTTY() function.\r\n//#define IMGUI_DISABLE_DEFAULT_ALLOCATORS                  // Don't implement default allocators calling malloc()/free() to avoid linking with them. You will need to call ImGui::SetAllocatorFunctions().\r\n//#define IMGUI_DISABLE_SSE                                 // Disable use of SSE intrinsics even if available\r\n\r\n//---- Include imgui_user.h at the end of imgui.h as a convenience\r\n//#define IMGUI_INCLUDE_IMGUI_USER_H\r\n\r\n//---- Pack colors to BGRA8 instead of RGBA8 (to avoid converting from one to another)\r\n//#define IMGUI_USE_BGRA_PACKED_COLOR\r\n\r\n//---- Use 32-bit for ImWchar (default is 16-bit) to support unicode planes 1-16. (e.g. point beyond 0xFFFF like emoticons, dingbats, symbols, shapes, ancient languages, etc...)\r\n//#define IMGUI_USE_WCHAR32\r\n\r\n//---- Avoid multiple STB libraries implementations, or redefine path/filenames to prioritize another version\r\n// By default the embedded implementations are declared static and not available outside of Dear ImGui sources files.\r\n//#define IMGUI_STB_TRUETYPE_FILENAME   \"my_folder/stb_truetype.h\"\r\n//#define IMGUI_STB_RECT_PACK_FILENAME  \"my_folder/stb_rect_pack.h\"\r\n//#define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION\r\n//#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION\r\n\r\n//---- Use stb_printf's faster implementation of vsnprintf instead of the one from libc (unless IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS is defined)\r\n// Requires 'stb_sprintf.h' to be available in the include path. Compatibility checks of arguments and formats done by clang and GCC will be disabled in order to support the extra formats provided by STB sprintf.\r\n// #define IMGUI_USE_STB_SPRINTF\r\n\r\n//---- Use FreeType to build and rasterize the font atlas (instead of stb_truetype which is embedded by default in Dear ImGui)\r\n// Requires FreeType headers to be available in the include path. Requires program to be compiled with 'misc/freetype/imgui_freetype.cpp' (in this repository) + the FreeType library (not provided).\r\n// On Windows you may use vcpkg with 'vcpkg install freetype --triplet=x64-windows' + 'vcpkg integrate install'.\r\n//#define IMGUI_ENABLE_FREETYPE\r\n\r\n//---- Use stb_truetype to build and rasterize the font atlas (default)\r\n// The only purpose of this define is if you want force compilation of the stb_truetype backend ALONG with the FreeType backend.\r\n//#define IMGUI_ENABLE_STB_TRUETYPE\r\n\r\n//---- Define constructor and implicit cast operators to convert back<>forth between your math types and ImVec2/ImVec4.\r\n// This will be inlined as part of ImVec2 and ImVec4 class declarations.\r\n/*\r\n#define IM_VEC2_CLASS_EXTRA                                                 \\\r\n        ImVec2(const MyVec2& f) { x = f.x; y = f.y; }                       \\\r\n        operator MyVec2() const { return MyVec2(x,y); }\r\n\r\n#define IM_VEC4_CLASS_EXTRA                                                 \\\r\n        ImVec4(const MyVec4& f) { x = f.x; y = f.y; z = f.z; w = f.w; }     \\\r\n        operator MyVec4() const { return MyVec4(x,y,z,w); }\r\n*/\r\n\r\n//---- Use 32-bit vertex indices (default is 16-bit) is one way to allow large meshes with more than 64K vertices.\r\n// Your renderer backend will need to support it (most example renderer backends support both 16/32-bit indices).\r\n// Another way to allow large meshes while keeping 16-bit indices is to handle ImDrawCmd::VtxOffset in your renderer.\r\n// Read about ImGuiBackendFlags_RendererHasVtxOffset for details.\r\n//#define ImDrawIdx unsigned int\r\n\r\n//---- Override ImDrawCallback signature (will need to modify renderer backends accordingly)\r\n//struct ImDrawList;\r\n//struct ImDrawCmd;\r\n//typedef void (*MyImDrawCallback)(const ImDrawList* draw_list, const ImDrawCmd* cmd, void* my_renderer_user_data);\r\n//#define ImDrawCallback MyImDrawCallback\r\n\r\n//---- Debug Tools: Macro to break in Debugger\r\n// (use 'Metrics->Tools->Item Picker' to pick widgets with the mouse and break into them for easy debugging.)\r\n//#define IM_DEBUG_BREAK  IM_ASSERT(0)\r\n//#define IM_DEBUG_BREAK  __debugbreak()\r\n\r\n//---- Debug Tools: Have the Item Picker break in the ItemAdd() function instead of ItemHoverable(),\r\n// (which comes earlier in the code, will catch a few extra items, allow picking items other than Hovered one.)\r\n// This adds a small runtime cost which is why it is not enabled by default.\r\n//#define IMGUI_DEBUG_TOOL_ITEM_PICKER_EX\r\n\r\n//---- Debug Tools: Enable slower asserts\r\n//#define IMGUI_DEBUG_PARANOID\r\n\r\n//---- Tip: You can add extra functions within the ImGui:: namespace, here or in your own headers files.\r\n/*\r\nnamespace ImGui\r\n{\r\n    void MyFunction(const char* name, const MyMatrix44& v);\r\n}\r\n*/\r\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/imgui/imgui.cpp",
    "content": "// dear imgui, v1.87 WIP\r\n// (main code and documentation)\r\n\r\n// Help:\r\n// - Read FAQ at http://dearimgui.org/faq\r\n// - Newcomers, read 'Programmer guide' below for notes on how to setup Dear ImGui in your codebase.\r\n// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that.\r\n// Read imgui.cpp for details, links and comments.\r\n\r\n// Resources:\r\n// - FAQ                   http://dearimgui.org/faq\r\n// - Homepage & latest     https://github.com/ocornut/imgui\r\n// - Releases & changelog  https://github.com/ocornut/imgui/releases\r\n// - Gallery               https://github.com/ocornut/imgui/issues/4451 (please post your screenshots/video there!)\r\n// - Wiki                  https://github.com/ocornut/imgui/wiki (lots of good stuff there)\r\n// - Glossary              https://github.com/ocornut/imgui/wiki/Glossary\r\n// - Issues & support      https://github.com/ocornut/imgui/issues\r\n\r\n// Getting Started?\r\n// - For first-time users having issues compiling/linking/running or issues loading fonts:\r\n//   please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above.\r\n\r\n// Developed by Omar Cornut and every direct or indirect contributors to the GitHub.\r\n// See LICENSE.txt for copyright and licensing details (standard MIT License).\r\n// This library is free but needs your support to sustain development and maintenance.\r\n// Businesses: you can support continued development via invoiced technical support, maintenance and sponsoring contracts. Please reach out to \"contact AT dearimgui.com\".\r\n// Individuals: you can support continued development via donations. See docs/README or web page.\r\n\r\n// It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.\r\n// Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without\r\n// modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't\r\n// come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you\r\n// to a better solution or official support for them.\r\n\r\n/*\r\n\r\nIndex of this file:\r\n\r\nDOCUMENTATION\r\n\r\n- MISSION STATEMENT\r\n- END-USER GUIDE\r\n- PROGRAMMER GUIDE\r\n  - READ FIRST\r\n  - HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI\r\n  - GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE\r\n  - HOW A SIMPLE APPLICATION MAY LOOK LIKE\r\n  - HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE\r\n  - USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS\r\n- API BREAKING CHANGES (read me when you update!)\r\n- FREQUENTLY ASKED QUESTIONS (FAQ)\r\n  - Read all answers online: https://www.dearimgui.org/faq, or in docs/FAQ.md (with a Markdown viewer)\r\n\r\nCODE\r\n(search for \"[SECTION]\" in the code to find them)\r\n\r\n// [SECTION] INCLUDES\r\n// [SECTION] FORWARD DECLARATIONS\r\n// [SECTION] CONTEXT AND MEMORY ALLOCATORS\r\n// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)\r\n// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)\r\n// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)\r\n// [SECTION] MISC HELPERS/UTILITIES (File functions)\r\n// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)\r\n// [SECTION] MISC HELPERS/UTILITIES (Color functions)\r\n// [SECTION] ImGuiStorage\r\n// [SECTION] ImGuiTextFilter\r\n// [SECTION] ImGuiTextBuffer\r\n// [SECTION] ImGuiListClipper\r\n// [SECTION] STYLING\r\n// [SECTION] RENDER HELPERS\r\n// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)\r\n// [SECTION] INPUTS\r\n// [SECTION] ERROR CHECKING\r\n// [SECTION] LAYOUT\r\n// [SECTION] SCROLLING\r\n// [SECTION] TOOLTIPS\r\n// [SECTION] POPUPS\r\n// [SECTION] KEYBOARD/GAMEPAD NAVIGATION\r\n// [SECTION] DRAG AND DROP\r\n// [SECTION] LOGGING/CAPTURING\r\n// [SECTION] SETTINGS\r\n// [SECTION] VIEWPORTS\r\n// [SECTION] PLATFORM DEPENDENT HELPERS\r\n// [SECTION] METRICS/DEBUGGER WINDOW\r\n// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, STACK TOOL)\r\n\r\n*/\r\n\r\n//-----------------------------------------------------------------------------\r\n// DOCUMENTATION\r\n//-----------------------------------------------------------------------------\r\n\r\n/*\r\n\r\n MISSION STATEMENT\r\n =================\r\n\r\n - Easy to use to create code-driven and data-driven tools.\r\n - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools.\r\n - Easy to hack and improve.\r\n - Minimize setup and maintenance.\r\n - Minimize state storage on user side.\r\n - Portable, minimize dependencies, run on target (consoles, phones, etc.).\r\n - Efficient runtime and memory consumption.\r\n\r\n Designed for developers and content-creators, not the typical end-user! Some of the current weaknesses includes:\r\n\r\n - Doesn't look fancy, doesn't animate.\r\n - Limited layout features, intricate layouts are typically crafted in code.\r\n\r\n\r\n END-USER GUIDE\r\n ==============\r\n\r\n - Double-click on title bar to collapse window.\r\n - Click upper right corner to close a window, available when 'bool* p_open' is passed to ImGui::Begin().\r\n - Click and drag on lower right corner to resize window (double-click to auto fit window to its contents).\r\n - Click and drag on any empty space to move window.\r\n - TAB/SHIFT+TAB to cycle through keyboard editable fields.\r\n - CTRL+Click on a slider or drag box to input value as text.\r\n - Use mouse wheel to scroll.\r\n - Text editor:\r\n   - Hold SHIFT or use mouse to select text.\r\n   - CTRL+Left/Right to word jump.\r\n   - CTRL+Shift+Left/Right to select words.\r\n   - CTRL+A our Double-Click to select all.\r\n   - CTRL+X,CTRL+C,CTRL+V to use OS clipboard/\r\n   - CTRL+Z,CTRL+Y to undo/redo.\r\n   - ESCAPE to revert text to its original value.\r\n   - Controls are automatically adjusted for OSX to match standard OSX text editing operations.\r\n - General Keyboard controls: enable with ImGuiConfigFlags_NavEnableKeyboard.\r\n - General Gamepad controls: enable with ImGuiConfigFlags_NavEnableGamepad. See suggested mappings in imgui.h ImGuiNavInput_ + download PNG/PSD at http://dearimgui.org/controls_sheets\r\n\r\n\r\n PROGRAMMER GUIDE\r\n ================\r\n\r\n READ FIRST\r\n ----------\r\n - Remember to check the wonderful Wiki (https://github.com/ocornut/imgui/wiki)\r\n - Your code creates the UI, if your code doesn't run the UI is gone! The UI can be highly dynamic, there are no construction or\r\n   destruction steps, less superfluous data retention on your side, less state duplication, less state synchronization, fewer bugs.\r\n - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.\r\n - The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.\r\n - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).\r\n   You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links in Wiki.\r\n - Dear ImGui is a \"single pass\" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.\r\n   For every application frame, your UI code will be called only once. This is in contrast to e.g. Unity's implementation of an IMGUI,\r\n   where the UI code is called multiple times (\"multiple passes\") from a single entry point. There are pros and cons to both approaches.\r\n - Our origin is on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.\r\n - This codebase is also optimized to yield decent performances with typical \"Debug\" builds settings.\r\n - Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).\r\n   If you get an assert, read the messages and comments around the assert.\r\n - C++: this is a very C-ish codebase: we don't rely on C++11, we don't include any C++ headers, and ImGui:: is a namespace.\r\n - C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.\r\n   See FAQ \"How can I use my own math types instead of ImVec2/ImVec4?\" for details about setting up imconfig.h for that.\r\n   However, imgui_internal.h can optionally export math operators for ImVec2/ImVec4, which we use in this codebase.\r\n - C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction (avoid using it in your code!).\r\n\r\n\r\n HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI\r\n ----------------------------------------------\r\n - Overwrite all the sources files except for imconfig.h (if you have modified your copy of imconfig.h)\r\n - Or maintain your own branch where you have imconfig.h modified as a top-most commit which you can regularly rebase over \"master\".\r\n - You can also use '#define IMGUI_USER_CONFIG \"my_config_file.h\" to redirect configuration to your own file.\r\n - Read the \"API BREAKING CHANGES\" section (below). This is where we list occasional API breaking changes.\r\n   If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed\r\n   from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will\r\n   likely be a comment about it. Please report any issue to the GitHub page!\r\n - To find out usage of old API, you can add '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in your configuration file.\r\n - Try to keep your copy of Dear ImGui reasonably up to date.\r\n\r\n\r\n GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE\r\n ---------------------------------------------------------------\r\n - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.\r\n - In the majority of cases you should be able to use unmodified backends files available in the backends/ folder.\r\n - Add the Dear ImGui source files + selected backend source files to your projects or using your preferred build system.\r\n   It is recommended you build and statically link the .cpp files as part of your project and NOT as a shared library (DLL).\r\n - You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating Dear ImGui types with your own maths types.\r\n - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.\r\n - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.\r\n   Effectively it means you can create widgets at any time in your code, regardless of considerations of being in \"update\" vs \"render\"\r\n   phases of your own application. All rendering information is stored into command-lists that you will retrieve after calling ImGui::Render().\r\n - Refer to the backends and demo applications in the examples/ folder for instruction on how to setup your code.\r\n - If you are running over a standard OS with a common graphics API, you should be able to use unmodified imgui_impl_*** files from the examples/ folder.\r\n\r\n\r\n HOW A SIMPLE APPLICATION MAY LOOK LIKE\r\n --------------------------------------\r\n EXHIBIT 1: USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder).\r\n The sub-folders in examples/ contain examples applications following this structure.\r\n\r\n     // Application init: create a dear imgui context, setup some options, load fonts\r\n     ImGui::CreateContext();\r\n     ImGuiIO& io = ImGui::GetIO();\r\n     // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.\r\n     // TODO: Fill optional fields of the io structure later.\r\n     // TODO: Load TTF/OTF fonts if you don't want to use the default font.\r\n\r\n     // Initialize helper Platform and Renderer backends (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp)\r\n     ImGui_ImplWin32_Init(hwnd);\r\n     ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);\r\n\r\n     // Application main loop\r\n     while (true)\r\n     {\r\n         // Feed inputs to dear imgui, start new frame\r\n         ImGui_ImplDX11_NewFrame();\r\n         ImGui_ImplWin32_NewFrame();\r\n         ImGui::NewFrame();\r\n\r\n         // Any application code here\r\n         ImGui::Text(\"Hello, world!\");\r\n\r\n         // Render dear imgui into screen\r\n         ImGui::Render();\r\n         ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());\r\n         g_pSwapChain->Present(1, 0);\r\n     }\r\n\r\n     // Shutdown\r\n     ImGui_ImplDX11_Shutdown();\r\n     ImGui_ImplWin32_Shutdown();\r\n     ImGui::DestroyContext();\r\n\r\n EXHIBIT 2: IMPLEMENTING CUSTOM BACKEND / CUSTOM ENGINE\r\n\r\n     // Application init: create a dear imgui context, setup some options, load fonts\r\n     ImGui::CreateContext();\r\n     ImGuiIO& io = ImGui::GetIO();\r\n     // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.\r\n     // TODO: Fill optional fields of the io structure later.\r\n     // TODO: Load TTF/OTF fonts if you don't want to use the default font.\r\n\r\n     // Build and load the texture atlas into a texture\r\n     // (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer)\r\n     int width, height;\r\n     unsigned char* pixels = NULL;\r\n     io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);\r\n\r\n     // At this point you've got the texture data and you need to upload that to your graphic system:\r\n     // After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.\r\n     // This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ for details about ImTextureID.\r\n     MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32)\r\n     io.Fonts->SetTexID((void*)texture);\r\n\r\n     // Application main loop\r\n     while (true)\r\n     {\r\n        // Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.\r\n        // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform Backends)\r\n        io.DeltaTime = 1.0f/60.0f;              // set the time elapsed since the previous frame (in seconds)\r\n        io.DisplaySize.x = 1920.0f;             // set the current display width\r\n        io.DisplaySize.y = 1280.0f;             // set the current display height here\r\n        io.AddMousePosEvent(mouse_x, mouse_y);  // update mouse position\r\n        io.AddMouseButtonEvent(0, mouse_b[0]);  // update mouse button states\r\n        io.AddMouseButtonEvent(1, mouse_b[1]);  // update mouse button states\r\n\r\n        // Call NewFrame(), after this point you can use ImGui::* functions anytime\r\n        // (So you want to try calling NewFrame() as early as you can in your main loop to be able to use Dear ImGui everywhere)\r\n        ImGui::NewFrame();\r\n\r\n        // Most of your application code here\r\n        ImGui::Text(\"Hello, world!\");\r\n        MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin(\"My window\"); ImGui::Text(\"Hello, world!\"); ImGui::End();\r\n        MyGameRender(); // may use any Dear ImGui functions as well!\r\n\r\n        // Render dear imgui, swap buffers\r\n        // (You want to try calling EndFrame/Render as late as you can, to be able to use Dear ImGui in your own game rendering code)\r\n        ImGui::EndFrame();\r\n        ImGui::Render();\r\n        ImDrawData* draw_data = ImGui::GetDrawData();\r\n        MyImGuiRenderFunction(draw_data);\r\n        SwapBuffers();\r\n     }\r\n\r\n     // Shutdown\r\n     ImGui::DestroyContext();\r\n\r\n To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest of your application,\r\n you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!\r\n Please read the FAQ and example applications for details about this!\r\n\r\n\r\n HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE\r\n ---------------------------------------------\r\n The backends in impl_impl_XXX.cpp files contain many working implementations of a rendering function.\r\n\r\n    void void MyImGuiRenderFunction(ImDrawData* draw_data)\r\n    {\r\n       // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled\r\n       // TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize\r\n       // TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize\r\n       // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.\r\n       ImVec2 clip_off = draw_data->DisplayPos;\r\n       for (int n = 0; n < draw_data->CmdListsCount; n++)\r\n       {\r\n          const ImDrawList* cmd_list = draw_data->CmdLists[n];\r\n          const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data;  // vertex buffer generated by Dear ImGui\r\n          const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data;   // index buffer generated by Dear ImGui\r\n          for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)\r\n          {\r\n             const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];\r\n             if (pcmd->UserCallback)\r\n             {\r\n                 pcmd->UserCallback(cmd_list, pcmd);\r\n             }\r\n             else\r\n             {\r\n                 // Project scissor/clipping rectangles into framebuffer space\r\n                 ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);\r\n                 ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);\r\n                 if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)\r\n                     continue;\r\n\r\n                 // We are using scissoring to clip some objects. All low-level graphics API should support it.\r\n                 // - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches\r\n                 //   (some elements visible outside their bounds) but you can fix that once everything else works!\r\n                 // - Clipping coordinates are provided in imgui coordinates space:\r\n                 //   - For a given viewport, draw_data->DisplayPos == viewport->Pos and draw_data->DisplaySize == viewport->Size\r\n                 //   - In a single viewport application, draw_data->DisplayPos == (0,0) and draw_data->DisplaySize == io.DisplaySize, but always use GetMainViewport()->Pos/Size instead of hardcoding those values.\r\n                 //   - In the interest of supporting multi-viewport applications (see 'docking' branch on github),\r\n                 //     always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space.\r\n                 // - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min)\r\n                 MyEngineSetScissor(clip_min.x, clip_min.y, clip_max.x, clip_max.y);\r\n\r\n                 // The texture for the draw call is specified by pcmd->GetTexID().\r\n                 // The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization.\r\n                 MyEngineBindTexture((MyTexture*)pcmd->GetTexID());\r\n\r\n                 // Render 'pcmd->ElemCount/3' indexed triangles.\r\n                 // By default the indices ImDrawIdx are 16-bit, you can change them to 32-bit in imconfig.h if your engine doesn't support 16-bit indices.\r\n                 MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer + pcmd->IdxOffset, vtx_buffer, pcmd->VtxOffset);\r\n             }\r\n          }\r\n       }\r\n    }\r\n\r\n\r\n USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS\r\n ------------------------------------------\r\n - The gamepad/keyboard navigation is fairly functional and keeps being improved.\r\n - Gamepad support is particularly useful to use Dear ImGui on a console system (e.g. PS4, Switch, XB1) without a mouse!\r\n - You can ask questions and report issues at https://github.com/ocornut/imgui/issues/787\r\n - The initial focus was to support game controllers, but keyboard is becoming increasingly and decently usable.\r\n - Keyboard:\r\n    - Application: Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard to enable.\r\n    - Internally: NewFrame() will automatically fill io.NavInputs[] based on backend's io.AddKeyEvent() calls.\r\n    - When keyboard navigation is active (io.NavActive + ImGuiConfigFlags_NavEnableKeyboard),\r\n      the io.WantCaptureKeyboard flag will be set. For more advanced uses, you may want to read from:\r\n       - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.\r\n       - io.NavVisible: true when the navigation cursor is visible (and usually goes false when mouse is used).\r\n       - or query focus information with e.g. IsWindowFocused(ImGuiFocusedFlags_AnyWindow), IsItemFocused() etc. functions.\r\n      Please reach out if you think the game vs navigation input sharing could be improved.\r\n - Gamepad:\r\n    - Application: Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad to enable.\r\n    - Backend: Set io.BackendFlags |= ImGuiBackendFlags_HasGamepad + call io.AddKeyEvent/AddKeyAnalogEvent() with ImGuiKey_Gamepad_XXX keys.\r\n      For analog values (0.0f to 1.0f), backend is responsible to handling a dead-zone and rescaling inputs accordingly.\r\n      Backend code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, etc.).\r\n    - Internally: NewFrame() will automatically fill io.NavInputs[] based on backend's io.AddKeyEvent() + io.AddKeyAnalogEvent() calls.\r\n    - BEFORE 1.87, BACKENDS USED TO WRITE DIRECTLY TO io.NavInputs[]. This is going to be obsoleted in the future. Please call io functions instead!\r\n    - You can download PNG/PSD files depicting the gamepad controls for common controllers at: http://dearimgui.org/controls_sheets\r\n    - If you need to share inputs between your game and the Dear ImGui interface, the easiest approach is to go all-or-nothing,\r\n      with a buttons combo to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.\r\n - Mouse:\r\n    - PS4/PS5 users: Consider emulating a mouse cursor with DualShock4 touch pad or a spare analog stick as a mouse-emulation fallback.\r\n    - Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + uSynergy.c (on your console/tablet/phone app) to share your PC mouse/keyboard.\r\n    - On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the ImGuiConfigFlags_NavEnableSetMousePos flag.\r\n      Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs dear imgui to move your mouse cursor along with navigation movements.\r\n      When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved.\r\n      When that happens your backend NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the backends in examples/ do that.\r\n      (If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, imgui will misbehave as it will see your mouse moving back and forth!)\r\n      (In a setup when you may not have easy control over the mouse cursor, e.g. uSynergy.c doesn't expose moving remote mouse cursor, you may want\r\n       to set a boolean to ignore your other external mouse positions until the external source is moved again.)\r\n\r\n\r\n API BREAKING CHANGES\r\n ====================\r\n\r\n Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.\r\n Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code.\r\n When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.\r\n You can read releases logs https://github.com/ocornut/imgui/releases for more details.\r\n\r\n - 2022/01/20 (1.87) - inputs: reworded gamepad IO.\r\n                        - Backend writing to io.NavInputs[]            -> backend should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values.\r\n - 2022/01/19 (1.87) - sliders, drags: removed support for legacy arithmetic operators (+,+-,*,/) when inputing text. This doesn't break any api/code but a feature that used to be accessible by end-users (which seemingly no one used).\r\n - 2022/01/17 (1.87) - inputs: reworked mouse IO.\r\n                        - Backend writing to io.MousePos               -> backend should call io.AddMousePosEvent()\r\n                        - Backend writing to io.MouseDown[]            -> backend should call io.AddMouseButtonEvent()\r\n                        - Backend writing to io.MouseWheel             -> backend should call io.AddMouseWheelEvent()\r\n                        - Backend writing to io.MouseHoveredViewport   -> backend should call io.AddMouseViewportEvent() [Docking branch w/ multi-viewports only]\r\n - 2022/01/10 (1.87) - inputs: reworked keyboard IO. Removed io.KeyMap[], io.KeysDown[] in favor of calling io.AddKeyEvent(). Removed GetKeyIndex(), now unecessary. All IsKeyXXX() functions now take ImGuiKey values. All features are still functional until IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Read Changelog and Release Notes for details.\r\n                        - IsKeyPressed(MY_NATIVE_KEY_XXX)              -> use IsKeyPressed(ImGuiKey_XXX)\r\n                        - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX))      -> use IsKeyPressed(ImGuiKey_XXX)\r\n                        - Backend writing to io.KeyMap[],io.KeysDown[] -> backend should call io.AddKeyEvent()\r\n                        - Backend writing to io.KeyCtrl, io.KeyShift.. -> backend should call io.AddKeyEvent() with ImGuiKey_ModXXX values. *IF YOU PULLED CODE BETWEEN 2021/01/10 and 2021/01/27: We used to have a io.AddKeyModsEvent() function which was now replaced by io.AddKeyEvent() with ImGuiKey_ModXXX values.*\r\n                     - one case won't work with backward compatibility: if your custom backend used ImGuiKey as mock native indices (e.g. \"io.KeyMap[ImGuiKey_A] = ImGuiKey_A\") because those values are now larger than the legacy KeyDown[] array. Will assert.\r\n                     - inputs: added ImGuiKey_ModCtrl/ImGuiKey_ModShift/ImGuiKey_ModAlt/ImGuiKey_ModSuper values to submit keyboard modifiers using io.AddKeyEvent(), instead of writing directly to io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper.\r\n - 2022/01/05 (1.87) - inputs: renamed ImGuiKey_KeyPadEnter to ImGuiKey_KeypadEnter to align with new symbols. Kept redirection enum.\r\n - 2022/01/05 (1.87) - removed io.ImeSetInputScreenPosFn() in favor of more flexible io.SetPlatformImeDataFn(). Removed 'void* io.ImeWindowHandle' in favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.\r\n - 2022/01/01 (1.87) - commented out redirecting functions/enums names that were marked obsolete in 1.69, 1.70, 1.71, 1.72 (March-July 2019)\r\n                        - ImGui::SetNextTreeNodeOpen()        -> use ImGui::SetNextItemOpen()\r\n                        - ImGui::GetContentRegionAvailWidth() -> use ImGui::GetContentRegionAvail().x\r\n                        - ImGui::TreeAdvanceToLabelPos()      -> use ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetTreeNodeToLabelSpacing());\r\n                        - ImFontAtlas::CustomRect             -> use ImFontAtlasCustomRect\r\n                        - ImGuiColorEditFlags_RGB/HSV/HEX     -> use ImGuiColorEditFlags_DisplayRGB/HSV/Hex\r\n - 2021/12/20 (1.86) - backends: removed obsolete Marmalade backend (imgui_impl_marmalade.cpp) + example. Find last supported version at https://github.com/ocornut/imgui/wiki/Bindings\r\n - 2021/11/04 (1.86) - removed CalcListClipping() function. Prefer using ImGuiListClipper which can return non-contiguous ranges. Please open an issue if you think you really need this function.\r\n - 2021/08/23 (1.85) - removed GetWindowContentRegionWidth() function. keep inline redirection helper. can use 'GetWindowContentRegionMax().x - GetWindowContentRegionMin().x' instead for generally 'GetContentRegionAvail().x' is more useful.\r\n - 2021/07/26 (1.84) - commented out redirecting functions/enums names that were marked obsolete in 1.67 and 1.69 (March 2019):\r\n                        - ImGui::GetOverlayDrawList() -> use ImGui::GetForegroundDrawList()\r\n                        - ImFont::GlyphRangesBuilder  -> use ImFontGlyphRangesBuilder\r\n - 2021/05/19 (1.83) - backends: obsoleted direct access to ImDrawCmd::TextureId in favor of calling ImDrawCmd::GetTexID().\r\n                        - if you are using official backends from the source tree: you have nothing to do.\r\n                        - if you have copied old backend code or using your own: change access to draw_cmd->TextureId to draw_cmd->GetTexID().\r\n - 2021/03/12 (1.82) - upgraded ImDrawList::AddRect(), AddRectFilled(), PathRect() to use ImDrawFlags instead of ImDrawCornersFlags.\r\n                        - ImDrawCornerFlags_TopLeft  -> use ImDrawFlags_RoundCornersTopLeft\r\n                        - ImDrawCornerFlags_BotRight -> use ImDrawFlags_RoundCornersBottomRight\r\n                        - ImDrawCornerFlags_None     -> use ImDrawFlags_RoundCornersNone etc.\r\n                       flags now sanely defaults to 0 instead of 0x0F, consistent with all other flags in the API.\r\n                       breaking: the default with rounding > 0.0f is now \"round all corners\" vs old implicit \"round no corners\":\r\n                        - rounding == 0.0f + flags == 0 --> meant no rounding  --> unchanged (common use)\r\n                        - rounding  > 0.0f + flags != 0 --> meant rounding     --> unchanged (common use)\r\n                        - rounding == 0.0f + flags != 0 --> meant no rounding  --> unchanged (unlikely use)\r\n                        - rounding  > 0.0f + flags == 0 --> meant no rounding  --> BREAKING (unlikely use): will now round all corners --> use ImDrawFlags_RoundCornersNone or rounding == 0.0f.\r\n                       this ONLY matters for hard coded use of 0 + rounding > 0.0f. Use of named ImDrawFlags_RoundCornersNone (new) or ImDrawCornerFlags_None (old) are ok.\r\n                       the old ImDrawCornersFlags used awkward default values of ~0 or 0xF (4 lower bits set) to signify \"round all corners\" and we sometimes encouraged using them as shortcuts.\r\n                       legacy path still support use of hard coded ~0 or any value from 0x1 or 0xF. They will behave the same with legacy paths enabled (will assert otherwise).\r\n - 2021/03/11 (1.82) - removed redirecting functions/enums names that were marked obsolete in 1.66 (September 2018):\r\n                        - ImGui::SetScrollHere()              -> use ImGui::SetScrollHereY()\r\n - 2021/03/11 (1.82) - clarified that ImDrawList::PathArcTo(), ImDrawList::PathArcToFast() won't render with radius < 0.0f. Previously it sorts of accidentally worked but would generally lead to counter-clockwise paths and have an effect on anti-aliasing.\r\n - 2021/03/10 (1.82) - upgraded ImDrawList::AddPolyline() and PathStroke() \"bool closed\" parameter to \"ImDrawFlags flags\". The matching ImDrawFlags_Closed value is guaranteed to always stay == 1 in the future.\r\n - 2021/02/22 (1.82) - (*undone in 1.84*) win32+mingw: Re-enabled IME functions by default even under MinGW. In July 2016, issue #738 had me incorrectly disable those default functions for MinGW. MinGW users should: either link with -limm32, either set their imconfig file  with '#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS'.\r\n - 2021/02/17 (1.82) - renamed rarely used style.CircleSegmentMaxError (old default = 1.60f) to style.CircleTessellationMaxError (new default = 0.30f) as the meaning of the value changed.\r\n - 2021/02/03 (1.81) - renamed ListBoxHeader(const char* label, ImVec2 size) to BeginListBox(). Kept inline redirection function (will obsolete).\r\n                     - removed ListBoxHeader(const char* label, int items_count, int height_in_items = -1) in favor of specifying size. Kept inline redirection function (will obsolete).\r\n                     - renamed ListBoxFooter() to EndListBox(). Kept inline redirection function (will obsolete).\r\n - 2021/01/26 (1.81) - removed ImGuiFreeType::BuildFontAtlas(). Kept inline redirection function. Prefer using '#define IMGUI_ENABLE_FREETYPE', but there's a runtime selection path available too. The shared extra flags parameters (very rarely used) are now stored in ImFontAtlas::FontBuilderFlags.\r\n                     - renamed ImFontConfig::RasterizerFlags (used by FreeType) to ImFontConfig::FontBuilderFlags.\r\n                     - renamed ImGuiFreeType::XXX flags to ImGuiFreeTypeBuilderFlags_XXX for consistency with other API.\r\n - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.63 (August 2018):\r\n                        - ImGui::IsItemDeactivatedAfterChange() -> use ImGui::IsItemDeactivatedAfterEdit().\r\n                        - ImGuiCol_ModalWindowDarkening       -> use ImGuiCol_ModalWindowDimBg\r\n                        - ImGuiInputTextCallback              -> use ImGuiTextEditCallback\r\n                        - ImGuiInputTextCallbackData          -> use ImGuiTextEditCallbackData\r\n - 2020/12/21 (1.80) - renamed ImDrawList::AddBezierCurve() to AddBezierCubic(), and PathBezierCurveTo() to PathBezierCubicCurveTo(). Kept inline redirection function (will obsolete).\r\n - 2020/12/04 (1.80) - added imgui_tables.cpp file! Manually constructed project files will need the new file added!\r\n - 2020/11/18 (1.80) - renamed undocumented/internals ImGuiColumnsFlags_* to ImGuiOldColumnFlags_* in prevision of incoming Tables API.\r\n - 2020/11/03 (1.80) - renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures\r\n - 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/.\r\n - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018):\r\n                        - io.RenderDrawListsFn pointer        -> use ImGui::GetDrawData() value and call the render function of your backend\r\n                        - ImGui::IsAnyWindowFocused()         -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow)\r\n                        - ImGui::IsAnyWindowHovered()         -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow)\r\n                        - ImGuiStyleVar_Count_                -> use ImGuiStyleVar_COUNT\r\n                        - ImGuiMouseCursor_Count_             -> use ImGuiMouseCursor_COUNT\r\n                      - removed redirecting functions names that were marked obsolete in 1.61 (May 2018):\r\n                        - InputFloat (... int decimal_precision ...) -> use InputFloat (... const char* format ...) with format = \"%.Xf\" where X is your value for decimal_precision.\r\n                        - same for InputFloat2()/InputFloat3()/InputFloat4() variants taking a `int decimal_precision` parameter.\r\n - 2020/10/05 (1.79) - removed ImGuiListClipper: Renamed constructor parameters which created an ambiguous alternative to using the ImGuiListClipper::Begin() function, with misleading edge cases (note: imgui_memory_editor <0.40 from imgui_club/ used this old clipper API. Update your copy if needed).\r\n - 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently).\r\n - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton.\r\n - 2020/09/21 (1.79) - renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), reverting the change from 1.77. For varieties of reason this is more self-explanatory.\r\n - 2020/09/21 (1.79) - removed return value from OpenPopupOnItemClick() - returned true on mouse release on an item - because it is inconsistent with other popup APIs and makes others misleading. It's also and unnecessary: you can use IsWindowAppearing() after BeginPopup() for a similar result.\r\n - 2020/09/17 (1.79) - removed ImFont::DisplayOffset in favor of ImFontConfig::GlyphOffset. DisplayOffset was applied after scaling and not very meaningful/useful outside of being needed by the default ProggyClean font. If you scaled this value after calling AddFontDefault(), this is now done automatically. It was also getting in the way of better font scaling, so let's get rid of it now!\r\n - 2020/08/17 (1.78) - obsoleted use of the trailing 'float power=1.0f' parameter for DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN(), VSliderFloat() and VSliderScalar().\r\n                       replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags).\r\n                       worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions:\r\n                       - if you omitted the 'power' parameter (likely!), you are not affected.\r\n                       - if you set the 'power' parameter to 1.0f (same as previous default value): 1/ your compiler may warn on float>int conversion, 2/ everything else will work. 3/ you can replace the 1.0f value with 0 to fix the warning, and be technically correct.\r\n                       - if you set the 'power' parameter to >1.0f (to enable non-linear editing): 1/ your compiler may warn on float>int conversion, 2/ code will assert at runtime, 3/ in case asserts are disabled, the code will not crash and enable the _Logarithmic flag. 4/ you can replace the >1.0f value with ImGuiSliderFlags_Logarithmic to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f.\r\n                       see https://github.com/ocornut/imgui/issues/3361 for all details.\r\n                       kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version was removed directly as they were most unlikely ever used.\r\n                       for shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`.\r\n                     - obsoleted use of v_min > v_max in DragInt, DragFloat, DragScalar to lock edits (introduced in 1.73, was not demoed nor documented very), will be replaced by a more generic ReadOnly feature. You may use the ImGuiSliderFlags_ReadOnly internal flag in the meantime.\r\n - 2020/06/23 (1.77) - removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems.\r\n - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). [NOTE: THIS WAS REVERTED IN 1.79]\r\n - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017.\r\n - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular().\r\n - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more.\r\n - 2019/12/17 (1.75) - [undid this change in 1.76] made Columns() limited to 64 columns by asserting above that limit. While the current code technically supports it, future code may not so we're putting the restriction ahead.\r\n - 2019/12/13 (1.75) - [imgui_internal.h] changed ImRect() default constructor initializes all fields to 0.0f instead of (FLT_MAX,FLT_MAX,-FLT_MAX,-FLT_MAX). If you used ImRect::Add() to create bounding boxes by adding multiple points into it, you may need to fix your initial value.\r\n - 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017):\r\n                       - ShowTestWindow()                    -> use ShowDemoWindow()\r\n                       - IsRootWindowFocused()               -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow)\r\n                       - IsRootWindowOrAnyChildFocused()     -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)\r\n                       - SetNextWindowContentWidth(w)        -> use SetNextWindowContentSize(ImVec2(w, 0.0f)\r\n                       - GetItemsLineHeightWithSpacing()     -> use GetFrameHeightWithSpacing()\r\n                       - ImGuiCol_ChildWindowBg              -> use ImGuiCol_ChildBg\r\n                       - ImGuiStyleVar_ChildWindowRounding   -> use ImGuiStyleVar_ChildRounding\r\n                       - ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap\r\n                       - IMGUI_DISABLE_TEST_WINDOWS          -> use IMGUI_DISABLE_DEMO_WINDOWS\r\n - 2019/12/08 (1.75) - obsoleted calling ImDrawList::PrimReserve() with a negative count (which was vaguely documented and rarely if ever used). Instead, we added an explicit PrimUnreserve() API.\r\n - 2019/12/06 (1.75) - removed implicit default parameter to IsMouseDragging(int button = 0) to be consistent with other mouse functions (none of the other functions have it).\r\n - 2019/11/21 (1.74) - ImFontAtlas::AddCustomRectRegular() now requires an ID larger than 0x110000 (instead of 0x10000) to conform with supporting Unicode planes 1-16 in a future update. ID below 0x110000 will now assert.\r\n - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency.\r\n - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency.\r\n - 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017):\r\n                       - Begin() [old 5 args version]        -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed\r\n                       - IsRootWindowOrAnyChildHovered()     -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows)\r\n                       - AlignFirstTextHeightToWidgets()     -> use AlignTextToFramePadding()\r\n                       - SetNextWindowPosCenter()            -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f)\r\n                       - ImFont::Glyph                       -> use ImFontGlyph\r\n - 2019/10/14 (1.74) - inputs: Fixed a miscalculation in the keyboard/mouse \"typematic\" repeat delay/rate calculation, used by keys and e.g. repeating mouse buttons as well as the GetKeyPressedAmount() function.\r\n                       if you were using a non-default value for io.KeyRepeatRate (previous default was 0.250), you can add +io.KeyRepeatDelay to it to compensate for the fix.\r\n                       The function was triggering on: 0.0 and (delay+rate*N) where (N>=1). Fixed formula responds to (N>=0). Effectively it made io.KeyRepeatRate behave like it was set to (io.KeyRepeatRate + io.KeyRepeatDelay).\r\n                       If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you.\r\n - 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete).\r\n - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete).\r\n - 2019/06/14 (1.72) - removed redirecting functions/enums names that were marked obsolete in 1.51 (June 2017): ImGuiCol_Column*, ImGuiSetCond_*, IsItemHoveredRect(), IsPosHoveringAnyWindow(), IsMouseHoveringAnyWindow(), IsMouseHoveringWindow(), IMGUI_ONCE_UPON_A_FRAME. Grep this log for details and new names, or see how they were implemented until 1.71.\r\n - 2019/06/07 (1.71) - rendering of child window outer decorations (bg color, border, scrollbars) is now performed as part of the parent window. If you have\r\n                       overlapping child windows in a same parent, and relied on their relative z-order to be mapped to their submission order, this will affect your rendering.\r\n                       This optimization is disabled if the parent window has no visual output, because it appears to be the most common situation leading to the creation of overlapping child windows.\r\n                       Please reach out if you are affected.\r\n - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete).\r\n - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c).\r\n - 2019/04/29 (1.70) - improved ImDrawList thick strokes (>1.0f) preserving correct thickness up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, they will appear thicker now.\r\n - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).\r\n - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).\r\n - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).\r\n - 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with an arbitrarily small value!\r\n - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).\r\n - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!\r\n - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete).\r\n - 2018/12/20 (1.67) - made it illegal to call Begin(\"\") with an empty string. This somehow half-worked before but had various undesirable side-effects.\r\n - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.\r\n - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.\r\n - 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).\r\n - 2018/09/06 (1.65) - renamed stb_truetype.h to imstb_truetype.h, stb_textedit.h to imstb_textedit.h, and stb_rect_pack.h to imstb_rectpack.h.\r\n                       If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.\r\n - 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)\r\n - 2018/08/31 (1.64) - added imgui_widgets.cpp file, extracted and moved widgets code out of imgui.cpp into imgui_widgets.cpp. Re-ordered some of the code remaining in imgui.cpp.\r\n                       NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.\r\n                       Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.\r\n - 2018/08/22 (1.63) - renamed IsItemDeactivatedAfterChange() to IsItemDeactivatedAfterEdit() for consistency with new IsItemEdited() API. Kept redirection function (will obsolete soonish as IsItemDeactivatedAfterChange() is very recent).\r\n - 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).\r\n - 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).\r\n - 2018/08/01 (1.63) - removed per-window ImGuiWindowFlags_ResizeFromAnySide beta flag in favor of a global io.ConfigResizeWindowsFromEdges [update 1.67 renamed to ConfigWindowsResizeFromEdges] to enable the feature.\r\n - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.\r\n - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.\r\n - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).\r\n - 2018/06/08 (1.62) - examples: the imgui_impl_XXX files have been split to separate platform (Win32, GLFW, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan,  etc.).\r\n                       old backends will still work as is, however prefer using the separated backends as they will be updated to support multi-viewports.\r\n                       when adopting new backends follow the main.cpp code of your preferred examples/ folder to know which functions to call.\r\n                       in particular, note that old backends called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.\r\n - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.\r\n - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.\r\n - 2018/05/03 (1.61) - DragInt(): the default compile-time format string has been changed from \"%.0f\" to \"%d\", as we are not using integers internally any more.\r\n                       If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.\r\n                       To honor backward-compatibility, the DragInt() code will currently parse and modify format strings to replace %*f with %d, giving time to users to upgrade their code.\r\n                       If you have IMGUI_DISABLE_OBSOLETE_FUNCTIONS enabled, the code will instead assert! You may run a reg-exp search on your codebase for e.g. \"DragInt.*%f\" to help you find them.\r\n - 2018/04/28 (1.61) - obsoleted InputFloat() functions taking an optional \"int decimal_precision\" in favor of an equivalent and more flexible \"const char* format\",\r\n                       consistent with other functions. Kept redirection functions (will obsolete).\r\n - 2018/04/09 (1.61) - IM_DELETE() helper function added in 1.60 doesn't clear the input _pointer_ reference, more consistent with expectation and allows passing r-value.\r\n - 2018/03/20 (1.60) - renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some backend ahead of merging the Nav branch).\r\n - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.\r\n - 2018/03/08 (1.60) - changed ImFont::DisplayOffset.y to default to 0 instead of +1. Fixed rounding of Ascent/Descent to match TrueType renderer. If you were adding or subtracting to ImFont::DisplayOffset check if your fonts are correctly aligned vertically.\r\n - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.\r\n - 2018/02/18 (1.60) - BeginDragDropSource(): temporarily removed the optional mouse_button=0 parameter because it is not really usable in many situations at the moment.\r\n - 2018/02/16 (1.60) - obsoleted the io.RenderDrawListsFn callback, you can call your graphics engine render function after ImGui::Render(). Use ImGui::GetDrawData() to retrieve the ImDrawData* to display.\r\n - 2018/02/07 (1.60) - reorganized context handling to be more explicit,\r\n                       - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.\r\n                       - removed Shutdown() function, as DestroyContext() serve this purpose.\r\n                       - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.\r\n                       - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.\r\n                       - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.\r\n - 2018/01/31 (1.60) - moved sample TTF files from extra_fonts/ to misc/fonts/. If you loaded files directly from the imgui repo you may need to update your paths.\r\n - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).\r\n - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).\r\n - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.\r\n - 2017/12/29 (1.60) - removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it it's easy to replicate on your side.\r\n - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).\r\n - 2017/12/21 (1.53) - ImDrawList: renamed style.AntiAliasedShapes to style.AntiAliasedFill for consistency and as a way to explicitly break code that manipulate those flag at runtime. You can now manipulate ImDrawList::Flags\r\n - 2017/12/21 (1.53) - ImDrawList: removed 'bool anti_aliased = true' final parameter of ImDrawList::AddPolyline() and ImDrawList::AddConvexPolyFilled(). Prefer manipulating ImDrawList::Flags if you need to toggle them during the frame.\r\n - 2017/12/14 (1.53) - using the ImGuiWindowFlags_NoScrollWithMouse flag on a child window forwards the mouse wheel event to the parent window, unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set.\r\n - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).\r\n - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).\r\n                     - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).\r\n - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).\r\n - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).\r\n - 2017/11/27 (1.53) - renamed ImGuiTextBuffer::append() helper to appendf(), appendv() to appendfv(). If you copied the 'Log' demo in your code, it uses appendv() so that needs to be renamed.\r\n - 2017/11/18 (1.53) - Style, Begin: removed ImGuiWindowFlags_ShowBorders window flag. Borders are now fully set up in the ImGuiStyle structure (see e.g. style.FrameBorderSize, style.WindowBorderSize). Use ImGui::ShowStyleEditor() to look them up.\r\n                       Please note that the style system will keep evolving (hopefully stabilizing in Q1 2018), and so custom styles will probably subtly break over time. It is recommended you use the StyleColorsClassic(), StyleColorsDark(), StyleColorsLight() functions.\r\n - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.\r\n - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.\r\n - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.\r\n - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);\r\n - 2017/10/24 (1.52) - renamed IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS to IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS for consistency.\r\n - 2017/10/20 (1.52) - changed IsWindowHovered() default parameters behavior to return false if an item is active in another window (e.g. click-dragging item from another window to this window). You can use the newly introduced IsWindowHovered() flags to requests this specific behavior if you need it.\r\n - 2017/10/20 (1.52) - marked IsItemHoveredRect()/IsMouseHoveringWindow() as obsolete, in favor of using the newly introduced flags for IsItemHovered() and IsWindowHovered(). See https://github.com/ocornut/imgui/issues/1382 for details.\r\n                       removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.\r\n                         IsItemHoveredRect()        --> IsItemHovered(ImGuiHoveredFlags_RectOnly)\r\n                         IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow)\r\n                         IsMouseHoveringWindow()    --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior]\r\n - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!\r\n - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).\r\n - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete).\r\n - 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete).\r\n - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your backend if you need to support unavailable mouse, make sure to replace \"io.MousePos = ImVec2(-1,-1)\" with \"io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)\".\r\n - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!\r\n                     - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).\r\n                     - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).\r\n - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.\r\n - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an \"ambiguous call\" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix.\r\n - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type.\r\n - 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely.\r\n - 2017/08/13 (1.51) - renamed ImGuiCol_Column to ImGuiCol_Separator, ImGuiCol_ColumnHovered to ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive to ImGuiCol_SeparatorActive. Kept redirection enums (will obsolete).\r\n - 2017/08/11 (1.51) - renamed ImGuiSetCond_Always to ImGuiCond_Always, ImGuiSetCond_Once to ImGuiCond_Once, ImGuiSetCond_FirstUseEver to ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing to ImGuiCond_Appearing. Kept redirection enums (will obsolete).\r\n - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().\r\n - 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu.\r\n                     - changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under \"Color/Picker Widgets\", to understand the various new options.\r\n                     - changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0, 0))'\r\n - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse\r\n - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.\r\n - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.\r\n - 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetID() and use it instead of passing string to BeginChild().\r\n - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.\r\n - 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc.\r\n - 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully, breakage should be minimal.\r\n - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.\r\n                       If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you, otherwise if <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.\r\n                       This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color:\r\n                       ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col) { float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a; return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a); }\r\n                       If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color.\r\n - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().\r\n - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.\r\n - 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the \"default_open = true\" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen).\r\n - 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDrawList::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer.\r\n - 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref GitHub issue #337).\r\n - 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337)\r\n - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).\r\n - 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert.\r\n - 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you.\r\n - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.\r\n - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.\r\n - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.\r\n                       GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side.\r\n                       GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out!\r\n - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize\r\n - 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project.\r\n - 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason\r\n - 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure.\r\n                       you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.\r\n - 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost.\r\n                       this necessary change will break your rendering function! the fix should be very easy. sorry for that :(\r\n                     - if you are using a vanilla copy of one of the imgui_impl_XXX.cpp provided in the example, you just need to update your copy and you can ignore the rest.\r\n                     - the signature of the io.RenderDrawListsFn handler has changed!\r\n                       old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)\r\n                       new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).\r\n                         parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'\r\n                         ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.\r\n                         ImDrawCmd:  'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.\r\n                     - each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer.\r\n                     - if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering!\r\n                     - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!\r\n - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.\r\n - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).\r\n - 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount.\r\n - 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence\r\n - 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely used. Sorry!\r\n - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).\r\n - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).\r\n - 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons.\r\n - 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the \"open\" state of a popup. BeginPopup() returns true if the popup is opened.\r\n - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).\r\n - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.\r\n - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API\r\n - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.\r\n - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.\r\n - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.\r\n - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing\r\n - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.\r\n - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)\r\n - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.\r\n - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.\r\n - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.\r\n - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior\r\n - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()\r\n - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)\r\n - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.\r\n - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.\r\n - 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.\r\n                       - old:  const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..];\r\n                       - new:  unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->SetTexID(YourTexIdentifier);\r\n                       you now have more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs. It is now recommended that you sample the font texture with bilinear interpolation.\r\n - 2015/01/11 (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to call io.Fonts->SetTexID()\r\n - 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)\r\n - 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets\r\n - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)\r\n - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)\r\n - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility\r\n - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()\r\n - 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly)\r\n - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)\r\n - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()\r\n - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn\r\n - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)\r\n - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite\r\n - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes\r\n\r\n\r\n FREQUENTLY ASKED QUESTIONS (FAQ)\r\n ================================\r\n\r\n Read all answers online:\r\n   https://www.dearimgui.org/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url)\r\n Read all answers locally (with a text editor or ideally a Markdown viewer):\r\n   docs/FAQ.md\r\n Some answers are copied down here to facilitate searching in code.\r\n\r\n Q&A: Basics\r\n ===========\r\n\r\n Q: Where is the documentation?\r\n A: This library is poorly documented at the moment and expects the user to be acquainted with C/C++.\r\n    - Run the examples/ and explore them.\r\n    - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.\r\n    - The demo covers most features of Dear ImGui, so you can read the code and see its output.\r\n    - See documentation and comments at the top of imgui.cpp + effectively imgui.h.\r\n    - Dozens of standalone example applications using e.g. OpenGL/DirectX are provided in the\r\n      examples/ folder to explain how to integrate Dear ImGui with your own engine/application.\r\n    - The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links.\r\n    - The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful.\r\n    - Your programming IDE is your friend, find the type or function declaration to find comments\r\n      associated with it.\r\n\r\n Q: What is this library called?\r\n Q: Which version should I get?\r\n >> This library is called \"Dear ImGui\", please don't call it \"ImGui\" :)\r\n >> See https://www.dearimgui.org/faq for details.\r\n\r\n Q&A: Integration\r\n ================\r\n\r\n Q: How to get started?\r\n A: Read 'PROGRAMMER GUIDE' above. Read examples/README.txt.\r\n\r\n Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?\r\n A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!\r\n >> See https://www.dearimgui.org/faq for a fully detailed answer. You really want to read this.\r\n\r\n Q. How can I enable keyboard controls?\r\n Q: How can I use this without a mouse, without a keyboard or without a screen? (gamepad, input share, remote display)\r\n Q: I integrated Dear ImGui in my engine and little squares are showing instead of text...\r\n Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around...\r\n Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries...\r\n >> See https://www.dearimgui.org/faq\r\n\r\n Q&A: Usage\r\n ----------\r\n\r\n Q: About the ID Stack system..\r\n   - Why is my widget not reacting when I click on it?\r\n   - How can I have widgets with an empty label?\r\n   - How can I have multiple widgets with the same label?\r\n   - How can I have multiple windows with the same label?\r\n Q: How can I display an image? What is ImTextureID, how does it works?\r\n Q: How can I use my own math types instead of ImVec2/ImVec4?\r\n Q: How can I interact with standard C++ types (such as std::string and std::vector)?\r\n Q: How can I display custom shapes? (using low-level ImDrawList API)\r\n >> See https://www.dearimgui.org/faq\r\n\r\n Q&A: Fonts, Text\r\n ================\r\n\r\n Q: How should I handle DPI in my application?\r\n Q: How can I load a different font than the default?\r\n Q: How can I easily use icons in my application?\r\n Q: How can I load multiple fonts?\r\n Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?\r\n >> See https://www.dearimgui.org/faq and https://github.com/ocornut/imgui/edit/master/docs/FONTS.md\r\n\r\n Q&A: Concerns\r\n =============\r\n\r\n Q: Who uses Dear ImGui?\r\n Q: Can you create elaborate/serious tools with Dear ImGui?\r\n Q: Can you reskin the look of Dear ImGui?\r\n Q: Why using C++ (as opposed to C)?\r\n >> See https://www.dearimgui.org/faq\r\n\r\n Q&A: Community\r\n ==============\r\n\r\n Q: How can I help?\r\n A: - Businesses: please reach out to \"contact AT dearimgui.com\" if you work in a place using Dear ImGui!\r\n      We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts.\r\n      This is among the most useful thing you can do for Dear ImGui. With increased funding, we can hire more people working on this project.\r\n    - Individuals: you can support continued development via PayPal donations. See README.\r\n    - If you are experienced with Dear ImGui and C++, look at the GitHub issues, look at the Wiki, read docs/TODO.txt\r\n      and see how you want to help and can help!\r\n    - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.\r\n      You may post screenshot or links in the gallery threads. Visuals are ideal as they inspire other programmers.\r\n      But even without visuals, disclosing your use of dear imgui helps the library grow credibility, and help other teams and programmers with taking decisions.\r\n    - If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues (on GitHub or privately).\r\n\r\n*/\r\n\r\n//-------------------------------------------------------------------------\r\n// [SECTION] INCLUDES\r\n//-------------------------------------------------------------------------\r\n\r\n#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)\r\n#define _CRT_SECURE_NO_WARNINGS\r\n#endif\r\n\r\n#include \"imgui.h\"\r\n#ifndef IMGUI_DISABLE\r\n\r\n#ifndef IMGUI_DEFINE_MATH_OPERATORS\r\n#define IMGUI_DEFINE_MATH_OPERATORS\r\n#endif\r\n#include \"imgui_internal.h\"\r\n\r\n// System includes\r\n#include <ctype.h>      // toupper\r\n#include <stdio.h>      // vsnprintf, sscanf, printf\r\n#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier\r\n#include <stddef.h>     // intptr_t\r\n#else\r\n#include <stdint.h>     // intptr_t\r\n#endif\r\n\r\n// [Windows] On non-Visual Studio compilers, we default to IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS unless explicitly enabled\r\n#if defined(_WIN32) && !defined(_MSC_VER) && !defined(IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)\r\n#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS\r\n#endif\r\n\r\n// [Windows] OS specific includes (optional)\r\n#if defined(_WIN32) && defined(IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)\r\n#define IMGUI_DISABLE_WIN32_FUNCTIONS\r\n#endif\r\n#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)\r\n#ifndef WIN32_LEAN_AND_MEAN\r\n#define WIN32_LEAN_AND_MEAN\r\n#endif\r\n#ifndef NOMINMAX\r\n#define NOMINMAX\r\n#endif\r\n#ifndef __MINGW32__\r\n#include <Windows.h>        // _wfopen, OpenClipboard\r\n#else\r\n#include <windows.h>\r\n#endif\r\n#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) // UWP doesn't have all Win32 functions\r\n#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS\r\n#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS\r\n#endif\r\n#endif\r\n\r\n// [Apple] OS specific includes\r\n#if defined(__APPLE__)\r\n#include <TargetConditionals.h>\r\n#endif\r\n\r\n// Visual Studio warnings\r\n#ifdef _MSC_VER\r\n#pragma warning (disable: 4127)             // condition expression is constant\r\n#pragma warning (disable: 4996)             // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen\r\n#if defined(_MSC_VER) && _MSC_VER >= 1922   // MSVC 2019 16.2 or later\r\n#pragma warning (disable: 5054)             // operator '|': deprecated between enumerations of different types\r\n#endif\r\n#pragma warning (disable: 26451)            // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to a 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2).\r\n#pragma warning (disable: 26495)            // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6).\r\n#pragma warning (disable: 26812)            // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).\r\n#endif\r\n\r\n// Clang/GCC warnings with -Weverything\r\n#if defined(__clang__)\r\n#if __has_warning(\"-Wunknown-warning-option\")\r\n#pragma clang diagnostic ignored \"-Wunknown-warning-option\"         // warning: unknown warning group 'xxx'                      // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great!\r\n#endif\r\n#pragma clang diagnostic ignored \"-Wunknown-pragmas\"                // warning: unknown warning group 'xxx'\r\n#pragma clang diagnostic ignored \"-Wold-style-cast\"                 // warning: use of old-style cast                            // yes, they are more terse.\r\n#pragma clang diagnostic ignored \"-Wfloat-equal\"                    // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok.\r\n#pragma clang diagnostic ignored \"-Wformat-nonliteral\"              // warning: format string is not a string literal            // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code.\r\n#pragma clang diagnostic ignored \"-Wexit-time-destructors\"          // warning: declaration requires an exit-time destructor     // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals.\r\n#pragma clang diagnostic ignored \"-Wglobal-constructors\"            // warning: declaration requires a global destructor         // similar to above, not sure what the exact difference is.\r\n#pragma clang diagnostic ignored \"-Wsign-conversion\"                // warning: implicit conversion changes signedness\r\n#pragma clang diagnostic ignored \"-Wformat-pedantic\"                // warning: format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic.\r\n#pragma clang diagnostic ignored \"-Wint-to-void-pointer-cast\"       // warning: cast to 'void *' from smaller integer type 'int'\r\n#pragma clang diagnostic ignored \"-Wzero-as-null-pointer-constant\"  // warning: zero as null pointer constant                    // some standard header variations use #define NULL 0\r\n#pragma clang diagnostic ignored \"-Wdouble-promotion\"               // warning: implicit conversion from 'float' to 'double' when passing argument to function  // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.\r\n#pragma clang diagnostic ignored \"-Wimplicit-int-float-conversion\"  // warning: implicit conversion from 'xxx' to 'float' may lose precision\r\n#elif defined(__GNUC__)\r\n// We disable -Wpragmas because GCC doesn't provide an has_warning equivalent and some forks/patches may not following the warning/version association.\r\n#pragma GCC diagnostic ignored \"-Wpragmas\"                  // warning: unknown option after '#pragma GCC diagnostic' kind\r\n#pragma GCC diagnostic ignored \"-Wunused-function\"          // warning: 'xxxx' defined but not used\r\n#pragma GCC diagnostic ignored \"-Wint-to-pointer-cast\"      // warning: cast to pointer from integer of different size\r\n#pragma GCC diagnostic ignored \"-Wformat\"                   // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'\r\n#pragma GCC diagnostic ignored \"-Wdouble-promotion\"         // warning: implicit conversion from 'float' to 'double' when passing argument to function\r\n#pragma GCC diagnostic ignored \"-Wconversion\"               // warning: conversion to 'xxxx' from 'xxxx' may alter its value\r\n#pragma GCC diagnostic ignored \"-Wformat-nonliteral\"        // warning: format not a string literal, format string not checked\r\n#pragma GCC diagnostic ignored \"-Wstrict-overflow\"          // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false\r\n#pragma GCC diagnostic ignored \"-Wclass-memaccess\"          // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead\r\n#endif\r\n\r\n// Debug options\r\n#define IMGUI_DEBUG_NAV_SCORING     0   // Display navigation scoring preview when hovering items. Display last moving direction matches when holding CTRL\r\n#define IMGUI_DEBUG_NAV_RECTS       0   // Display the reference navigation rectangle for each window\r\n#define IMGUI_DEBUG_INI_SETTINGS    0   // Save additional comments in .ini file (particularly helps for Docking, but makes saving slower)\r\n\r\n// When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch.\r\nstatic const float NAV_WINDOWING_HIGHLIGHT_DELAY            = 0.20f;    // Time before the highlight and screen dimming starts fading in\r\nstatic const float NAV_WINDOWING_LIST_APPEAR_DELAY          = 0.15f;    // Time before the window list starts to appear\r\n\r\n// Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by backend)\r\nstatic const float WINDOWS_HOVER_PADDING                    = 4.0f;     // Extend outside window for hovering/resizing (maxxed with TouchPadding) and inside windows for borders. Affect FindHoveredWindow().\r\nstatic const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f;    // Reduce visual noise by only highlighting the border after a certain time.\r\nstatic const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER    = 2.00f;    // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certain time, unless mouse moved.\r\n\r\n//-------------------------------------------------------------------------\r\n// [SECTION] FORWARD DECLARATIONS\r\n//-------------------------------------------------------------------------\r\n\r\nstatic void             SetCurrentWindow(ImGuiWindow* window);\r\nstatic void             FindHoveredWindow();\r\nstatic ImGuiWindow*     CreateNewWindow(const char* name, ImGuiWindowFlags flags);\r\nstatic ImVec2           CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);\r\n\r\nstatic void             AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list);\r\nstatic void             AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);\r\n\r\n// Settings\r\nstatic void             WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);\r\nstatic void*            WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);\r\nstatic void             WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);\r\nstatic void             WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);\r\nstatic void             WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf);\r\n\r\n// Platform Dependents default implementation for IO functions\r\nstatic const char*      GetClipboardTextFn_DefaultImpl(void* user_data);\r\nstatic void             SetClipboardTextFn_DefaultImpl(void* user_data, const char* text);\r\nstatic void             SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data);\r\n\r\nnamespace ImGui\r\n{\r\n// Navigation\r\nstatic void             NavUpdate();\r\nstatic void             NavUpdateWindowing();\r\nstatic void             NavUpdateWindowingOverlay();\r\nstatic void             NavUpdateCancelRequest();\r\nstatic void             NavUpdateCreateMoveRequest();\r\nstatic void             NavUpdateCreateTabbingRequest();\r\nstatic float            NavUpdatePageUpPageDown();\r\nstatic inline void      NavUpdateAnyRequestFlag();\r\nstatic void             NavUpdateCreateWrappingRequest();\r\nstatic void             NavEndFrame();\r\nstatic bool             NavScoreItem(ImGuiNavItemData* result);\r\nstatic void             NavApplyItemToResult(ImGuiNavItemData* result);\r\nstatic void             NavProcessItem();\r\nstatic void             NavProcessItemForTabbingRequest(ImGuiID id);\r\nstatic ImVec2           NavCalcPreferredRefPos();\r\nstatic void             NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);\r\nstatic ImGuiWindow*     NavRestoreLastChildNavWindow(ImGuiWindow* window);\r\nstatic void             NavRestoreLayer(ImGuiNavLayer layer);\r\nstatic void             NavRestoreHighlightAfterMove();\r\nstatic int              FindWindowFocusIndex(ImGuiWindow* window);\r\n\r\n// Error Checking and Debug Tools\r\nstatic void             ErrorCheckNewFrameSanityChecks();\r\nstatic void             ErrorCheckEndFrameSanityChecks();\r\nstatic void             UpdateDebugToolItemPicker();\r\nstatic void             UpdateDebugToolStackQueries();\r\n\r\n// Misc\r\nstatic void             UpdateSettings();\r\nstatic void             UpdateKeyboardInputs();\r\nstatic void             UpdateMouseInputs();\r\nstatic void             UpdateMouseWheel();\r\nstatic bool             UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect);\r\nstatic void             RenderWindowOuterBorders(ImGuiWindow* window);\r\nstatic void             RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size);\r\nstatic void             RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);\r\nstatic void             RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col);\r\nstatic void             RenderDimmedBackgrounds();\r\nstatic ImGuiWindow*     FindBlockingModal(ImGuiWindow* window);\r\n\r\n// Viewports\r\nstatic void             UpdateViewportsNewFrame();\r\n\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] CONTEXT AND MEMORY ALLOCATORS\r\n//-----------------------------------------------------------------------------\r\n\r\n// DLL users:\r\n// - Heaps and globals are not shared across DLL boundaries!\r\n// - You will need to call SetCurrentContext() + SetAllocatorFunctions() for each static/DLL boundary you are calling from.\r\n// - Same applies for hot-reloading mechanisms that are reliant on reloading DLL (note that many hot-reloading mechanisms work without DLL).\r\n// - Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility.\r\n// - Confused? In a debugger: add GImGui to your watch window and notice how its value changes depending on your current location (which DLL boundary you are in).\r\n\r\n// Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.\r\n// - ImGui::CreateContext() will automatically set this pointer if it is NULL.\r\n//   Change to a different context by calling ImGui::SetCurrentContext().\r\n// - Important: Dear ImGui functions are not thread-safe because of this pointer.\r\n//   If you want thread-safety to allow N threads to access N different contexts:\r\n//   - Change this variable to use thread local storage so each thread can refer to a different context, in your imconfig.h:\r\n//         struct ImGuiContext;\r\n//         extern thread_local ImGuiContext* MyImGuiTLS;\r\n//         #define GImGui MyImGuiTLS\r\n//     And then define MyImGuiTLS in one of your cpp files. Note that thread_local is a C++11 keyword, earlier C++ uses compiler-specific keyword.\r\n//   - Future development aims to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586\r\n//   - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from a different namespace.\r\n// - DLL users: read comments above.\r\n#ifndef GImGui\r\nImGuiContext*   GImGui = NULL;\r\n#endif\r\n\r\n// Memory Allocator functions. Use SetAllocatorFunctions() to change them.\r\n// - You probably don't want to modify that mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction.\r\n// - DLL users: read comments above.\r\n#ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS\r\nstatic void*   MallocWrapper(size_t size, void* user_data)    { IM_UNUSED(user_data); return malloc(size); }\r\nstatic void    FreeWrapper(void* ptr, void* user_data)        { IM_UNUSED(user_data); free(ptr); }\r\n#else\r\nstatic void*   MallocWrapper(size_t size, void* user_data)    { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }\r\nstatic void    FreeWrapper(void* ptr, void* user_data)        { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }\r\n#endif\r\nstatic ImGuiMemAllocFunc    GImAllocatorAllocFunc = MallocWrapper;\r\nstatic ImGuiMemFreeFunc     GImAllocatorFreeFunc = FreeWrapper;\r\nstatic void*                GImAllocatorUserData = NULL;\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)\r\n//-----------------------------------------------------------------------------\r\n\r\nImGuiStyle::ImGuiStyle()\r\n{\r\n    Alpha                   = 1.0f;             // Global alpha applies to everything in Dear ImGui.\r\n    DisabledAlpha           = 0.60f;            // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha.\r\n    WindowPadding           = ImVec2(8,8);      // Padding within a window\r\n    WindowRounding          = 0.0f;             // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended.\r\n    WindowBorderSize        = 1.0f;             // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.\r\n    WindowMinSize           = ImVec2(32,32);    // Minimum window size\r\n    WindowTitleAlign        = ImVec2(0.0f,0.5f);// Alignment for title bar text\r\n    WindowMenuButtonPosition= ImGuiDir_Left;    // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left.\r\n    ChildRounding           = 0.0f;             // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows\r\n    ChildBorderSize         = 1.0f;             // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.\r\n    PopupRounding           = 0.0f;             // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows\r\n    PopupBorderSize         = 1.0f;             // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.\r\n    FramePadding            = ImVec2(4,3);      // Padding within a framed rectangle (used by most widgets)\r\n    FrameRounding           = 0.0f;             // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).\r\n    FrameBorderSize         = 0.0f;             // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.\r\n    ItemSpacing             = ImVec2(8,4);      // Horizontal and vertical spacing between widgets/lines\r\n    ItemInnerSpacing        = ImVec2(4,4);      // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)\r\n    CellPadding             = ImVec2(4,2);      // Padding within a table cell\r\n    TouchExtraPadding       = ImVec2(0,0);      // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!\r\n    IndentSpacing           = 21.0f;            // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).\r\n    ColumnsMinSpacing       = 6.0f;             // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).\r\n    ScrollbarSize           = 14.0f;            // Width of the vertical scrollbar, Height of the horizontal scrollbar\r\n    ScrollbarRounding       = 9.0f;             // Radius of grab corners rounding for scrollbar\r\n    GrabMinSize             = 10.0f;            // Minimum width/height of a grab box for slider/scrollbar\r\n    GrabRounding            = 0.0f;             // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.\r\n    LogSliderDeadzone       = 4.0f;             // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.\r\n    TabRounding             = 4.0f;             // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.\r\n    TabBorderSize           = 0.0f;             // Thickness of border around tabs.\r\n    TabMinWidthForCloseButton = 0.0f;           // Minimum width for close button to appears on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected.\r\n    ColorButtonPosition     = ImGuiDir_Right;   // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.\r\n    ButtonTextAlign         = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.\r\n    SelectableTextAlign     = ImVec2(0.0f,0.0f);// Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line.\r\n    DisplayWindowPadding    = ImVec2(19,19);    // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows.\r\n    DisplaySafeAreaPadding  = ImVec2(3,3);      // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows.\r\n    MouseCursorScale        = 1.0f;             // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.\r\n    AntiAliasedLines        = true;             // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU.\r\n    AntiAliasedLinesUseTex  = true;             // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering.\r\n    AntiAliasedFill         = true;             // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.).\r\n    CurveTessellationTol    = 1.25f;            // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.\r\n    CircleTessellationMaxError = 0.30f;         // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry.\r\n\r\n    // Default theme\r\n    ImGui::StyleColorsDark(this);\r\n}\r\n\r\n// To scale your entire UI (e.g. if you want your app to use High DPI or generally be DPI aware) you may use this helper function. Scaling the fonts is done separately and is up to you.\r\n// Important: This operation is lossy because we round all sizes to integer. If you need to change your scale multiples, call this over a freshly initialized ImGuiStyle structure rather than scaling multiple times.\r\nvoid ImGuiStyle::ScaleAllSizes(float scale_factor)\r\n{\r\n    WindowPadding = ImFloor(WindowPadding * scale_factor);\r\n    WindowRounding = ImFloor(WindowRounding * scale_factor);\r\n    WindowMinSize = ImFloor(WindowMinSize * scale_factor);\r\n    ChildRounding = ImFloor(ChildRounding * scale_factor);\r\n    PopupRounding = ImFloor(PopupRounding * scale_factor);\r\n    FramePadding = ImFloor(FramePadding * scale_factor);\r\n    FrameRounding = ImFloor(FrameRounding * scale_factor);\r\n    ItemSpacing = ImFloor(ItemSpacing * scale_factor);\r\n    ItemInnerSpacing = ImFloor(ItemInnerSpacing * scale_factor);\r\n    CellPadding = ImFloor(CellPadding * scale_factor);\r\n    TouchExtraPadding = ImFloor(TouchExtraPadding * scale_factor);\r\n    IndentSpacing = ImFloor(IndentSpacing * scale_factor);\r\n    ColumnsMinSpacing = ImFloor(ColumnsMinSpacing * scale_factor);\r\n    ScrollbarSize = ImFloor(ScrollbarSize * scale_factor);\r\n    ScrollbarRounding = ImFloor(ScrollbarRounding * scale_factor);\r\n    GrabMinSize = ImFloor(GrabMinSize * scale_factor);\r\n    GrabRounding = ImFloor(GrabRounding * scale_factor);\r\n    LogSliderDeadzone = ImFloor(LogSliderDeadzone * scale_factor);\r\n    TabRounding = ImFloor(TabRounding * scale_factor);\r\n    TabMinWidthForCloseButton = (TabMinWidthForCloseButton != FLT_MAX) ? ImFloor(TabMinWidthForCloseButton * scale_factor) : FLT_MAX;\r\n    DisplayWindowPadding = ImFloor(DisplayWindowPadding * scale_factor);\r\n    DisplaySafeAreaPadding = ImFloor(DisplaySafeAreaPadding * scale_factor);\r\n    MouseCursorScale = ImFloor(MouseCursorScale * scale_factor);\r\n}\r\n\r\nImGuiIO::ImGuiIO()\r\n{\r\n    // Most fields are initialized with zero\r\n    memset(this, 0, sizeof(*this));\r\n    IM_STATIC_ASSERT(IM_ARRAYSIZE(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_ARRAYSIZE(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT);\r\n\r\n    // Settings\r\n    ConfigFlags = ImGuiConfigFlags_None;\r\n    BackendFlags = ImGuiBackendFlags_None;\r\n    DisplaySize = ImVec2(-1.0f, -1.0f);\r\n    DeltaTime = 1.0f / 60.0f;\r\n    IniSavingRate = 5.0f;\r\n    IniFilename = \"imgui.ini\"; // Important: \"imgui.ini\" is relative to current working dir, most apps will want to lock this to an absolute path (e.g. same path as executables).\r\n    LogFilename = \"imgui_log.txt\";\r\n    MouseDoubleClickTime = 0.30f;\r\n    MouseDoubleClickMaxDist = 6.0f;\r\n#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO\r\n    for (int i = 0; i < ImGuiKey_COUNT; i++)\r\n        KeyMap[i] = -1;\r\n#endif\r\n    KeyRepeatDelay = 0.275f;\r\n    KeyRepeatRate = 0.050f;\r\n    UserData = NULL;\r\n\r\n    Fonts = NULL;\r\n    FontGlobalScale = 1.0f;\r\n    FontDefault = NULL;\r\n    FontAllowUserScaling = false;\r\n    DisplayFramebufferScale = ImVec2(1.0f, 1.0f);\r\n\r\n    // Miscellaneous options\r\n    MouseDrawCursor = false;\r\n#ifdef __APPLE__\r\n    ConfigMacOSXBehaviors = true;  // Set Mac OS X style defaults based on __APPLE__ compile time flag\r\n#else\r\n    ConfigMacOSXBehaviors = false;\r\n#endif\r\n    ConfigInputTrickleEventQueue = true;\r\n    ConfigInputTextCursorBlink = true;\r\n    ConfigWindowsResizeFromEdges = true;\r\n    ConfigWindowsMoveFromTitleBarOnly = false;\r\n    ConfigMemoryCompactTimer = 60.0f;\r\n\r\n    // Platform Functions\r\n    BackendPlatformName = BackendRendererName = NULL;\r\n    BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;\r\n    GetClipboardTextFn = GetClipboardTextFn_DefaultImpl;   // Platform dependent default implementations\r\n    SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;\r\n    ClipboardUserData = NULL;\r\n    SetPlatformImeDataFn = SetPlatformImeDataFn_DefaultImpl;\r\n\r\n    // Input (NB: we already have memset zero the entire structure!)\r\n    MousePos = ImVec2(-FLT_MAX, -FLT_MAX);\r\n    MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);\r\n    MouseDragThreshold = 6.0f;\r\n    for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;\r\n    for (int i = 0; i < IM_ARRAYSIZE(KeysData); i++) { KeysData[i].DownDuration = KeysData[i].DownDurationPrev = -1.0f; }\r\n    for (int i = 0; i < IM_ARRAYSIZE(NavInputsDownDuration); i++) NavInputsDownDuration[i] = -1.0f;\r\n    BackendUsingLegacyKeyArrays = (ImS8)-1;\r\n    BackendUsingLegacyNavInputArray = true; // assume using legacy array until proven wrong\r\n}\r\n\r\n// Pass in translated ASCII characters for text input.\r\n// - with glfw you can get those from the callback set in glfwSetCharCallback()\r\n// - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message\r\n// FIXME: Should in theory be called \"AddCharacterEvent()\" to be consistent with new API\r\nvoid ImGuiIO::AddInputCharacter(unsigned int c)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(&g.IO == this && \"Can only add events to current context.\");\r\n    if (c == 0)\r\n        return;\r\n\r\n    ImGuiInputEvent e;\r\n    e.Type = ImGuiInputEventType_Char;\r\n    e.Source = ImGuiInputSource_Keyboard;\r\n    e.Text.Char = c;\r\n    g.InputEventsQueue.push_back(e);\r\n}\r\n\r\n// UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so\r\n// we should save the high surrogate.\r\nvoid ImGuiIO::AddInputCharacterUTF16(ImWchar16 c)\r\n{\r\n    if (c == 0 && InputQueueSurrogate == 0)\r\n        return;\r\n\r\n    if ((c & 0xFC00) == 0xD800) // High surrogate, must save\r\n    {\r\n        if (InputQueueSurrogate != 0)\r\n            AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);\r\n        InputQueueSurrogate = c;\r\n        return;\r\n    }\r\n\r\n    ImWchar cp = c;\r\n    if (InputQueueSurrogate != 0)\r\n    {\r\n        if ((c & 0xFC00) != 0xDC00) // Invalid low surrogate\r\n        {\r\n            AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);\r\n        }\r\n        else\r\n        {\r\n#if IM_UNICODE_CODEPOINT_MAX == 0xFFFF\r\n            cp = IM_UNICODE_CODEPOINT_INVALID; // Codepoint will not fit in ImWchar\r\n#else\r\n            cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000);\r\n#endif\r\n        }\r\n\r\n        InputQueueSurrogate = 0;\r\n    }\r\n    AddInputCharacter((unsigned)cp);\r\n}\r\n\r\nvoid ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)\r\n{\r\n    while (*utf8_chars != 0)\r\n    {\r\n        unsigned int c = 0;\r\n        utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL);\r\n        if (c != 0)\r\n            AddInputCharacter(c);\r\n    }\r\n}\r\n\r\nvoid ImGuiIO::ClearInputCharacters()\r\n{\r\n    InputQueueCharacters.resize(0);\r\n}\r\n\r\nvoid ImGuiIO::ClearInputKeys()\r\n{\r\n#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO\r\n    memset(KeysDown, 0, sizeof(KeysDown));\r\n#endif\r\n    for (int n = 0; n < IM_ARRAYSIZE(KeysData); n++)\r\n    {\r\n        KeysData[n].Down             = false;\r\n        KeysData[n].DownDuration     = -1.0f;\r\n        KeysData[n].DownDurationPrev = -1.0f;\r\n    }\r\n    KeyCtrl = KeyShift = KeyAlt = KeySuper = false;\r\n    KeyMods = KeyModsPrev = ImGuiKeyModFlags_None;\r\n    for (int n = 0; n < IM_ARRAYSIZE(NavInputsDownDuration); n++)\r\n        NavInputsDownDuration[n] = NavInputsDownDurationPrev[n] = -1.0f;\r\n}\r\n\r\n// Queue a new key down/up event.\r\n// - ImGuiKey key:       Translated key (as in, generally ImGuiKey_A matches the key end-user would use to emit an 'A' character)\r\n// - bool down:          Is the key down? use false to signify a key release.\r\n// - float analog_value: 0.0f..1.0f\r\nvoid ImGuiIO::AddKeyAnalogEvent(ImGuiKey key, bool down, float analog_value)\r\n{\r\n    //if (e->Down) { IMGUI_DEBUG_LOG(\"AddKeyEvent() Key='%s' %d, NativeKeycode = %d, NativeScancode = %d\\n\", ImGui::GetKeyName(e->Key), e->Down, e->NativeKeycode, e->NativeScancode); }\r\n    if (key == ImGuiKey_None)\r\n        return;\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(&g.IO == this && \"Can only add events to current context.\");\r\n    IM_ASSERT(ImGui::IsNamedKey(key)); // Backend needs to pass a valid ImGuiKey_ constant. 0..511 values are legacy native key codes which are not accepted by this API.\r\n\r\n    // Verify that backend isn't mixing up using new io.AddKeyEvent() api and old io.KeysDown[] + io.KeyMap[] data.\r\n#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO\r\n    IM_ASSERT((BackendUsingLegacyKeyArrays == -1 || BackendUsingLegacyKeyArrays == 0) && \"Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!\");\r\n    if (BackendUsingLegacyKeyArrays == -1)\r\n        for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)\r\n            IM_ASSERT(KeyMap[n] == -1 && \"Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!\");\r\n    BackendUsingLegacyKeyArrays = 0;\r\n#endif\r\n    if (ImGui::IsGamepadKey(key))\r\n        BackendUsingLegacyNavInputArray = false;\r\n\r\n    // Partial filter of duplicates (not strictly needed, but makes data neater in particular for key mods and gamepad values which are most commonly spmamed)\r\n    ImGuiKeyData* key_data = ImGui::GetKeyData(key);\r\n    if (key_data->Down == down && key_data->AnalogValue == analog_value)\r\n    {\r\n        bool found = false;\r\n        for (int n = g.InputEventsQueue.Size - 1; n >= 0 && !found; n--)\r\n            if (g.InputEventsQueue[n].Type == ImGuiInputEventType_Key && g.InputEventsQueue[n].Key.Key == key)\r\n                found = true;\r\n        if (!found)\r\n            return;\r\n    }\r\n\r\n    // Add event\r\n    ImGuiInputEvent e;\r\n    e.Type = ImGuiInputEventType_Key;\r\n    e.Source = ImGui::IsGamepadKey(key) ? ImGuiInputSource_Gamepad : ImGuiInputSource_Keyboard;\r\n    e.Key.Key = key;\r\n    e.Key.Down = down;\r\n    e.Key.AnalogValue = analog_value;\r\n    g.InputEventsQueue.push_back(e);\r\n}\r\n\r\nvoid ImGuiIO::AddKeyEvent(ImGuiKey key, bool down)\r\n{\r\n    AddKeyAnalogEvent(key, down, down ? 1.0f : 0.0f);\r\n}\r\n\r\n// [Optional] Call after AddKeyEvent().\r\n// Specify native keycode, scancode + Specify index for legacy <1.87 IsKeyXXX() functions with native indices.\r\n// If you are writing a backend in 2022 or don't use IsKeyXXX() with native values that are not ImGuiKey values, you can avoid calling this.\r\nvoid ImGuiIO::SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native_scancode, int native_legacy_index)\r\n{\r\n    if (key == ImGuiKey_None)\r\n        return;\r\n    IM_ASSERT(ImGui::IsNamedKey(key)); // >= 512\r\n    IM_ASSERT(native_legacy_index == -1 || ImGui::IsLegacyKey(native_legacy_index)); // >= 0 && <= 511\r\n    IM_UNUSED(native_keycode);  // Yet unused\r\n    IM_UNUSED(native_scancode); // Yet unused\r\n\r\n    // Build native->imgui map so old user code can still call key functions with native 0..511 values.\r\n#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO\r\n    const int legacy_key = (native_legacy_index != -1) ? native_legacy_index : native_keycode;\r\n    if (ImGui::IsLegacyKey(legacy_key))\r\n        KeyMap[legacy_key] = key;\r\n#else\r\n    IM_UNUSED(key);\r\n    IM_UNUSED(native_legacy_index);\r\n#endif\r\n}\r\n\r\n// Queue a mouse move event\r\nvoid ImGuiIO::AddMousePosEvent(float x, float y)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(&g.IO == this && \"Can only add events to current context.\");\r\n\r\n    ImGuiInputEvent e;\r\n    e.Type = ImGuiInputEventType_MousePos;\r\n    e.Source = ImGuiInputSource_Mouse;\r\n    e.MousePos.PosX = x;\r\n    e.MousePos.PosY = y;\r\n    g.InputEventsQueue.push_back(e);\r\n}\r\n\r\nvoid ImGuiIO::AddMouseButtonEvent(int mouse_button, bool down)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(&g.IO == this && \"Can only add events to current context.\");\r\n    IM_ASSERT(mouse_button >= 0 && mouse_button < ImGuiMouseButton_COUNT);\r\n\r\n    ImGuiInputEvent e;\r\n    e.Type = ImGuiInputEventType_MouseButton;\r\n    e.Source = ImGuiInputSource_Mouse;\r\n    e.MouseButton.Button = mouse_button;\r\n    e.MouseButton.Down = down;\r\n    g.InputEventsQueue.push_back(e);\r\n}\r\n\r\n// Queue a mouse wheel event (most mouse/API will only have a Y component)\r\nvoid ImGuiIO::AddMouseWheelEvent(float wheel_x, float wheel_y)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(&g.IO == this && \"Can only add events to current context.\");\r\n    if (wheel_x == 0.0f && wheel_y == 0.0f)\r\n        return;\r\n\r\n    ImGuiInputEvent e;\r\n    e.Type = ImGuiInputEventType_MouseWheel;\r\n    e.Source = ImGuiInputSource_Mouse;\r\n    e.MouseWheel.WheelX = wheel_x;\r\n    e.MouseWheel.WheelY = wheel_y;\r\n    g.InputEventsQueue.push_back(e);\r\n}\r\n\r\nvoid ImGuiIO::AddFocusEvent(bool focused)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(&g.IO == this && \"Can only add events to current context.\");\r\n\r\n    ImGuiInputEvent e;\r\n    e.Type = ImGuiInputEventType_Focus;\r\n    e.AppFocused.Focused = focused;\r\n    g.InputEventsQueue.push_back(e);\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)\r\n//-----------------------------------------------------------------------------\r\n\r\nImVec2 ImBezierCubicClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments)\r\n{\r\n    IM_ASSERT(num_segments > 0); // Use ImBezierCubicClosestPointCasteljau()\r\n    ImVec2 p_last = p1;\r\n    ImVec2 p_closest;\r\n    float p_closest_dist2 = FLT_MAX;\r\n    float t_step = 1.0f / (float)num_segments;\r\n    for (int i_step = 1; i_step <= num_segments; i_step++)\r\n    {\r\n        ImVec2 p_current = ImBezierCubicCalc(p1, p2, p3, p4, t_step * i_step);\r\n        ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);\r\n        float dist2 = ImLengthSqr(p - p_line);\r\n        if (dist2 < p_closest_dist2)\r\n        {\r\n            p_closest = p_line;\r\n            p_closest_dist2 = dist2;\r\n        }\r\n        p_last = p_current;\r\n    }\r\n    return p_closest;\r\n}\r\n\r\n// Closely mimics PathBezierToCasteljau() in imgui_draw.cpp\r\nstatic void ImBezierCubicClosestPointCasteljauStep(const ImVec2& p, ImVec2& p_closest, ImVec2& p_last, float& p_closest_dist2, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level)\r\n{\r\n    float dx = x4 - x1;\r\n    float dy = y4 - y1;\r\n    float d2 = ((x2 - x4) * dy - (y2 - y4) * dx);\r\n    float d3 = ((x3 - x4) * dy - (y3 - y4) * dx);\r\n    d2 = (d2 >= 0) ? d2 : -d2;\r\n    d3 = (d3 >= 0) ? d3 : -d3;\r\n    if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy))\r\n    {\r\n        ImVec2 p_current(x4, y4);\r\n        ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);\r\n        float dist2 = ImLengthSqr(p - p_line);\r\n        if (dist2 < p_closest_dist2)\r\n        {\r\n            p_closest = p_line;\r\n            p_closest_dist2 = dist2;\r\n        }\r\n        p_last = p_current;\r\n    }\r\n    else if (level < 10)\r\n    {\r\n        float x12 = (x1 + x2)*0.5f,       y12 = (y1 + y2)*0.5f;\r\n        float x23 = (x2 + x3)*0.5f,       y23 = (y2 + y3)*0.5f;\r\n        float x34 = (x3 + x4)*0.5f,       y34 = (y3 + y4)*0.5f;\r\n        float x123 = (x12 + x23)*0.5f,    y123 = (y12 + y23)*0.5f;\r\n        float x234 = (x23 + x34)*0.5f,    y234 = (y23 + y34)*0.5f;\r\n        float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f;\r\n        ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1);\r\n        ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1);\r\n    }\r\n}\r\n\r\n// tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol\r\n// Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically.\r\nImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol)\r\n{\r\n    IM_ASSERT(tess_tol > 0.0f);\r\n    ImVec2 p_last = p1;\r\n    ImVec2 p_closest;\r\n    float p_closest_dist2 = FLT_MAX;\r\n    ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, tess_tol, 0);\r\n    return p_closest;\r\n}\r\n\r\nImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)\r\n{\r\n    ImVec2 ap = p - a;\r\n    ImVec2 ab_dir = b - a;\r\n    float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;\r\n    if (dot < 0.0f)\r\n        return a;\r\n    float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;\r\n    if (dot > ab_len_sqr)\r\n        return b;\r\n    return a + ab_dir * dot / ab_len_sqr;\r\n}\r\n\r\nbool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)\r\n{\r\n    bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;\r\n    bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;\r\n    bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;\r\n    return ((b1 == b2) && (b2 == b3));\r\n}\r\n\r\nvoid ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)\r\n{\r\n    ImVec2 v0 = b - a;\r\n    ImVec2 v1 = c - a;\r\n    ImVec2 v2 = p - a;\r\n    const float denom = v0.x * v1.y - v1.x * v0.y;\r\n    out_v = (v2.x * v1.y - v1.x * v2.y) / denom;\r\n    out_w = (v0.x * v2.y - v2.x * v0.y) / denom;\r\n    out_u = 1.0f - out_v - out_w;\r\n}\r\n\r\nImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)\r\n{\r\n    ImVec2 proj_ab = ImLineClosestPoint(a, b, p);\r\n    ImVec2 proj_bc = ImLineClosestPoint(b, c, p);\r\n    ImVec2 proj_ca = ImLineClosestPoint(c, a, p);\r\n    float dist2_ab = ImLengthSqr(p - proj_ab);\r\n    float dist2_bc = ImLengthSqr(p - proj_bc);\r\n    float dist2_ca = ImLengthSqr(p - proj_ca);\r\n    float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));\r\n    if (m == dist2_ab)\r\n        return proj_ab;\r\n    if (m == dist2_bc)\r\n        return proj_bc;\r\n    return proj_ca;\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)\r\n//-----------------------------------------------------------------------------\r\n\r\n// Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.\r\nint ImStricmp(const char* str1, const char* str2)\r\n{\r\n    int d;\r\n    while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; }\r\n    return d;\r\n}\r\n\r\nint ImStrnicmp(const char* str1, const char* str2, size_t count)\r\n{\r\n    int d = 0;\r\n    while (count > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; count--; }\r\n    return d;\r\n}\r\n\r\nvoid ImStrncpy(char* dst, const char* src, size_t count)\r\n{\r\n    if (count < 1)\r\n        return;\r\n    if (count > 1)\r\n        strncpy(dst, src, count - 1);\r\n    dst[count - 1] = 0;\r\n}\r\n\r\nchar* ImStrdup(const char* str)\r\n{\r\n    size_t len = strlen(str);\r\n    void* buf = IM_ALLOC(len + 1);\r\n    return (char*)memcpy(buf, (const void*)str, len + 1);\r\n}\r\n\r\nchar* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)\r\n{\r\n    size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1;\r\n    size_t src_size = strlen(src) + 1;\r\n    if (dst_buf_size < src_size)\r\n    {\r\n        IM_FREE(dst);\r\n        dst = (char*)IM_ALLOC(src_size);\r\n        if (p_dst_size)\r\n            *p_dst_size = src_size;\r\n    }\r\n    return (char*)memcpy(dst, (const void*)src, src_size);\r\n}\r\n\r\nconst char* ImStrchrRange(const char* str, const char* str_end, char c)\r\n{\r\n    const char* p = (const char*)memchr(str, (int)c, str_end - str);\r\n    return p;\r\n}\r\n\r\nint ImStrlenW(const ImWchar* str)\r\n{\r\n    //return (int)wcslen((const wchar_t*)str);  // FIXME-OPT: Could use this when wchar_t are 16-bit\r\n    int n = 0;\r\n    while (*str++) n++;\r\n    return n;\r\n}\r\n\r\n// Find end-of-line. Return pointer will point to either first \\n, either str_end.\r\nconst char* ImStreolRange(const char* str, const char* str_end)\r\n{\r\n    const char* p = (const char*)memchr(str, '\\n', str_end - str);\r\n    return p ? p : str_end;\r\n}\r\n\r\nconst ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line\r\n{\r\n    while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\\n')\r\n        buf_mid_line--;\r\n    return buf_mid_line;\r\n}\r\n\r\nconst char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)\r\n{\r\n    if (!needle_end)\r\n        needle_end = needle + strlen(needle);\r\n\r\n    const char un0 = (char)toupper(*needle);\r\n    while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))\r\n    {\r\n        if (toupper(*haystack) == un0)\r\n        {\r\n            const char* b = needle + 1;\r\n            for (const char* a = haystack + 1; b < needle_end; a++, b++)\r\n                if (toupper(*a) != toupper(*b))\r\n                    break;\r\n            if (b == needle_end)\r\n                return haystack;\r\n        }\r\n        haystack++;\r\n    }\r\n    return NULL;\r\n}\r\n\r\n// Trim str by offsetting contents when there's leading data + writing a \\0 at the trailing position. We use this in situation where the cost is negligible.\r\nvoid ImStrTrimBlanks(char* buf)\r\n{\r\n    char* p = buf;\r\n    while (p[0] == ' ' || p[0] == '\\t')     // Leading blanks\r\n        p++;\r\n    char* p_start = p;\r\n    while (*p != 0)                         // Find end of string\r\n        p++;\r\n    while (p > p_start && (p[-1] == ' ' || p[-1] == '\\t'))  // Trailing blanks\r\n        p--;\r\n    if (p_start != buf)                     // Copy memory if we had leading blanks\r\n        memmove(buf, p_start, p - p_start);\r\n    buf[p - p_start] = 0;                   // Zero terminate\r\n}\r\n\r\nconst char* ImStrSkipBlank(const char* str)\r\n{\r\n    while (str[0] == ' ' || str[0] == '\\t')\r\n        str++;\r\n    return str;\r\n}\r\n\r\n// A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).\r\n// Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm.\r\n// B) When buf==NULL vsnprintf() will return the output size.\r\n#ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS\r\n\r\n// We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h)\r\n// You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS\r\n// and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are\r\n// designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.)\r\n#ifdef IMGUI_USE_STB_SPRINTF\r\n#define STB_SPRINTF_IMPLEMENTATION\r\n#include \"stb_sprintf.h\"\r\n#endif\r\n\r\n#if defined(_MSC_VER) && !defined(vsnprintf)\r\n#define vsnprintf _vsnprintf\r\n#endif\r\n\r\nint ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)\r\n{\r\n    va_list args;\r\n    va_start(args, fmt);\r\n#ifdef IMGUI_USE_STB_SPRINTF\r\n    int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);\r\n#else\r\n    int w = vsnprintf(buf, buf_size, fmt, args);\r\n#endif\r\n    va_end(args);\r\n    if (buf == NULL)\r\n        return w;\r\n    if (w == -1 || w >= (int)buf_size)\r\n        w = (int)buf_size - 1;\r\n    buf[w] = 0;\r\n    return w;\r\n}\r\n\r\nint ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)\r\n{\r\n#ifdef IMGUI_USE_STB_SPRINTF\r\n    int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);\r\n#else\r\n    int w = vsnprintf(buf, buf_size, fmt, args);\r\n#endif\r\n    if (buf == NULL)\r\n        return w;\r\n    if (w == -1 || w >= (int)buf_size)\r\n        w = (int)buf_size - 1;\r\n    buf[w] = 0;\r\n    return w;\r\n}\r\n#endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS\r\n\r\n// CRC32 needs a 1KB lookup table (not cache friendly)\r\n// Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:\r\n// - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.\r\nstatic const ImU32 GCrc32LookupTable[256] =\r\n{\r\n    0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,\r\n    0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,\r\n    0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,\r\n    0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,\r\n    0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,\r\n    0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,\r\n    0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,\r\n    0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,\r\n    0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,\r\n    0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,\r\n    0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,\r\n    0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,\r\n    0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,\r\n    0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,\r\n    0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,\r\n    0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,\r\n};\r\n\r\n// Known size hash\r\n// It is ok to call ImHashData on a string with known length but the ### operator won't be supported.\r\n// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.\r\nImGuiID ImHashData(const void* data_p, size_t data_size, ImU32 seed)\r\n{\r\n    ImU32 crc = ~seed;\r\n    const unsigned char* data = (const unsigned char*)data_p;\r\n    const ImU32* crc32_lut = GCrc32LookupTable;\r\n    while (data_size-- != 0)\r\n        crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];\r\n    return ~crc;\r\n}\r\n\r\n// Zero-terminated string hash, with support for ### to reset back to seed value\r\n// We support a syntax of \"label###id\" where only \"###id\" is included in the hash, and only \"label\" gets displayed.\r\n// Because this syntax is rarely used we are optimizing for the common case.\r\n// - If we reach ### in the string we discard the hash so far and reset to the seed.\r\n// - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)\r\n// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.\r\nImGuiID ImHashStr(const char* data_p, size_t data_size, ImU32 seed)\r\n{\r\n    seed = ~seed;\r\n    ImU32 crc = seed;\r\n    const unsigned char* data = (const unsigned char*)data_p;\r\n    const ImU32* crc32_lut = GCrc32LookupTable;\r\n    if (data_size != 0)\r\n    {\r\n        while (data_size-- != 0)\r\n        {\r\n            unsigned char c = *data++;\r\n            if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')\r\n                crc = seed;\r\n            crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];\r\n        }\r\n    }\r\n    else\r\n    {\r\n        while (unsigned char c = *data++)\r\n        {\r\n            if (c == '#' && data[0] == '#' && data[1] == '#')\r\n                crc = seed;\r\n            crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];\r\n        }\r\n    }\r\n    return ~crc;\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] MISC HELPERS/UTILITIES (File functions)\r\n//-----------------------------------------------------------------------------\r\n\r\n// Default file functions\r\n#ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS\r\n\r\nImFileHandle ImFileOpen(const char* filename, const char* mode)\r\n{\r\n#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(__CYGWIN__) && !defined(__GNUC__)\r\n    // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames.\r\n    // Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32!\r\n    const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);\r\n    const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0);\r\n    ImVector<ImWchar> buf;\r\n    buf.resize(filename_wsize + mode_wsize);\r\n    ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, (wchar_t*)&buf[0], filename_wsize);\r\n    ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, (wchar_t*)&buf[filename_wsize], mode_wsize);\r\n    return ::_wfopen((const wchar_t*)&buf[0], (const wchar_t*)&buf[filename_wsize]);\r\n#else\r\n    return fopen(filename, mode);\r\n#endif\r\n}\r\n\r\n// We should in theory be using fseeko()/ftello() with off_t and _fseeki64()/_ftelli64() with __int64, waiting for the PR that does that in a very portable pre-C++11 zero-warnings way.\r\nbool    ImFileClose(ImFileHandle f)     { return fclose(f) == 0; }\r\nImU64   ImFileGetSize(ImFileHandle f)   { long off = 0, sz = 0; return ((off = ftell(f)) != -1 && !fseek(f, 0, SEEK_END) && (sz = ftell(f)) != -1 && !fseek(f, off, SEEK_SET)) ? (ImU64)sz : (ImU64)-1; }\r\nImU64   ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f)           { return fread(data, (size_t)sz, (size_t)count, f); }\r\nImU64   ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f)    { return fwrite(data, (size_t)sz, (size_t)count, f); }\r\n#endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS\r\n\r\n// Helper: Load file content into memory\r\n// Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()\r\n// This can't really be used with \"rt\" because fseek size won't match read size.\r\nvoid*   ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes)\r\n{\r\n    IM_ASSERT(filename && mode);\r\n    if (out_file_size)\r\n        *out_file_size = 0;\r\n\r\n    ImFileHandle f;\r\n    if ((f = ImFileOpen(filename, mode)) == NULL)\r\n        return NULL;\r\n\r\n    size_t file_size = (size_t)ImFileGetSize(f);\r\n    if (file_size == (size_t)-1)\r\n    {\r\n        ImFileClose(f);\r\n        return NULL;\r\n    }\r\n\r\n    void* file_data = IM_ALLOC(file_size + padding_bytes);\r\n    if (file_data == NULL)\r\n    {\r\n        ImFileClose(f);\r\n        return NULL;\r\n    }\r\n    if (ImFileRead(file_data, 1, file_size, f) != file_size)\r\n    {\r\n        ImFileClose(f);\r\n        IM_FREE(file_data);\r\n        return NULL;\r\n    }\r\n    if (padding_bytes > 0)\r\n        memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes);\r\n\r\n    ImFileClose(f);\r\n    if (out_file_size)\r\n        *out_file_size = file_size;\r\n\r\n    return file_data;\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)\r\n//-----------------------------------------------------------------------------\r\n\r\n// Convert UTF-8 to 32-bit character, process single character input.\r\n// A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8).\r\n// We handle UTF-8 decoding error by skipping forward.\r\nint ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)\r\n{\r\n    static const char lengths[32] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0 };\r\n    static const int masks[]  = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 };\r\n    static const uint32_t mins[] = { 0x400000, 0, 0x80, 0x800, 0x10000 };\r\n    static const int shiftc[] = { 0, 18, 12, 6, 0 };\r\n    static const int shifte[] = { 0, 6, 4, 2, 0 };\r\n    int len = lengths[*(const unsigned char*)in_text >> 3];\r\n    int wanted = len + !len;\r\n\r\n    if (in_text_end == NULL)\r\n        in_text_end = in_text + wanted; // Max length, nulls will be taken into account.\r\n\r\n    // Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here,\r\n    // so it is fast even with excessive branching.\r\n    unsigned char s[4];\r\n    s[0] = in_text + 0 < in_text_end ? in_text[0] : 0;\r\n    s[1] = in_text + 1 < in_text_end ? in_text[1] : 0;\r\n    s[2] = in_text + 2 < in_text_end ? in_text[2] : 0;\r\n    s[3] = in_text + 3 < in_text_end ? in_text[3] : 0;\r\n\r\n    // Assume a four-byte character and load four bytes. Unused bits are shifted out.\r\n    *out_char  = (uint32_t)(s[0] & masks[len]) << 18;\r\n    *out_char |= (uint32_t)(s[1] & 0x3f) << 12;\r\n    *out_char |= (uint32_t)(s[2] & 0x3f) <<  6;\r\n    *out_char |= (uint32_t)(s[3] & 0x3f) <<  0;\r\n    *out_char >>= shiftc[len];\r\n\r\n    // Accumulate the various error conditions.\r\n    int e = 0;\r\n    e  = (*out_char < mins[len]) << 6; // non-canonical encoding\r\n    e |= ((*out_char >> 11) == 0x1b) << 7;  // surrogate half?\r\n    e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8;  // out of range?\r\n    e |= (s[1] & 0xc0) >> 2;\r\n    e |= (s[2] & 0xc0) >> 4;\r\n    e |= (s[3]       ) >> 6;\r\n    e ^= 0x2a; // top two bits of each tail byte correct?\r\n    e >>= shifte[len];\r\n\r\n    if (e)\r\n    {\r\n        // No bytes are consumed when *in_text == 0 || in_text == in_text_end.\r\n        // One byte is consumed in case of invalid first byte of in_text.\r\n        // All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes.\r\n        // Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s.\r\n        wanted = ImMin(wanted, !!s[0] + !!s[1] + !!s[2] + !!s[3]);\r\n        *out_char = IM_UNICODE_CODEPOINT_INVALID;\r\n    }\r\n\r\n    return wanted;\r\n}\r\n\r\nint ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)\r\n{\r\n    ImWchar* buf_out = buf;\r\n    ImWchar* buf_end = buf + buf_size;\r\n    while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)\r\n    {\r\n        unsigned int c;\r\n        in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);\r\n        if (c == 0)\r\n            break;\r\n        *buf_out++ = (ImWchar)c;\r\n    }\r\n    *buf_out = 0;\r\n    if (in_text_remaining)\r\n        *in_text_remaining = in_text;\r\n    return (int)(buf_out - buf);\r\n}\r\n\r\nint ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)\r\n{\r\n    int char_count = 0;\r\n    while ((!in_text_end || in_text < in_text_end) && *in_text)\r\n    {\r\n        unsigned int c;\r\n        in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);\r\n        if (c == 0)\r\n            break;\r\n        char_count++;\r\n    }\r\n    return char_count;\r\n}\r\n\r\n// Based on stb_to_utf8() from github.com/nothings/stb/\r\nstatic inline int ImTextCharToUtf8_inline(char* buf, int buf_size, unsigned int c)\r\n{\r\n    if (c < 0x80)\r\n    {\r\n        buf[0] = (char)c;\r\n        return 1;\r\n    }\r\n    if (c < 0x800)\r\n    {\r\n        if (buf_size < 2) return 0;\r\n        buf[0] = (char)(0xc0 + (c >> 6));\r\n        buf[1] = (char)(0x80 + (c & 0x3f));\r\n        return 2;\r\n    }\r\n    if (c < 0x10000)\r\n    {\r\n        if (buf_size < 3) return 0;\r\n        buf[0] = (char)(0xe0 + (c >> 12));\r\n        buf[1] = (char)(0x80 + ((c >> 6) & 0x3f));\r\n        buf[2] = (char)(0x80 + ((c ) & 0x3f));\r\n        return 3;\r\n    }\r\n    if (c <= 0x10FFFF)\r\n    {\r\n        if (buf_size < 4) return 0;\r\n        buf[0] = (char)(0xf0 + (c >> 18));\r\n        buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));\r\n        buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));\r\n        buf[3] = (char)(0x80 + ((c ) & 0x3f));\r\n        return 4;\r\n    }\r\n    // Invalid code point, the max unicode is 0x10FFFF\r\n    return 0;\r\n}\r\n\r\nconst char* ImTextCharToUtf8(char out_buf[5], unsigned int c)\r\n{\r\n    int count = ImTextCharToUtf8_inline(out_buf, 5, c);\r\n    out_buf[count] = 0;\r\n    return out_buf;\r\n}\r\n\r\n// Not optimal but we very rarely use this function.\r\nint ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)\r\n{\r\n    unsigned int unused = 0;\r\n    return ImTextCharFromUtf8(&unused, in_text, in_text_end);\r\n}\r\n\r\nstatic inline int ImTextCountUtf8BytesFromChar(unsigned int c)\r\n{\r\n    if (c < 0x80) return 1;\r\n    if (c < 0x800) return 2;\r\n    if (c < 0x10000) return 3;\r\n    if (c <= 0x10FFFF) return 4;\r\n    return 3;\r\n}\r\n\r\nint ImTextStrToUtf8(char* out_buf, int out_buf_size, const ImWchar* in_text, const ImWchar* in_text_end)\r\n{\r\n    char* buf_p = out_buf;\r\n    const char* buf_end = out_buf + out_buf_size;\r\n    while (buf_p < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)\r\n    {\r\n        unsigned int c = (unsigned int)(*in_text++);\r\n        if (c < 0x80)\r\n            *buf_p++ = (char)c;\r\n        else\r\n            buf_p += ImTextCharToUtf8_inline(buf_p, (int)(buf_end - buf_p - 1), c);\r\n    }\r\n    *buf_p = 0;\r\n    return (int)(buf_p - out_buf);\r\n}\r\n\r\nint ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)\r\n{\r\n    int bytes_count = 0;\r\n    while ((!in_text_end || in_text < in_text_end) && *in_text)\r\n    {\r\n        unsigned int c = (unsigned int)(*in_text++);\r\n        if (c < 0x80)\r\n            bytes_count++;\r\n        else\r\n            bytes_count += ImTextCountUtf8BytesFromChar(c);\r\n    }\r\n    return bytes_count;\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] MISC HELPERS/UTILITIES (Color functions)\r\n// Note: The Convert functions are early design which are not consistent with other API.\r\n//-----------------------------------------------------------------------------\r\n\r\nIMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b)\r\n{\r\n    float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;\r\n    int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);\r\n    int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);\r\n    int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);\r\n    return IM_COL32(r, g, b, 0xFF);\r\n}\r\n\r\nImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)\r\n{\r\n    float s = 1.0f / 255.0f;\r\n    return ImVec4(\r\n        ((in >> IM_COL32_R_SHIFT) & 0xFF) * s,\r\n        ((in >> IM_COL32_G_SHIFT) & 0xFF) * s,\r\n        ((in >> IM_COL32_B_SHIFT) & 0xFF) * s,\r\n        ((in >> IM_COL32_A_SHIFT) & 0xFF) * s);\r\n}\r\n\r\nImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)\r\n{\r\n    ImU32 out;\r\n    out  = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;\r\n    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;\r\n    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;\r\n    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;\r\n    return out;\r\n}\r\n\r\n// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592\r\n// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv\r\nvoid ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)\r\n{\r\n    float K = 0.f;\r\n    if (g < b)\r\n    {\r\n        ImSwap(g, b);\r\n        K = -1.f;\r\n    }\r\n    if (r < g)\r\n    {\r\n        ImSwap(r, g);\r\n        K = -2.f / 6.f - K;\r\n    }\r\n\r\n    const float chroma = r - (g < b ? g : b);\r\n    out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));\r\n    out_s = chroma / (r + 1e-20f);\r\n    out_v = r;\r\n}\r\n\r\n// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593\r\n// also http://en.wikipedia.org/wiki/HSL_and_HSV\r\nvoid ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)\r\n{\r\n    if (s == 0.0f)\r\n    {\r\n        // gray\r\n        out_r = out_g = out_b = v;\r\n        return;\r\n    }\r\n\r\n    h = ImFmod(h, 1.0f) / (60.0f / 360.0f);\r\n    int   i = (int)h;\r\n    float f = h - (float)i;\r\n    float p = v * (1.0f - s);\r\n    float q = v * (1.0f - s * f);\r\n    float t = v * (1.0f - s * (1.0f - f));\r\n\r\n    switch (i)\r\n    {\r\n    case 0: out_r = v; out_g = t; out_b = p; break;\r\n    case 1: out_r = q; out_g = v; out_b = p; break;\r\n    case 2: out_r = p; out_g = v; out_b = t; break;\r\n    case 3: out_r = p; out_g = q; out_b = v; break;\r\n    case 4: out_r = t; out_g = p; out_b = v; break;\r\n    case 5: default: out_r = v; out_g = p; out_b = q; break;\r\n    }\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] ImGuiStorage\r\n// Helper: Key->value storage\r\n//-----------------------------------------------------------------------------\r\n\r\n// std::lower_bound but without the bullshit\r\nstatic ImGuiStorage::ImGuiStoragePair* LowerBound(ImVector<ImGuiStorage::ImGuiStoragePair>& data, ImGuiID key)\r\n{\r\n    ImGuiStorage::ImGuiStoragePair* first = data.Data;\r\n    ImGuiStorage::ImGuiStoragePair* last = data.Data + data.Size;\r\n    size_t count = (size_t)(last - first);\r\n    while (count > 0)\r\n    {\r\n        size_t count2 = count >> 1;\r\n        ImGuiStorage::ImGuiStoragePair* mid = first + count2;\r\n        if (mid->key < key)\r\n        {\r\n            first = ++mid;\r\n            count -= count2 + 1;\r\n        }\r\n        else\r\n        {\r\n            count = count2;\r\n        }\r\n    }\r\n    return first;\r\n}\r\n\r\n// For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.\r\nvoid ImGuiStorage::BuildSortByKey()\r\n{\r\n    struct StaticFunc\r\n    {\r\n        static int IMGUI_CDECL PairComparerByID(const void* lhs, const void* rhs)\r\n        {\r\n            // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.\r\n            if (((const ImGuiStoragePair*)lhs)->key > ((const ImGuiStoragePair*)rhs)->key) return +1;\r\n            if (((const ImGuiStoragePair*)lhs)->key < ((const ImGuiStoragePair*)rhs)->key) return -1;\r\n            return 0;\r\n        }\r\n    };\r\n    ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), StaticFunc::PairComparerByID);\r\n}\r\n\r\nint ImGuiStorage::GetInt(ImGuiID key, int default_val) const\r\n{\r\n    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);\r\n    if (it == Data.end() || it->key != key)\r\n        return default_val;\r\n    return it->val_i;\r\n}\r\n\r\nbool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const\r\n{\r\n    return GetInt(key, default_val ? 1 : 0) != 0;\r\n}\r\n\r\nfloat ImGuiStorage::GetFloat(ImGuiID key, float default_val) const\r\n{\r\n    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);\r\n    if (it == Data.end() || it->key != key)\r\n        return default_val;\r\n    return it->val_f;\r\n}\r\n\r\nvoid* ImGuiStorage::GetVoidPtr(ImGuiID key) const\r\n{\r\n    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);\r\n    if (it == Data.end() || it->key != key)\r\n        return NULL;\r\n    return it->val_p;\r\n}\r\n\r\n// References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer.\r\nint* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)\r\n{\r\n    ImGuiStoragePair* it = LowerBound(Data, key);\r\n    if (it == Data.end() || it->key != key)\r\n        it = Data.insert(it, ImGuiStoragePair(key, default_val));\r\n    return &it->val_i;\r\n}\r\n\r\nbool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)\r\n{\r\n    return (bool*)GetIntRef(key, default_val ? 1 : 0);\r\n}\r\n\r\nfloat* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)\r\n{\r\n    ImGuiStoragePair* it = LowerBound(Data, key);\r\n    if (it == Data.end() || it->key != key)\r\n        it = Data.insert(it, ImGuiStoragePair(key, default_val));\r\n    return &it->val_f;\r\n}\r\n\r\nvoid** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)\r\n{\r\n    ImGuiStoragePair* it = LowerBound(Data, key);\r\n    if (it == Data.end() || it->key != key)\r\n        it = Data.insert(it, ImGuiStoragePair(key, default_val));\r\n    return &it->val_p;\r\n}\r\n\r\n// FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame)\r\nvoid ImGuiStorage::SetInt(ImGuiID key, int val)\r\n{\r\n    ImGuiStoragePair* it = LowerBound(Data, key);\r\n    if (it == Data.end() || it->key != key)\r\n    {\r\n        Data.insert(it, ImGuiStoragePair(key, val));\r\n        return;\r\n    }\r\n    it->val_i = val;\r\n}\r\n\r\nvoid ImGuiStorage::SetBool(ImGuiID key, bool val)\r\n{\r\n    SetInt(key, val ? 1 : 0);\r\n}\r\n\r\nvoid ImGuiStorage::SetFloat(ImGuiID key, float val)\r\n{\r\n    ImGuiStoragePair* it = LowerBound(Data, key);\r\n    if (it == Data.end() || it->key != key)\r\n    {\r\n        Data.insert(it, ImGuiStoragePair(key, val));\r\n        return;\r\n    }\r\n    it->val_f = val;\r\n}\r\n\r\nvoid ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)\r\n{\r\n    ImGuiStoragePair* it = LowerBound(Data, key);\r\n    if (it == Data.end() || it->key != key)\r\n    {\r\n        Data.insert(it, ImGuiStoragePair(key, val));\r\n        return;\r\n    }\r\n    it->val_p = val;\r\n}\r\n\r\nvoid ImGuiStorage::SetAllInt(int v)\r\n{\r\n    for (int i = 0; i < Data.Size; i++)\r\n        Data[i].val_i = v;\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] ImGuiTextFilter\r\n//-----------------------------------------------------------------------------\r\n\r\n// Helper: Parse and apply text filters. In format \"aaaaa[,bbbb][,ccccc]\"\r\nImGuiTextFilter::ImGuiTextFilter(const char* default_filter)\r\n{\r\n    if (default_filter)\r\n    {\r\n        ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));\r\n        Build();\r\n    }\r\n    else\r\n    {\r\n        InputBuf[0] = 0;\r\n        CountGrep = 0;\r\n    }\r\n}\r\n\r\nbool ImGuiTextFilter::Draw(const char* label, float width)\r\n{\r\n    if (width != 0.0f)\r\n        ImGui::SetNextItemWidth(width);\r\n    bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));\r\n    if (value_changed)\r\n        Build();\r\n    return value_changed;\r\n}\r\n\r\nvoid ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRange>* out) const\r\n{\r\n    out->resize(0);\r\n    const char* wb = b;\r\n    const char* we = wb;\r\n    while (we < e)\r\n    {\r\n        if (*we == separator)\r\n        {\r\n            out->push_back(ImGuiTextRange(wb, we));\r\n            wb = we + 1;\r\n        }\r\n        we++;\r\n    }\r\n    if (wb != we)\r\n        out->push_back(ImGuiTextRange(wb, we));\r\n}\r\n\r\nvoid ImGuiTextFilter::Build()\r\n{\r\n    Filters.resize(0);\r\n    ImGuiTextRange input_range(InputBuf, InputBuf + strlen(InputBuf));\r\n    input_range.split(',', &Filters);\r\n\r\n    CountGrep = 0;\r\n    for (int i = 0; i != Filters.Size; i++)\r\n    {\r\n        ImGuiTextRange& f = Filters[i];\r\n        while (f.b < f.e && ImCharIsBlankA(f.b[0]))\r\n            f.b++;\r\n        while (f.e > f.b && ImCharIsBlankA(f.e[-1]))\r\n            f.e--;\r\n        if (f.empty())\r\n            continue;\r\n        if (Filters[i].b[0] != '-')\r\n            CountGrep += 1;\r\n    }\r\n}\r\n\r\nbool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const\r\n{\r\n    if (Filters.empty())\r\n        return true;\r\n\r\n    if (text == NULL)\r\n        text = \"\";\r\n\r\n    for (int i = 0; i != Filters.Size; i++)\r\n    {\r\n        const ImGuiTextRange& f = Filters[i];\r\n        if (f.empty())\r\n            continue;\r\n        if (f.b[0] == '-')\r\n        {\r\n            // Subtract\r\n            if (ImStristr(text, text_end, f.b + 1, f.e) != NULL)\r\n                return false;\r\n        }\r\n        else\r\n        {\r\n            // Grep\r\n            if (ImStristr(text, text_end, f.b, f.e) != NULL)\r\n                return true;\r\n        }\r\n    }\r\n\r\n    // Implicit * grep\r\n    if (CountGrep == 0)\r\n        return true;\r\n\r\n    return false;\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] ImGuiTextBuffer\r\n//-----------------------------------------------------------------------------\r\n\r\n// On some platform vsnprintf() takes va_list by reference and modifies it.\r\n// va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.\r\n#ifndef va_copy\r\n#if defined(__GNUC__) || defined(__clang__)\r\n#define va_copy(dest, src) __builtin_va_copy(dest, src)\r\n#else\r\n#define va_copy(dest, src) (dest = src)\r\n#endif\r\n#endif\r\n\r\nchar ImGuiTextBuffer::EmptyString[1] = { 0 };\r\n\r\nvoid ImGuiTextBuffer::append(const char* str, const char* str_end)\r\n{\r\n    int len = str_end ? (int)(str_end - str) : (int)strlen(str);\r\n\r\n    // Add zero-terminator the first time\r\n    const int write_off = (Buf.Size != 0) ? Buf.Size : 1;\r\n    const int needed_sz = write_off + len;\r\n    if (write_off + len >= Buf.Capacity)\r\n    {\r\n        int new_capacity = Buf.Capacity * 2;\r\n        Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);\r\n    }\r\n\r\n    Buf.resize(needed_sz);\r\n    memcpy(&Buf[write_off - 1], str, (size_t)len);\r\n    Buf[write_off - 1 + len] = 0;\r\n}\r\n\r\nvoid ImGuiTextBuffer::appendf(const char* fmt, ...)\r\n{\r\n    va_list args;\r\n    va_start(args, fmt);\r\n    appendfv(fmt, args);\r\n    va_end(args);\r\n}\r\n\r\n// Helper: Text buffer for logging/accumulating text\r\nvoid ImGuiTextBuffer::appendfv(const char* fmt, va_list args)\r\n{\r\n    va_list args_copy;\r\n    va_copy(args_copy, args);\r\n\r\n    int len = ImFormatStringV(NULL, 0, fmt, args);         // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.\r\n    if (len <= 0)\r\n    {\r\n        va_end(args_copy);\r\n        return;\r\n    }\r\n\r\n    // Add zero-terminator the first time\r\n    const int write_off = (Buf.Size != 0) ? Buf.Size : 1;\r\n    const int needed_sz = write_off + len;\r\n    if (write_off + len >= Buf.Capacity)\r\n    {\r\n        int new_capacity = Buf.Capacity * 2;\r\n        Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);\r\n    }\r\n\r\n    Buf.resize(needed_sz);\r\n    ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy);\r\n    va_end(args_copy);\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] ImGuiListClipper\r\n// This is currently not as flexible/powerful as it should be and really confusing/spaghetti, mostly because we changed\r\n// the API mid-way through development and support two ways to using the clipper, needs some rework (see TODO)\r\n//-----------------------------------------------------------------------------\r\n\r\n// FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell.\r\n// The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous.\r\nstatic bool GetSkipItemForListClipping()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    return (g.CurrentTable ? g.CurrentTable->HostSkipItems : g.CurrentWindow->SkipItems);\r\n}\r\n\r\n#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS\r\n// Legacy helper to calculate coarse clipping of large list of evenly sized items.\r\n// This legacy API is not ideal because it assume we will return a single contiguous rectangle.\r\n// Prefer using ImGuiListClipper which can returns non-contiguous ranges.\r\nvoid ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    if (g.LogEnabled)\r\n    {\r\n        // If logging is active, do not perform any clipping\r\n        *out_items_display_start = 0;\r\n        *out_items_display_end = items_count;\r\n        return;\r\n    }\r\n    if (GetSkipItemForListClipping())\r\n    {\r\n        *out_items_display_start = *out_items_display_end = 0;\r\n        return;\r\n    }\r\n\r\n    // We create the union of the ClipRect and the scoring rect which at worst should be 1 page away from ClipRect\r\n    // We don't include g.NavId's rectangle in there (unless g.NavJustMovedToId is set) because the rectangle enlargement can get costly.\r\n    ImRect rect = window->ClipRect;\r\n    if (g.NavMoveScoringItems)\r\n        rect.Add(g.NavScoringNoClipRect);\r\n    if (g.NavJustMovedToId && window->NavLastIds[0] == g.NavJustMovedToId)\r\n        rect.Add(WindowRectRelToAbs(window, window->NavRectRel[0])); // Could store and use NavJustMovedToRectRel\r\n\r\n    const ImVec2 pos = window->DC.CursorPos;\r\n    int start = (int)((rect.Min.y - pos.y) / items_height);\r\n    int end = (int)((rect.Max.y - pos.y) / items_height);\r\n\r\n    // When performing a navigation request, ensure we have one item extra in the direction we are moving to\r\n    // FIXME: Verify this works with tabbing\r\n    const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);\r\n    if (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up)\r\n        start--;\r\n    if (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down)\r\n        end++;\r\n\r\n    start = ImClamp(start, 0, items_count);\r\n    end = ImClamp(end + 1, start, items_count);\r\n    *out_items_display_start = start;\r\n    *out_items_display_end = end;\r\n}\r\n#endif\r\n\r\nstatic void ImGuiListClipper_SortAndFuseRanges(ImVector<ImGuiListClipperRange>& ranges, int offset = 0)\r\n{\r\n    if (ranges.Size - offset <= 1)\r\n        return;\r\n\r\n    // Helper to order ranges and fuse them together if possible (bubble sort is fine as we are only sorting 2-3 entries)\r\n    for (int sort_end = ranges.Size - offset - 1; sort_end > 0; --sort_end)\r\n        for (int i = offset; i < sort_end + offset; ++i)\r\n            if (ranges[i].Min > ranges[i + 1].Min)\r\n                ImSwap(ranges[i], ranges[i + 1]);\r\n\r\n    // Now fuse ranges together as much as possible.\r\n    for (int i = 1 + offset; i < ranges.Size; i++)\r\n    {\r\n        IM_ASSERT(!ranges[i].PosToIndexConvert && !ranges[i - 1].PosToIndexConvert);\r\n        if (ranges[i - 1].Max < ranges[i].Min)\r\n            continue;\r\n        ranges[i - 1].Min = ImMin(ranges[i - 1].Min, ranges[i].Min);\r\n        ranges[i - 1].Max = ImMax(ranges[i - 1].Max, ranges[i].Max);\r\n        ranges.erase(ranges.Data + i);\r\n        i--;\r\n    }\r\n}\r\n\r\nstatic void ImGuiListClipper_SeekCursorAndSetupPrevLine(float pos_y, float line_height)\r\n{\r\n    // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.\r\n    // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.\r\n    // The clipper should probably have a final step to display the last item in a regular manner, maybe with an opt-out flag for data sets which may have costly seek?\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    float off_y = pos_y - window->DC.CursorPos.y;\r\n    window->DC.CursorPos.y = pos_y;\r\n    window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y - g.Style.ItemSpacing.y);\r\n    window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height;  // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage.\r\n    window->DC.PrevLineSize.y = (line_height - g.Style.ItemSpacing.y);      // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list.\r\n    if (ImGuiOldColumns* columns = window->DC.CurrentColumns)\r\n        columns->LineMinY = window->DC.CursorPos.y;                         // Setting this so that cell Y position are set properly\r\n    if (ImGuiTable* table = g.CurrentTable)\r\n    {\r\n        if (table->IsInsideRow)\r\n            ImGui::TableEndRow(table);\r\n        table->RowPosY2 = window->DC.CursorPos.y;\r\n        const int row_increase = (int)((off_y / line_height) + 0.5f);\r\n        //table->CurrentRow += row_increase; // Can't do without fixing TableEndRow()\r\n        table->RowBgColorCounter += row_increase;\r\n    }\r\n}\r\n\r\nstatic void ImGuiListClipper_SeekCursorForItem(ImGuiListClipper* clipper, int item_n)\r\n{\r\n    // StartPosY starts from ItemsFrozen hence the subtraction\r\n    // Perform the add and multiply with double to allow seeking through larger ranges\r\n    ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;\r\n    float pos_y = (float)((double)clipper->StartPosY + data->LossynessOffset + (double)(item_n - data->ItemsFrozen) * clipper->ItemsHeight);\r\n    ImGuiListClipper_SeekCursorAndSetupPrevLine(pos_y, clipper->ItemsHeight);\r\n}\r\n\r\nImGuiListClipper::ImGuiListClipper()\r\n{\r\n    memset(this, 0, sizeof(*this));\r\n    ItemsCount = -1;\r\n}\r\n\r\nImGuiListClipper::~ImGuiListClipper()\r\n{\r\n    End();\r\n}\r\n\r\n// Use case A: Begin() called from constructor with items_height<0, then called again from Step() in StepNo 1\r\n// Use case B: Begin() called from constructor with items_height>0\r\n// FIXME-LEGACY: Ideally we should remove the Begin/End functions but they are part of the legacy API we still support. This is why some of the code in Step() calling Begin() and reassign some fields, spaghetti style.\r\nvoid ImGuiListClipper::Begin(int items_count, float items_height)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n\r\n    if (ImGuiTable* table = g.CurrentTable)\r\n        if (table->IsInsideRow)\r\n            ImGui::TableEndRow(table);\r\n\r\n    StartPosY = window->DC.CursorPos.y;\r\n    ItemsHeight = items_height;\r\n    ItemsCount = items_count;\r\n    DisplayStart = -1;\r\n    DisplayEnd = 0;\r\n\r\n    // Acquire temporary buffer\r\n    if (++g.ClipperTempDataStacked > g.ClipperTempData.Size)\r\n        g.ClipperTempData.resize(g.ClipperTempDataStacked, ImGuiListClipperData());\r\n    ImGuiListClipperData* data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];\r\n    data->Reset(this);\r\n    data->LossynessOffset = window->DC.CursorStartPosLossyness.y;\r\n    TempData = data;\r\n}\r\n\r\nvoid ImGuiListClipper::End()\r\n{\r\n    // In theory here we should assert that we are already at the right position, but it seems saner to just seek at the end and not assert/crash the user.\r\n    ImGuiContext& g = *GImGui;\r\n    if (ItemsCount >= 0 && ItemsCount < INT_MAX && DisplayStart >= 0)\r\n        ImGuiListClipper_SeekCursorForItem(this, ItemsCount);\r\n    ItemsCount = -1;\r\n\r\n    // Restore temporary buffer and fix back pointers which may be invalidated when nesting\r\n    if (ImGuiListClipperData* data = (ImGuiListClipperData*)TempData)\r\n    {\r\n        IM_ASSERT(data->ListClipper == this);\r\n        data->StepNo = data->Ranges.Size;\r\n        if (--g.ClipperTempDataStacked > 0)\r\n        {\r\n            data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];\r\n            data->ListClipper->TempData = data;\r\n        }\r\n        TempData = NULL;\r\n    }\r\n}\r\n\r\nvoid ImGuiListClipper::ForceDisplayRangeByIndices(int item_min, int item_max)\r\n{\r\n    ImGuiListClipperData* data = (ImGuiListClipperData*)TempData;\r\n    IM_ASSERT(DisplayStart < 0); // Only allowed after Begin() and if there has not been a specified range yet.\r\n    IM_ASSERT(item_min <= item_max);\r\n    if (item_min < item_max)\r\n        data->Ranges.push_back(ImGuiListClipperRange::FromIndices(item_min, item_max));\r\n}\r\n\r\nbool ImGuiListClipper::Step()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    ImGuiListClipperData* data = (ImGuiListClipperData*)TempData;\r\n\r\n    ImGuiTable* table = g.CurrentTable;\r\n    if (table && table->IsInsideRow)\r\n        ImGui::TableEndRow(table);\r\n\r\n    // No items\r\n    if (ItemsCount == 0 || GetSkipItemForListClipping())\r\n        return (void)End(), false;\r\n\r\n    // While we are in frozen row state, keep displaying items one by one, unclipped\r\n    // FIXME: Could be stored as a table-agnostic state.\r\n    if (data->StepNo == 0 && table != NULL && !table->IsUnfrozenRows)\r\n    {\r\n        DisplayStart = data->ItemsFrozen;\r\n        DisplayEnd = data->ItemsFrozen + 1;\r\n        if (DisplayStart >= ItemsCount)\r\n            return (void)End(), false;\r\n        data->ItemsFrozen++;\r\n        return true;\r\n    }\r\n\r\n    // Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height)\r\n    bool calc_clipping = false;\r\n    if (data->StepNo == 0)\r\n    {\r\n        StartPosY = window->DC.CursorPos.y;\r\n        if (ItemsHeight <= 0.0f)\r\n        {\r\n            // Submit the first item (or range) so we can measure its height (generally the first range is 0..1)\r\n            data->Ranges.push_front(ImGuiListClipperRange::FromIndices(data->ItemsFrozen, data->ItemsFrozen + 1));\r\n            DisplayStart = ImMax(data->Ranges[0].Min, data->ItemsFrozen);\r\n            DisplayEnd = ImMin(data->Ranges[0].Max, ItemsCount);\r\n            if (DisplayStart == DisplayEnd)\r\n                return (void)End(), false;\r\n            data->StepNo = 1;\r\n            return true;\r\n        }\r\n        calc_clipping = true;   // If on the first step with known item height, calculate clipping.\r\n    }\r\n\r\n    // Step 1: Let the clipper infer height from first range\r\n    if (ItemsHeight <= 0.0f)\r\n    {\r\n        IM_ASSERT(data->StepNo == 1);\r\n        if (table)\r\n            IM_ASSERT(table->RowPosY1 == StartPosY && table->RowPosY2 == window->DC.CursorPos.y);\r\n\r\n        ItemsHeight = (window->DC.CursorPos.y - StartPosY) / (float)(DisplayEnd - DisplayStart);\r\n        bool affected_by_floating_point_precision = ImIsFloatAboveGuaranteedIntegerPrecision(StartPosY) || ImIsFloatAboveGuaranteedIntegerPrecision(window->DC.CursorPos.y);\r\n        if (affected_by_floating_point_precision)\r\n            ItemsHeight = window->DC.PrevLineSize.y + g.Style.ItemSpacing.y; // FIXME: Technically wouldn't allow multi-line entries.\r\n\r\n        IM_ASSERT(ItemsHeight > 0.0f && \"Unable to calculate item height! First item hasn't moved the cursor vertically!\");\r\n        calc_clipping = true;   // If item height had to be calculated, calculate clipping afterwards.\r\n    }\r\n\r\n    // Step 0 or 1: Calculate the actual ranges of visible elements.\r\n    const int already_submitted = DisplayEnd;\r\n    if (calc_clipping)\r\n    {\r\n        if (g.LogEnabled)\r\n        {\r\n            // If logging is active, do not perform any clipping\r\n            data->Ranges.push_back(ImGuiListClipperRange::FromIndices(0, ItemsCount));\r\n        }\r\n        else\r\n        {\r\n            // Add range selected to be included for navigation\r\n            const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);\r\n            if (is_nav_request)\r\n                data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringNoClipRect.Min.y, g.NavScoringNoClipRect.Max.y, 0, 0));\r\n            if (is_nav_request && (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) && g.NavTabbingDir == -1)\r\n                data->Ranges.push_back(ImGuiListClipperRange::FromIndices(ItemsCount - 1, ItemsCount));\r\n\r\n            // Add focused/active item\r\n            ImRect nav_rect_abs = ImGui::WindowRectRelToAbs(window, window->NavRectRel[0]);\r\n            if (g.NavId != 0 && window->NavLastIds[0] == g.NavId)\r\n                data->Ranges.push_back(ImGuiListClipperRange::FromPositions(nav_rect_abs.Min.y, nav_rect_abs.Max.y, 0, 0));\r\n\r\n            // Add visible range\r\n            const int off_min = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) ? -1 : 0;\r\n            const int off_max = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down) ? 1 : 0;\r\n            data->Ranges.push_back(ImGuiListClipperRange::FromPositions(window->ClipRect.Min.y, window->ClipRect.Max.y, off_min, off_max));\r\n        }\r\n\r\n        // Convert position ranges to item index ranges\r\n        // - Very important: when a starting position is after our maximum item, we set Min to (ItemsCount - 1). This allows us to handle most forms of wrapping.\r\n        // - Due to how Selectable extra padding they tend to be \"unaligned\" with exact unit in the item list,\r\n        //   which with the flooring/ceiling tend to lead to 2 items instead of one being submitted.\r\n        for (int i = 0; i < data->Ranges.Size; i++)\r\n            if (data->Ranges[i].PosToIndexConvert)\r\n            {\r\n                int m1 = (int)(((double)data->Ranges[i].Min - window->DC.CursorPos.y - data->LossynessOffset) / ItemsHeight);\r\n                int m2 = (int)((((double)data->Ranges[i].Max - window->DC.CursorPos.y - data->LossynessOffset) / ItemsHeight) + 0.999999f);\r\n                data->Ranges[i].Min = ImClamp(already_submitted + m1 + data->Ranges[i].PosToIndexOffsetMin, already_submitted, ItemsCount - 1);\r\n                data->Ranges[i].Max = ImClamp(already_submitted + m2 + data->Ranges[i].PosToIndexOffsetMax, data->Ranges[i].Min + 1, ItemsCount);\r\n                data->Ranges[i].PosToIndexConvert = false;\r\n            }\r\n        ImGuiListClipper_SortAndFuseRanges(data->Ranges, data->StepNo);\r\n    }\r\n\r\n    // Step 0+ (if item height is given in advance) or 1+: Display the next range in line.\r\n    if (data->StepNo < data->Ranges.Size)\r\n    {\r\n        DisplayStart = ImMax(data->Ranges[data->StepNo].Min, already_submitted);\r\n        DisplayEnd = ImMin(data->Ranges[data->StepNo].Max, ItemsCount);\r\n        if (DisplayStart > already_submitted) //-V1051\r\n            ImGuiListClipper_SeekCursorForItem(this, DisplayStart);\r\n        data->StepNo++;\r\n        return true;\r\n    }\r\n\r\n    // After the last step: Let the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd),\r\n    // Advance the cursor to the end of the list and then returns 'false' to end the loop.\r\n    if (ItemsCount < INT_MAX)\r\n        ImGuiListClipper_SeekCursorForItem(this, ItemsCount);\r\n    ItemsCount = -1;\r\n\r\n    return false;\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] STYLING\r\n//-----------------------------------------------------------------------------\r\n\r\nImGuiStyle& ImGui::GetStyle()\r\n{\r\n    IM_ASSERT(GImGui != NULL && \"No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?\");\r\n    return GImGui->Style;\r\n}\r\n\r\nImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)\r\n{\r\n    ImGuiStyle& style = GImGui->Style;\r\n    ImVec4 c = style.Colors[idx];\r\n    c.w *= style.Alpha * alpha_mul;\r\n    return ColorConvertFloat4ToU32(c);\r\n}\r\n\r\nImU32 ImGui::GetColorU32(const ImVec4& col)\r\n{\r\n    ImGuiStyle& style = GImGui->Style;\r\n    ImVec4 c = col;\r\n    c.w *= style.Alpha;\r\n    return ColorConvertFloat4ToU32(c);\r\n}\r\n\r\nconst ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)\r\n{\r\n    ImGuiStyle& style = GImGui->Style;\r\n    return style.Colors[idx];\r\n}\r\n\r\nImU32 ImGui::GetColorU32(ImU32 col)\r\n{\r\n    ImGuiStyle& style = GImGui->Style;\r\n    if (style.Alpha >= 1.0f)\r\n        return col;\r\n    ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;\r\n    a = (ImU32)(a * style.Alpha); // We don't need to clamp 0..255 because Style.Alpha is in 0..1 range.\r\n    return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);\r\n}\r\n\r\n// FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32\r\nvoid ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiColorMod backup;\r\n    backup.Col = idx;\r\n    backup.BackupValue = g.Style.Colors[idx];\r\n    g.ColorStack.push_back(backup);\r\n    g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);\r\n}\r\n\r\nvoid ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiColorMod backup;\r\n    backup.Col = idx;\r\n    backup.BackupValue = g.Style.Colors[idx];\r\n    g.ColorStack.push_back(backup);\r\n    g.Style.Colors[idx] = col;\r\n}\r\n\r\nvoid ImGui::PopStyleColor(int count)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    while (count > 0)\r\n    {\r\n        ImGuiColorMod& backup = g.ColorStack.back();\r\n        g.Style.Colors[backup.Col] = backup.BackupValue;\r\n        g.ColorStack.pop_back();\r\n        count--;\r\n    }\r\n}\r\n\r\nstruct ImGuiStyleVarInfo\r\n{\r\n    ImGuiDataType   Type;\r\n    ImU32           Count;\r\n    ImU32           Offset;\r\n    void*           GetVarPtr(ImGuiStyle* style) const { return (void*)((unsigned char*)style + Offset); }\r\n};\r\n\r\nstatic const ImGuiStyleVarInfo GStyleVarInfo[] =\r\n{\r\n    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) },               // ImGuiStyleVar_Alpha\r\n    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, DisabledAlpha) },       // ImGuiStyleVar_DisabledAlpha\r\n    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) },       // ImGuiStyleVar_WindowPadding\r\n    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) },      // ImGuiStyleVar_WindowRounding\r\n    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowBorderSize) },    // ImGuiStyleVar_WindowBorderSize\r\n    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) },       // ImGuiStyleVar_WindowMinSize\r\n    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowTitleAlign) },    // ImGuiStyleVar_WindowTitleAlign\r\n    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildRounding) },       // ImGuiStyleVar_ChildRounding\r\n    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildBorderSize) },     // ImGuiStyleVar_ChildBorderSize\r\n    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupRounding) },       // ImGuiStyleVar_PopupRounding\r\n    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupBorderSize) },     // ImGuiStyleVar_PopupBorderSize\r\n    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) },        // ImGuiStyleVar_FramePadding\r\n    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) },       // ImGuiStyleVar_FrameRounding\r\n    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameBorderSize) },     // ImGuiStyleVar_FrameBorderSize\r\n    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) },         // ImGuiStyleVar_ItemSpacing\r\n    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) },    // ImGuiStyleVar_ItemInnerSpacing\r\n    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) },       // ImGuiStyleVar_IndentSpacing\r\n    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, CellPadding) },         // ImGuiStyleVar_CellPadding\r\n    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarSize) },       // ImGuiStyleVar_ScrollbarSize\r\n    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarRounding) },   // ImGuiStyleVar_ScrollbarRounding\r\n    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) },         // ImGuiStyleVar_GrabMinSize\r\n    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabRounding) },        // ImGuiStyleVar_GrabRounding\r\n    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, TabRounding) },         // ImGuiStyleVar_TabRounding\r\n    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) },     // ImGuiStyleVar_ButtonTextAlign\r\n    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign\r\n};\r\n\r\nstatic const ImGuiStyleVarInfo* GetStyleVarInfo(ImGuiStyleVar idx)\r\n{\r\n    IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);\r\n    IM_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT);\r\n    return &GStyleVarInfo[idx];\r\n}\r\n\r\nvoid ImGui::PushStyleVar(ImGuiStyleVar idx, float val)\r\n{\r\n    const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);\r\n    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1)\r\n    {\r\n        ImGuiContext& g = *GImGui;\r\n        float* pvar = (float*)var_info->GetVarPtr(&g.Style);\r\n        g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));\r\n        *pvar = val;\r\n        return;\r\n    }\r\n    IM_ASSERT(0 && \"Called PushStyleVar() float variant but variable is not a float!\");\r\n}\r\n\r\nvoid ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)\r\n{\r\n    const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);\r\n    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2)\r\n    {\r\n        ImGuiContext& g = *GImGui;\r\n        ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);\r\n        g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));\r\n        *pvar = val;\r\n        return;\r\n    }\r\n    IM_ASSERT(0 && \"Called PushStyleVar() ImVec2 variant but variable is not a ImVec2!\");\r\n}\r\n\r\nvoid ImGui::PopStyleVar(int count)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    while (count > 0)\r\n    {\r\n        // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.\r\n        ImGuiStyleMod& backup = g.StyleVarStack.back();\r\n        const ImGuiStyleVarInfo* info = GetStyleVarInfo(backup.VarIdx);\r\n        void* data = info->GetVarPtr(&g.Style);\r\n        if (info->Type == ImGuiDataType_Float && info->Count == 1)      { ((float*)data)[0] = backup.BackupFloat[0]; }\r\n        else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }\r\n        g.StyleVarStack.pop_back();\r\n        count--;\r\n    }\r\n}\r\n\r\nconst char* ImGui::GetStyleColorName(ImGuiCol idx)\r\n{\r\n    // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\\1: return \"\\1\";\r\n    switch (idx)\r\n    {\r\n    case ImGuiCol_Text: return \"Text\";\r\n    case ImGuiCol_TextDisabled: return \"TextDisabled\";\r\n    case ImGuiCol_WindowBg: return \"WindowBg\";\r\n    case ImGuiCol_ChildBg: return \"ChildBg\";\r\n    case ImGuiCol_PopupBg: return \"PopupBg\";\r\n    case ImGuiCol_Border: return \"Border\";\r\n    case ImGuiCol_BorderShadow: return \"BorderShadow\";\r\n    case ImGuiCol_FrameBg: return \"FrameBg\";\r\n    case ImGuiCol_FrameBgHovered: return \"FrameBgHovered\";\r\n    case ImGuiCol_FrameBgActive: return \"FrameBgActive\";\r\n    case ImGuiCol_TitleBg: return \"TitleBg\";\r\n    case ImGuiCol_TitleBgActive: return \"TitleBgActive\";\r\n    case ImGuiCol_TitleBgCollapsed: return \"TitleBgCollapsed\";\r\n    case ImGuiCol_MenuBarBg: return \"MenuBarBg\";\r\n    case ImGuiCol_ScrollbarBg: return \"ScrollbarBg\";\r\n    case ImGuiCol_ScrollbarGrab: return \"ScrollbarGrab\";\r\n    case ImGuiCol_ScrollbarGrabHovered: return \"ScrollbarGrabHovered\";\r\n    case ImGuiCol_ScrollbarGrabActive: return \"ScrollbarGrabActive\";\r\n    case ImGuiCol_CheckMark: return \"CheckMark\";\r\n    case ImGuiCol_SliderGrab: return \"SliderGrab\";\r\n    case ImGuiCol_SliderGrabActive: return \"SliderGrabActive\";\r\n    case ImGuiCol_Button: return \"Button\";\r\n    case ImGuiCol_ButtonHovered: return \"ButtonHovered\";\r\n    case ImGuiCol_ButtonActive: return \"ButtonActive\";\r\n    case ImGuiCol_Header: return \"Header\";\r\n    case ImGuiCol_HeaderHovered: return \"HeaderHovered\";\r\n    case ImGuiCol_HeaderActive: return \"HeaderActive\";\r\n    case ImGuiCol_Separator: return \"Separator\";\r\n    case ImGuiCol_SeparatorHovered: return \"SeparatorHovered\";\r\n    case ImGuiCol_SeparatorActive: return \"SeparatorActive\";\r\n    case ImGuiCol_ResizeGrip: return \"ResizeGrip\";\r\n    case ImGuiCol_ResizeGripHovered: return \"ResizeGripHovered\";\r\n    case ImGuiCol_ResizeGripActive: return \"ResizeGripActive\";\r\n    case ImGuiCol_Tab: return \"Tab\";\r\n    case ImGuiCol_TabHovered: return \"TabHovered\";\r\n    case ImGuiCol_TabActive: return \"TabActive\";\r\n    case ImGuiCol_TabUnfocused: return \"TabUnfocused\";\r\n    case ImGuiCol_TabUnfocusedActive: return \"TabUnfocusedActive\";\r\n    case ImGuiCol_PlotLines: return \"PlotLines\";\r\n    case ImGuiCol_PlotLinesHovered: return \"PlotLinesHovered\";\r\n    case ImGuiCol_PlotHistogram: return \"PlotHistogram\";\r\n    case ImGuiCol_PlotHistogramHovered: return \"PlotHistogramHovered\";\r\n    case ImGuiCol_TableHeaderBg: return \"TableHeaderBg\";\r\n    case ImGuiCol_TableBorderStrong: return \"TableBorderStrong\";\r\n    case ImGuiCol_TableBorderLight: return \"TableBorderLight\";\r\n    case ImGuiCol_TableRowBg: return \"TableRowBg\";\r\n    case ImGuiCol_TableRowBgAlt: return \"TableRowBgAlt\";\r\n    case ImGuiCol_TextSelectedBg: return \"TextSelectedBg\";\r\n    case ImGuiCol_DragDropTarget: return \"DragDropTarget\";\r\n    case ImGuiCol_NavHighlight: return \"NavHighlight\";\r\n    case ImGuiCol_NavWindowingHighlight: return \"NavWindowingHighlight\";\r\n    case ImGuiCol_NavWindowingDimBg: return \"NavWindowingDimBg\";\r\n    case ImGuiCol_ModalWindowDimBg: return \"ModalWindowDimBg\";\r\n    }\r\n    IM_ASSERT(0);\r\n    return \"Unknown\";\r\n}\r\n\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] RENDER HELPERS\r\n// Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change,\r\n// we need a nicer separation between low-level functions and high-level functions relying on the ImGui context.\r\n// Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context.\r\n//-----------------------------------------------------------------------------\r\n\r\nconst char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)\r\n{\r\n    const char* text_display_end = text;\r\n    if (!text_end)\r\n        text_end = (const char*)-1;\r\n\r\n    while (text_display_end < text_end && *text_display_end != '\\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))\r\n        text_display_end++;\r\n    return text_display_end;\r\n}\r\n\r\n// Internal ImGui functions to render text\r\n// RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()\r\nvoid ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n\r\n    // Hide anything after a '##' string\r\n    const char* text_display_end;\r\n    if (hide_text_after_hash)\r\n    {\r\n        text_display_end = FindRenderedTextEnd(text, text_end);\r\n    }\r\n    else\r\n    {\r\n        if (!text_end)\r\n            text_end = text + strlen(text); // FIXME-OPT\r\n        text_display_end = text_end;\r\n    }\r\n\r\n    if (text != text_display_end)\r\n    {\r\n        window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);\r\n        if (g.LogEnabled)\r\n            LogRenderedText(&pos, text, text_display_end);\r\n    }\r\n}\r\n\r\nvoid ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n\r\n    if (!text_end)\r\n        text_end = text + strlen(text); // FIXME-OPT\r\n\r\n    if (text != text_end)\r\n    {\r\n        window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);\r\n        if (g.LogEnabled)\r\n            LogRenderedText(&pos, text, text_end);\r\n    }\r\n}\r\n\r\n// Default clip_rect uses (pos_min,pos_max)\r\n// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)\r\nvoid ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)\r\n{\r\n    // Perform CPU side clipping for single clipped element to avoid using scissor state\r\n    ImVec2 pos = pos_min;\r\n    const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);\r\n\r\n    const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;\r\n    const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;\r\n    bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);\r\n    if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min\r\n        need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);\r\n\r\n    // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.\r\n    if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);\r\n    if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);\r\n\r\n    // Render\r\n    if (need_clipping)\r\n    {\r\n        ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);\r\n        draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);\r\n    }\r\n    else\r\n    {\r\n        draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);\r\n    }\r\n}\r\n\r\nvoid ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)\r\n{\r\n    // Hide anything after a '##' string\r\n    const char* text_display_end = FindRenderedTextEnd(text, text_end);\r\n    const int text_len = (int)(text_display_end - text);\r\n    if (text_len == 0)\r\n        return;\r\n\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);\r\n    if (g.LogEnabled)\r\n        LogRenderedText(&pos_min, text, text_display_end);\r\n}\r\n\r\n\r\n// Another overly complex function until we reorganize everything into a nice all-in-one helper.\r\n// This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) which define _where_ the ellipsis is, from actual clipping of text and limit of the ellipsis display.\r\n// This is because in the context of tabs we selectively hide part of the text when the Close Button appears, but we don't want the ellipsis to move.\r\nvoid ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end_full, const ImVec2* text_size_if_known)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    if (text_end_full == NULL)\r\n        text_end_full = FindRenderedTextEnd(text);\r\n    const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f);\r\n\r\n    //draw_list->AddLine(ImVec2(pos_max.x, pos_min.y - 4), ImVec2(pos_max.x, pos_max.y + 4), IM_COL32(0, 0, 255, 255));\r\n    //draw_list->AddLine(ImVec2(ellipsis_max_x, pos_min.y-2), ImVec2(ellipsis_max_x, pos_max.y+2), IM_COL32(0, 255, 0, 255));\r\n    //draw_list->AddLine(ImVec2(clip_max_x, pos_min.y), ImVec2(clip_max_x, pos_max.y), IM_COL32(255, 0, 0, 255));\r\n    // FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.\r\n    if (text_size.x > pos_max.x - pos_min.x)\r\n    {\r\n        // Hello wo...\r\n        // |       |   |\r\n        // min   max   ellipsis_max\r\n        //          <-> this is generally some padding value\r\n\r\n        const ImFont* font = draw_list->_Data->Font;\r\n        const float font_size = draw_list->_Data->FontSize;\r\n        const char* text_end_ellipsis = NULL;\r\n\r\n        ImWchar ellipsis_char = font->EllipsisChar;\r\n        int ellipsis_char_count = 1;\r\n        if (ellipsis_char == (ImWchar)-1)\r\n        {\r\n            ellipsis_char = font->DotChar;\r\n            ellipsis_char_count = 3;\r\n        }\r\n        const ImFontGlyph* glyph = font->FindGlyph(ellipsis_char);\r\n\r\n        float ellipsis_glyph_width = glyph->X1;                 // Width of the glyph with no padding on either side\r\n        float ellipsis_total_width = ellipsis_glyph_width;      // Full width of entire ellipsis\r\n\r\n        if (ellipsis_char_count > 1)\r\n        {\r\n            // Full ellipsis size without free spacing after it.\r\n            const float spacing_between_dots = 1.0f * (draw_list->_Data->FontSize / font->FontSize);\r\n            ellipsis_glyph_width = glyph->X1 - glyph->X0 + spacing_between_dots;\r\n            ellipsis_total_width = ellipsis_glyph_width * (float)ellipsis_char_count - spacing_between_dots;\r\n        }\r\n\r\n        // We can now claim the space between pos_max.x and ellipsis_max.x\r\n        const float text_avail_width = ImMax((ImMax(pos_max.x, ellipsis_max_x) - ellipsis_total_width) - pos_min.x, 1.0f);\r\n        float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x;\r\n        if (text == text_end_ellipsis && text_end_ellipsis < text_end_full)\r\n        {\r\n            // Always display at least 1 character if there's no room for character + ellipsis\r\n            text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(text, text_end_full);\r\n            text_size_clipped_x = font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text, text_end_ellipsis).x;\r\n        }\r\n        while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1]))\r\n        {\r\n            // Trim trailing space before ellipsis (FIXME: Supporting non-ascii blanks would be nice, for this we need a function to backtrack in UTF-8 text)\r\n            text_end_ellipsis--;\r\n            text_size_clipped_x -= font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text_end_ellipsis, text_end_ellipsis + 1).x; // Ascii blanks are always 1 byte\r\n        }\r\n\r\n        // Render text, render ellipsis\r\n        RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f));\r\n        float ellipsis_x = pos_min.x + text_size_clipped_x;\r\n        if (ellipsis_x + ellipsis_total_width <= ellipsis_max_x)\r\n            for (int i = 0; i < ellipsis_char_count; i++)\r\n            {\r\n                font->RenderChar(draw_list, font_size, ImVec2(ellipsis_x, pos_min.y), GetColorU32(ImGuiCol_Text), ellipsis_char);\r\n                ellipsis_x += ellipsis_glyph_width;\r\n            }\r\n    }\r\n    else\r\n    {\r\n        RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_full, &text_size, ImVec2(0.0f, 0.0f));\r\n    }\r\n\r\n    if (g.LogEnabled)\r\n        LogRenderedText(&pos_min, text, text_end_full);\r\n}\r\n\r\n// Render a rectangle shaped with optional rounding and borders\r\nvoid ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);\r\n    const float border_size = g.Style.FrameBorderSize;\r\n    if (border && border_size > 0.0f)\r\n    {\r\n        window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);\r\n        window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);\r\n    }\r\n}\r\n\r\nvoid ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    const float border_size = g.Style.FrameBorderSize;\r\n    if (border_size > 0.0f)\r\n    {\r\n        window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);\r\n        window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);\r\n    }\r\n}\r\n\r\nvoid ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    if (id != g.NavId)\r\n        return;\r\n    if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))\r\n        return;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    if (window->DC.NavHideHighlightOneFrame)\r\n        return;\r\n\r\n    float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;\r\n    ImRect display_rect = bb;\r\n    display_rect.ClipWith(window->ClipRect);\r\n    if (flags & ImGuiNavHighlightFlags_TypeDefault)\r\n    {\r\n        const float THICKNESS = 2.0f;\r\n        const float DISTANCE = 3.0f + THICKNESS * 0.5f;\r\n        display_rect.Expand(ImVec2(DISTANCE, DISTANCE));\r\n        bool fully_visible = window->ClipRect.Contains(display_rect);\r\n        if (!fully_visible)\r\n            window->DrawList->PushClipRect(display_rect.Min, display_rect.Max);\r\n        window->DrawList->AddRect(display_rect.Min + ImVec2(THICKNESS * 0.5f, THICKNESS * 0.5f), display_rect.Max - ImVec2(THICKNESS * 0.5f, THICKNESS * 0.5f), GetColorU32(ImGuiCol_NavHighlight), rounding, 0, THICKNESS);\r\n        if (!fully_visible)\r\n            window->DrawList->PopClipRect();\r\n    }\r\n    if (flags & ImGuiNavHighlightFlags_TypeThin)\r\n    {\r\n        window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, 0, 1.0f);\r\n    }\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)\r\n//-----------------------------------------------------------------------------\r\n\r\n// ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods\r\nImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name) : DrawListInst(NULL)\r\n{\r\n    memset(this, 0, sizeof(*this));\r\n    Name = ImStrdup(name);\r\n    NameBufLen = (int)strlen(name) + 1;\r\n    ID = ImHashStr(name);\r\n    IDStack.push_back(ID);\r\n    MoveId = GetID(\"#MOVE\");\r\n    ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);\r\n    ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);\r\n    AutoFitFramesX = AutoFitFramesY = -1;\r\n    AutoPosLastDirection = ImGuiDir_None;\r\n    SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;\r\n    SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);\r\n    LastFrameActive = -1;\r\n    LastTimeActive = -1.0f;\r\n    FontWindowScale = 1.0f;\r\n    SettingsOffset = -1;\r\n    DrawList = &DrawListInst;\r\n    DrawList->_Data = &context->DrawListSharedData;\r\n    DrawList->_OwnerName = Name;\r\n}\r\n\r\nImGuiWindow::~ImGuiWindow()\r\n{\r\n    IM_ASSERT(DrawList == &DrawListInst);\r\n    IM_DELETE(Name);\r\n    ColumnsStorage.clear_destruct();\r\n}\r\n\r\nImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)\r\n{\r\n    ImGuiID seed = IDStack.back();\r\n    ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);\r\n    ImGui::KeepAliveID(id);\r\n    ImGuiContext& g = *GImGui;\r\n    if (g.DebugHookIdInfo == id)\r\n        ImGui::DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);\r\n    return id;\r\n}\r\n\r\nImGuiID ImGuiWindow::GetID(const void* ptr)\r\n{\r\n    ImGuiID seed = IDStack.back();\r\n    ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);\r\n    ImGui::KeepAliveID(id);\r\n    ImGuiContext& g = *GImGui;\r\n    if (g.DebugHookIdInfo == id)\r\n        ImGui::DebugHookIdInfo(id, ImGuiDataType_Pointer, ptr, NULL);\r\n    return id;\r\n}\r\n\r\nImGuiID ImGuiWindow::GetID(int n)\r\n{\r\n    ImGuiID seed = IDStack.back();\r\n    ImGuiID id = ImHashData(&n, sizeof(n), seed);\r\n    ImGui::KeepAliveID(id);\r\n    ImGuiContext& g = *GImGui;\r\n    if (g.DebugHookIdInfo == id)\r\n        ImGui::DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);\r\n    return id;\r\n}\r\n\r\nImGuiID ImGuiWindow::GetIDNoKeepAlive(const char* str, const char* str_end)\r\n{\r\n    ImGuiID seed = IDStack.back();\r\n    ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);\r\n    ImGuiContext& g = *GImGui;\r\n    if (g.DebugHookIdInfo == id)\r\n        ImGui::DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);\r\n    return id;\r\n}\r\n\r\nImGuiID ImGuiWindow::GetIDNoKeepAlive(const void* ptr)\r\n{\r\n    ImGuiID seed = IDStack.back();\r\n    ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);\r\n    ImGuiContext& g = *GImGui;\r\n    if (g.DebugHookIdInfo == id)\r\n        ImGui::DebugHookIdInfo(id, ImGuiDataType_Pointer, ptr, NULL);\r\n    return id;\r\n}\r\n\r\nImGuiID ImGuiWindow::GetIDNoKeepAlive(int n)\r\n{\r\n    ImGuiID seed = IDStack.back();\r\n    ImGuiID id = ImHashData(&n, sizeof(n), seed);\r\n    ImGuiContext& g = *GImGui;\r\n    if (g.DebugHookIdInfo == id)\r\n        ImGui::DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);\r\n    return id;\r\n}\r\n\r\n// This is only used in rare/specific situations to manufacture an ID out of nowhere.\r\nImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)\r\n{\r\n    ImGuiID seed = IDStack.back();\r\n    ImRect r_rel = ImGui::WindowRectAbsToRel(this, r_abs);\r\n    ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed);\r\n    ImGui::KeepAliveID(id);\r\n    return id;\r\n}\r\n\r\nstatic void SetCurrentWindow(ImGuiWindow* window)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    g.CurrentWindow = window;\r\n    g.CurrentTable = window && window->DC.CurrentTableIdx != -1 ? g.Tables.GetByIndex(window->DC.CurrentTableIdx) : NULL;\r\n    if (window)\r\n        g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();\r\n}\r\n\r\nvoid ImGui::GcCompactTransientMiscBuffers()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    g.ItemFlagsStack.clear();\r\n    g.GroupStack.clear();\r\n    TableGcCompactSettings();\r\n}\r\n\r\n// Free up/compact internal window buffers, we can use this when a window becomes unused.\r\n// Not freed:\r\n// - ImGuiWindow, ImGuiWindowSettings, Name, StateStorage, ColumnsStorage (may hold useful data)\r\n// This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost.\r\nvoid ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window)\r\n{\r\n    window->MemoryCompacted = true;\r\n    window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity;\r\n    window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity;\r\n    window->IDStack.clear();\r\n    window->DrawList->_ClearFreeMemory();\r\n    window->DC.ChildWindows.clear();\r\n    window->DC.ItemWidthStack.clear();\r\n    window->DC.TextWrapPosStack.clear();\r\n}\r\n\r\nvoid ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window)\r\n{\r\n    // We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening.\r\n    // The other buffers tends to amortize much faster.\r\n    window->MemoryCompacted = false;\r\n    window->DrawList->IdxBuffer.reserve(window->MemoryDrawListIdxCapacity);\r\n    window->DrawList->VtxBuffer.reserve(window->MemoryDrawListVtxCapacity);\r\n    window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0;\r\n}\r\n\r\nvoid ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    g.ActiveIdIsJustActivated = (g.ActiveId != id);\r\n    if (g.ActiveIdIsJustActivated)\r\n    {\r\n        g.ActiveIdTimer = 0.0f;\r\n        g.ActiveIdHasBeenPressedBefore = false;\r\n        g.ActiveIdHasBeenEditedBefore = false;\r\n        g.ActiveIdMouseButton = -1;\r\n        if (id != 0)\r\n        {\r\n            g.LastActiveId = id;\r\n            g.LastActiveIdTimer = 0.0f;\r\n        }\r\n    }\r\n    g.ActiveId = id;\r\n    g.ActiveIdAllowOverlap = false;\r\n    g.ActiveIdNoClearOnFocusLoss = false;\r\n    g.ActiveIdWindow = window;\r\n    g.ActiveIdHasBeenEditedThisFrame = false;\r\n    if (id)\r\n    {\r\n        g.ActiveIdIsAlive = id;\r\n        g.ActiveIdSource = (g.NavActivateId == id || g.NavActivateInputId == id || g.NavJustMovedToId == id) ? (ImGuiInputSource)ImGuiInputSource_Nav : ImGuiInputSource_Mouse;\r\n    }\r\n\r\n    // Clear declaration of inputs claimed by the widget\r\n    // (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet)\r\n    g.ActiveIdUsingMouseWheel = false;\r\n    g.ActiveIdUsingNavDirMask = 0x00;\r\n    g.ActiveIdUsingNavInputMask = 0x00;\r\n    g.ActiveIdUsingKeyInputMask.ClearAllBits();\r\n}\r\n\r\nvoid ImGui::ClearActiveID()\r\n{\r\n    SetActiveID(0, NULL); // g.ActiveId = 0;\r\n}\r\n\r\nvoid ImGui::SetHoveredID(ImGuiID id)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    g.HoveredId = id;\r\n    g.HoveredIdAllowOverlap = false;\r\n    g.HoveredIdUsingMouseWheel = false;\r\n    if (id != 0 && g.HoveredIdPreviousFrame != id)\r\n        g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;\r\n}\r\n\r\nImGuiID ImGui::GetHoveredID()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;\r\n}\r\n\r\nvoid ImGui::KeepAliveID(ImGuiID id)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    if (g.ActiveId == id)\r\n        g.ActiveIdIsAlive = id;\r\n    if (g.ActiveIdPreviousFrame == id)\r\n        g.ActiveIdPreviousFrameIsAlive = true;\r\n}\r\n\r\nvoid ImGui::MarkItemEdited(ImGuiID id)\r\n{\r\n    // This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit().\r\n    // ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need need to fill the data.\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(g.ActiveId == id || g.ActiveId == 0 || g.DragDropActive);\r\n    IM_UNUSED(id); // Avoid unused variable warnings when asserts are compiled out.\r\n    //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);\r\n    g.ActiveIdHasBeenEditedThisFrame = true;\r\n    g.ActiveIdHasBeenEditedBefore = true;\r\n    g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;\r\n}\r\n\r\nstatic inline bool IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)\r\n{\r\n    // An active popup disable hovering on other windows (apart from its own children)\r\n    // FIXME-OPT: This could be cached/stored within the window.\r\n    ImGuiContext& g = *GImGui;\r\n    if (g.NavWindow)\r\n        if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindow)\r\n            if (focused_root_window->WasActive && focused_root_window != window->RootWindow)\r\n            {\r\n                // For the purpose of those flags we differentiate \"standard popup\" from \"modal popup\"\r\n                // NB: The order of those two tests is important because Modal windows are also Popups.\r\n                if (focused_root_window->Flags & ImGuiWindowFlags_Modal)\r\n                    return false;\r\n                if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))\r\n                    return false;\r\n            }\r\n    return true;\r\n}\r\n\r\n// This is roughly matching the behavior of internal-facing ItemHoverable()\r\n// - we allow hovering to be true when ActiveId==window->MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered()\r\n// - this should work even for non-interactive items that have no ID, so we cannot use LastItemId\r\nbool ImGui::IsItemHovered(ImGuiHoveredFlags flags)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    if (g.NavDisableMouseHover && !g.NavDisableHighlight)\r\n    {\r\n        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))\r\n            return false;\r\n        if (!IsItemFocused())\r\n            return false;\r\n    }\r\n    else\r\n    {\r\n        // Test for bounding box overlap, as updated as ItemAdd()\r\n        ImGuiItemStatusFlags status_flags = g.LastItemData.StatusFlags;\r\n        if (!(status_flags & ImGuiItemStatusFlags_HoveredRect))\r\n            return false;\r\n        IM_ASSERT((flags & (ImGuiHoveredFlags_AnyWindow | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_NoPopupHierarchy)) == 0);   // Flags not supported by this function\r\n\r\n        // Test if we are hovering the right window (our window could be behind another window)\r\n        // [2021/03/02] Reworked / reverted the revert, finally. Note we want e.g. BeginGroup/ItemAdd/EndGroup to work as well. (#3851)\r\n        // [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable\r\n        // to use IsItemHovered() after EndChild() itself. Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was\r\n        // the test that has been running for a long while.\r\n        if (g.HoveredWindow != window && (status_flags & ImGuiItemStatusFlags_HoveredWindow) == 0)\r\n            if ((flags & ImGuiHoveredFlags_AllowWhenOverlapped) == 0)\r\n                return false;\r\n\r\n        // Test if another item is active (e.g. being dragged)\r\n        if ((flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) == 0)\r\n            if (g.ActiveId != 0 && g.ActiveId != g.LastItemData.ID && !g.ActiveIdAllowOverlap && g.ActiveId != window->MoveId)\r\n                return false;\r\n\r\n        // Test if interactions on this window are blocked by an active popup or modal.\r\n        // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.\r\n        if (!IsWindowContentHoverable(window, flags))\r\n            return false;\r\n\r\n        // Test if the item is disabled\r\n        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))\r\n            return false;\r\n\r\n        // Special handling for calling after Begin() which represent the title bar or tab.\r\n        // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.\r\n        if (g.LastItemData.ID == window->MoveId && window->WriteAccessed)\r\n            return false;\r\n    }\r\n\r\n    return true;\r\n}\r\n\r\n// Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered().\r\nbool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)\r\n        return false;\r\n\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    if (g.HoveredWindow != window)\r\n        return false;\r\n    if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)\r\n        return false;\r\n    if (!IsMouseHoveringRect(bb.Min, bb.Max))\r\n        return false;\r\n    if (g.NavDisableMouseHover)\r\n        return false;\r\n    if (!IsWindowContentHoverable(window, ImGuiHoveredFlags_None))\r\n    {\r\n        g.HoveredIdDisabled = true;\r\n        return false;\r\n    }\r\n\r\n    // We exceptionally allow this function to be called with id==0 to allow using it for easy high-level\r\n    // hover test in widgets code. We could also decide to split this function is two.\r\n    if (id != 0)\r\n        SetHoveredID(id);\r\n\r\n    // When disabled we'll return false but still set HoveredId\r\n    ImGuiItemFlags item_flags = (g.LastItemData.ID == id ? g.LastItemData.InFlags : g.CurrentItemFlags);\r\n    if (item_flags & ImGuiItemFlags_Disabled)\r\n    {\r\n        // Release active id if turning disabled\r\n        if (g.ActiveId == id)\r\n            ClearActiveID();\r\n        g.HoveredIdDisabled = true;\r\n        return false;\r\n    }\r\n\r\n    if (id != 0)\r\n    {\r\n        // [DEBUG] Item Picker tool!\r\n        // We perform the check here because SetHoveredID() is not frequently called (1~ time a frame), making\r\n        // the cost of this tool near-zero. We can get slightly better call-stack and support picking non-hovered\r\n        // items if we perform the test in ItemAdd(), but that would incur a small runtime cost.\r\n        // #define IMGUI_DEBUG_TOOL_ITEM_PICKER_EX in imconfig.h if you want this check to also be performed in ItemAdd().\r\n        if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id)\r\n            GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));\r\n        if (g.DebugItemPickerBreakId == id)\r\n            IM_DEBUG_BREAK();\r\n    }\r\n\r\n    return true;\r\n}\r\n\r\nbool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    if (!bb.Overlaps(window->ClipRect))\r\n        if (id == 0 || (id != g.ActiveId && id != g.NavId))\r\n            if (!g.LogEnabled)\r\n                return true;\r\n    return false;\r\n}\r\n\r\n// This is also inlined in ItemAdd()\r\n// Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set window->DC.LastItemDisplayRect!\r\nvoid ImGui::SetLastItemData(ImGuiID item_id, ImGuiItemFlags in_flags, ImGuiItemStatusFlags item_flags, const ImRect& item_rect)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    g.LastItemData.ID = item_id;\r\n    g.LastItemData.InFlags = in_flags;\r\n    g.LastItemData.StatusFlags = item_flags;\r\n    g.LastItemData.Rect = item_rect;\r\n}\r\n\r\nfloat ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)\r\n{\r\n    if (wrap_pos_x < 0.0f)\r\n        return 0.0f;\r\n\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    if (wrap_pos_x == 0.0f)\r\n    {\r\n        // We could decide to setup a default wrapping max point for auto-resizing windows,\r\n        // or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function?\r\n        //if (window->Hidden && (window->Flags & ImGuiWindowFlags_AlwaysAutoResize))\r\n        //    wrap_pos_x = ImMax(window->WorkRect.Min.x + g.FontSize * 10.0f, window->WorkRect.Max.x);\r\n        //else\r\n        wrap_pos_x = window->WorkRect.Max.x;\r\n    }\r\n    else if (wrap_pos_x > 0.0f)\r\n    {\r\n        wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space\r\n    }\r\n\r\n    return ImMax(wrap_pos_x - pos.x, 1.0f);\r\n}\r\n\r\n// IM_ALLOC() == ImGui::MemAlloc()\r\nvoid* ImGui::MemAlloc(size_t size)\r\n{\r\n    if (ImGuiContext* ctx = GImGui)\r\n        ctx->IO.MetricsActiveAllocations++;\r\n    return (*GImAllocatorAllocFunc)(size, GImAllocatorUserData);\r\n}\r\n\r\n// IM_FREE() == ImGui::MemFree()\r\nvoid ImGui::MemFree(void* ptr)\r\n{\r\n    if (ptr)\r\n        if (ImGuiContext* ctx = GImGui)\r\n            ctx->IO.MetricsActiveAllocations--;\r\n    return (*GImAllocatorFreeFunc)(ptr, GImAllocatorUserData);\r\n}\r\n\r\nconst char* ImGui::GetClipboardText()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    return g.IO.GetClipboardTextFn ? g.IO.GetClipboardTextFn(g.IO.ClipboardUserData) : \"\";\r\n}\r\n\r\nvoid ImGui::SetClipboardText(const char* text)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    if (g.IO.SetClipboardTextFn)\r\n        g.IO.SetClipboardTextFn(g.IO.ClipboardUserData, text);\r\n}\r\n\r\nconst char* ImGui::GetVersion()\r\n{\r\n    return IMGUI_VERSION;\r\n}\r\n\r\n// Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself\r\n// Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module\r\nImGuiContext* ImGui::GetCurrentContext()\r\n{\r\n    return GImGui;\r\n}\r\n\r\nvoid ImGui::SetCurrentContext(ImGuiContext* ctx)\r\n{\r\n#ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC\r\n    IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.\r\n#else\r\n    GImGui = ctx;\r\n#endif\r\n}\r\n\r\nvoid ImGui::SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data)\r\n{\r\n    GImAllocatorAllocFunc = alloc_func;\r\n    GImAllocatorFreeFunc = free_func;\r\n    GImAllocatorUserData = user_data;\r\n}\r\n\r\n// This is provided to facilitate copying allocators from one static/DLL boundary to another (e.g. retrieve default allocator of your executable address space)\r\nvoid ImGui::GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data)\r\n{\r\n    *p_alloc_func = GImAllocatorAllocFunc;\r\n    *p_free_func = GImAllocatorFreeFunc;\r\n    *p_user_data = GImAllocatorUserData;\r\n}\r\n\r\nImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)\r\n{\r\n    ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);\r\n    if (GImGui == NULL)\r\n        SetCurrentContext(ctx);\r\n    Initialize(ctx);\r\n    return ctx;\r\n}\r\n\r\nvoid ImGui::DestroyContext(ImGuiContext* ctx)\r\n{\r\n    if (ctx == NULL)\r\n        ctx = GImGui;\r\n    Shutdown(ctx);\r\n    if (GImGui == ctx)\r\n        SetCurrentContext(NULL);\r\n    IM_DELETE(ctx);\r\n}\r\n\r\n// No specific ordering/dependency support, will see as needed\r\nImGuiID ImGui::AddContextHook(ImGuiContext* ctx, const ImGuiContextHook* hook)\r\n{\r\n    ImGuiContext& g = *ctx;\r\n    IM_ASSERT(hook->Callback != NULL && hook->HookId == 0 && hook->Type != ImGuiContextHookType_PendingRemoval_);\r\n    g.Hooks.push_back(*hook);\r\n    g.Hooks.back().HookId = ++g.HookIdNext;\r\n    return g.HookIdNext;\r\n}\r\n\r\n// Deferred removal, avoiding issue with changing vector while iterating it\r\nvoid ImGui::RemoveContextHook(ImGuiContext* ctx, ImGuiID hook_id)\r\n{\r\n    ImGuiContext& g = *ctx;\r\n    IM_ASSERT(hook_id != 0);\r\n    for (int n = 0; n < g.Hooks.Size; n++)\r\n        if (g.Hooks[n].HookId == hook_id)\r\n            g.Hooks[n].Type = ImGuiContextHookType_PendingRemoval_;\r\n}\r\n\r\n// Call context hooks (used by e.g. test engine)\r\n// We assume a small number of hooks so all stored in same array\r\nvoid ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type)\r\n{\r\n    ImGuiContext& g = *ctx;\r\n    for (int n = 0; n < g.Hooks.Size; n++)\r\n        if (g.Hooks[n].Type == hook_type)\r\n            g.Hooks[n].Callback(&g, &g.Hooks[n]);\r\n}\r\n\r\nImGuiIO& ImGui::GetIO()\r\n{\r\n    IM_ASSERT(GImGui != NULL && \"No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?\");\r\n    return GImGui->IO;\r\n}\r\n\r\n// Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame()\r\nImDrawData* ImGui::GetDrawData()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiViewportP* viewport = g.Viewports[0];\r\n    return viewport->DrawDataP.Valid ? &viewport->DrawDataP : NULL;\r\n}\r\n\r\ndouble ImGui::GetTime()\r\n{\r\n    return GImGui->Time;\r\n}\r\n\r\nint ImGui::GetFrameCount()\r\n{\r\n    return GImGui->FrameCount;\r\n}\r\n\r\nstatic ImDrawList* GetViewportDrawList(ImGuiViewportP* viewport, size_t drawlist_no, const char* drawlist_name)\r\n{\r\n    // Create the draw list on demand, because they are not frequently used for all viewports\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(drawlist_no < IM_ARRAYSIZE(viewport->DrawLists));\r\n    ImDrawList* draw_list = viewport->DrawLists[drawlist_no];\r\n    if (draw_list == NULL)\r\n    {\r\n        draw_list = IM_NEW(ImDrawList)(&g.DrawListSharedData);\r\n        draw_list->_OwnerName = drawlist_name;\r\n        viewport->DrawLists[drawlist_no] = draw_list;\r\n    }\r\n\r\n    // Our ImDrawList system requires that there is always a command\r\n    if (viewport->DrawListsLastFrame[drawlist_no] != g.FrameCount)\r\n    {\r\n        draw_list->_ResetForNewFrame();\r\n        draw_list->PushTextureID(g.IO.Fonts->TexID);\r\n        draw_list->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size, false);\r\n        viewport->DrawListsLastFrame[drawlist_no] = g.FrameCount;\r\n    }\r\n    return draw_list;\r\n}\r\n\r\nImDrawList* ImGui::GetBackgroundDrawList(ImGuiViewport* viewport)\r\n{\r\n    return GetViewportDrawList((ImGuiViewportP*)viewport, 0, \"##Background\");\r\n}\r\n\r\nImDrawList* ImGui::GetBackgroundDrawList()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    return GetBackgroundDrawList(g.Viewports[0]);\r\n}\r\n\r\nImDrawList* ImGui::GetForegroundDrawList(ImGuiViewport* viewport)\r\n{\r\n    return GetViewportDrawList((ImGuiViewportP*)viewport, 1, \"##Foreground\");\r\n}\r\n\r\nImDrawList* ImGui::GetForegroundDrawList()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    return GetForegroundDrawList(g.Viewports[0]);\r\n}\r\n\r\nImDrawListSharedData* ImGui::GetDrawListSharedData()\r\n{\r\n    return &GImGui->DrawListSharedData;\r\n}\r\n\r\nvoid ImGui::StartMouseMovingWindow(ImGuiWindow* window)\r\n{\r\n    // Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.\r\n    // We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.\r\n    // This is because we want ActiveId to be set even when the window is not permitted to move.\r\n    ImGuiContext& g = *GImGui;\r\n    FocusWindow(window);\r\n    SetActiveID(window->MoveId, window);\r\n    g.NavDisableHighlight = true;\r\n    g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindow->Pos;\r\n    g.ActiveIdNoClearOnFocusLoss = true;\r\n    SetActiveIdUsingNavAndKeys();\r\n\r\n    bool can_move_window = true;\r\n    if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindow->Flags & ImGuiWindowFlags_NoMove))\r\n        can_move_window = false;\r\n    if (can_move_window)\r\n        g.MovingWindow = window;\r\n}\r\n\r\n// Handle mouse moving window\r\n// Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()\r\n// FIXME: We don't have strong guarantee that g.MovingWindow stay synched with g.ActiveId == g.MovingWindow->MoveId.\r\n// This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs,\r\n// but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other.\r\nvoid ImGui::UpdateMouseMovingWindowNewFrame()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    if (g.MovingWindow != NULL)\r\n    {\r\n        // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).\r\n        // We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.\r\n        KeepAliveID(g.ActiveId);\r\n        IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindow);\r\n        ImGuiWindow* moving_window = g.MovingWindow->RootWindow;\r\n        if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos))\r\n        {\r\n            ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;\r\n            if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y)\r\n            {\r\n                MarkIniSettingsDirty(moving_window);\r\n                SetWindowPos(moving_window, pos, ImGuiCond_Always);\r\n            }\r\n            FocusWindow(g.MovingWindow);\r\n        }\r\n        else\r\n        {\r\n            g.MovingWindow = NULL;\r\n            ClearActiveID();\r\n        }\r\n    }\r\n    else\r\n    {\r\n        // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.\r\n        if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)\r\n        {\r\n            KeepAliveID(g.ActiveId);\r\n            if (!g.IO.MouseDown[0])\r\n                ClearActiveID();\r\n        }\r\n    }\r\n}\r\n\r\n// Initiate moving window when clicking on empty space or title bar.\r\n// Handle left-click and right-click focus.\r\nvoid ImGui::UpdateMouseMovingWindowEndFrame()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    if (g.ActiveId != 0 || g.HoveredId != 0)\r\n        return;\r\n\r\n    // Unless we just made a window/popup appear\r\n    if (g.NavWindow && g.NavWindow->Appearing)\r\n        return;\r\n\r\n    // Click on empty space to focus window and start moving\r\n    // (after we're done with all our widgets)\r\n    if (g.IO.MouseClicked[0])\r\n    {\r\n        // Handle the edge case of a popup being closed while clicking in its empty space.\r\n        // If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more.\r\n        ImGuiWindow* root_window = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;\r\n        const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(root_window->PopupId, ImGuiPopupFlags_AnyPopupLevel);\r\n\r\n        if (root_window != NULL && !is_closed_popup)\r\n        {\r\n            StartMouseMovingWindow(g.HoveredWindow); //-V595\r\n\r\n            // Cancel moving if clicked outside of title bar\r\n            if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(root_window->Flags & ImGuiWindowFlags_NoTitleBar))\r\n                if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0]))\r\n                    g.MovingWindow = NULL;\r\n\r\n            // Cancel moving if clicked over an item which was disabled or inhibited by popups (note that we know HoveredId == 0 already)\r\n            if (g.HoveredIdDisabled)\r\n                g.MovingWindow = NULL;\r\n        }\r\n        else if (root_window == NULL && g.NavWindow != NULL && GetTopMostPopupModal() == NULL)\r\n        {\r\n            // Clicking on void disable focus\r\n            FocusWindow(NULL);\r\n        }\r\n    }\r\n\r\n    // With right mouse button we close popups without changing focus based on where the mouse is aimed\r\n    // Instead, focus will be restored to the window under the bottom-most closed popup.\r\n    // (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)\r\n    if (g.IO.MouseClicked[1])\r\n    {\r\n        // Find the top-most window between HoveredWindow and the top-most Modal Window.\r\n        // This is where we can trim the popup stack.\r\n        ImGuiWindow* modal = GetTopMostPopupModal();\r\n        bool hovered_window_above_modal = g.HoveredWindow && (modal == NULL || IsWindowAbove(g.HoveredWindow, modal));\r\n        ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true);\r\n    }\r\n}\r\n\r\nstatic bool IsWindowActiveAndVisible(ImGuiWindow* window)\r\n{\r\n    return (window->Active) && (!window->Hidden);\r\n}\r\n\r\nstatic void ImGui::UpdateKeyboardInputs()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiIO& io = g.IO;\r\n\r\n    // Synchronize io.KeyMods with individual modifiers io.KeyXXX bools\r\n    io.KeyMods = GetMergedKeyModFlags();\r\n\r\n    // Import legacy keys or verify they are not used\r\n#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO\r\n    if (io.BackendUsingLegacyKeyArrays == 0)\r\n    {\r\n        // Backend used new io.AddKeyEvent() API: Good! Verify that old arrays are never written too.\r\n        for (int n = 0; n < IM_ARRAYSIZE(io.KeysDown); n++)\r\n            IM_ASSERT(io.KeysDown[n] == false && \"Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!\");\r\n    }\r\n    else\r\n    {\r\n        if (g.FrameCount == 0)\r\n            for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)\r\n                IM_ASSERT(g.IO.KeyMap[n] == -1 && \"Backend is not allowed to write to io.KeyMap[0..511]!\");\r\n\r\n        // Build reverse KeyMap (Named -> Legacy)\r\n        for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)\r\n            if (io.KeyMap[n] != -1)\r\n            {\r\n                IM_ASSERT(IsLegacyKey((ImGuiKey)io.KeyMap[n]));\r\n                io.KeyMap[io.KeyMap[n]] = n;\r\n            }\r\n\r\n        // Import legacy keys into new ones\r\n        for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)\r\n            if (io.KeysDown[n] || io.BackendUsingLegacyKeyArrays == 1)\r\n            {\r\n                const ImGuiKey key = (ImGuiKey)(io.KeyMap[n] != -1 ? io.KeyMap[n] : n);\r\n                IM_ASSERT(io.KeyMap[n] == -1 || IsNamedKey(key));\r\n                io.KeysData[key].Down = io.KeysDown[n];\r\n                io.BackendUsingLegacyKeyArrays = 1;\r\n            }\r\n        if (io.BackendUsingLegacyKeyArrays == 1)\r\n        {\r\n            io.KeysData[ImGuiKey_ModCtrl].Down = io.KeyCtrl;\r\n            io.KeysData[ImGuiKey_ModShift].Down = io.KeyShift;\r\n            io.KeysData[ImGuiKey_ModAlt].Down = io.KeyAlt;\r\n            io.KeysData[ImGuiKey_ModSuper].Down = io.KeySuper;\r\n        }\r\n    }\r\n#endif\r\n\r\n    // Clear gamepad data if disabled\r\n    if ((io.BackendFlags & ImGuiBackendFlags_HasGamepad) == 0)\r\n        for (int i = ImGuiKey_Gamepad_BEGIN; i < ImGuiKey_Gamepad_END; i++)\r\n        {\r\n            io.KeysData[i - ImGuiKey_KeysData_OFFSET].Down = false;\r\n            io.KeysData[i - ImGuiKey_KeysData_OFFSET].AnalogValue = 0.0f;\r\n        }\r\n\r\n    // Update keys\r\n    for (int i = 0; i < IM_ARRAYSIZE(io.KeysData); i++)\r\n    {\r\n        ImGuiKeyData& key_data = io.KeysData[i];\r\n        key_data.DownDurationPrev = key_data.DownDuration;\r\n        key_data.DownDuration = key_data.Down ? (key_data.DownDuration < 0.0f ? 0.0f : key_data.DownDuration + io.DeltaTime) : -1.0f;\r\n    }\r\n}\r\n\r\nstatic void ImGui::UpdateMouseInputs()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiIO& io = g.IO;\r\n\r\n    // Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)\r\n    if (IsMousePosValid(&io.MousePos))\r\n        io.MousePos = g.MouseLastValidPos = ImFloorSigned(io.MousePos);\r\n\r\n    // If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta\r\n    if (IsMousePosValid(&io.MousePos) && IsMousePosValid(&io.MousePosPrev))\r\n        io.MouseDelta = io.MousePos - io.MousePosPrev;\r\n    else\r\n        io.MouseDelta = ImVec2(0.0f, 0.0f);\r\n\r\n    // If mouse moved we re-enable mouse hovering in case it was disabled by gamepad/keyboard. In theory should use a >0.0f threshold but would need to reset in everywhere we set this to true.\r\n    if (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)\r\n        g.NavDisableMouseHover = false;\r\n\r\n    io.MousePosPrev = io.MousePos;\r\n    for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)\r\n    {\r\n        io.MouseClicked[i] = io.MouseDown[i] && io.MouseDownDuration[i] < 0.0f;\r\n        io.MouseClickedCount[i] = 0; // Will be filled below\r\n        io.MouseReleased[i] = !io.MouseDown[i] && io.MouseDownDuration[i] >= 0.0f;\r\n        io.MouseDownDurationPrev[i] = io.MouseDownDuration[i];\r\n        io.MouseDownDuration[i] = io.MouseDown[i] ? (io.MouseDownDuration[i] < 0.0f ? 0.0f : io.MouseDownDuration[i] + io.DeltaTime) : -1.0f;\r\n        if (io.MouseClicked[i])\r\n        {\r\n            bool is_repeated_click = false;\r\n            if ((float)(g.Time - io.MouseClickedTime[i]) < io.MouseDoubleClickTime)\r\n            {\r\n                ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);\r\n                if (ImLengthSqr(delta_from_click_pos) < io.MouseDoubleClickMaxDist * io.MouseDoubleClickMaxDist)\r\n                    is_repeated_click = true;\r\n            }\r\n            if (is_repeated_click)\r\n                io.MouseClickedLastCount[i]++;\r\n            else\r\n                io.MouseClickedLastCount[i] = 1;\r\n            io.MouseClickedTime[i] = g.Time;\r\n            io.MouseClickedPos[i] = io.MousePos;\r\n            io.MouseClickedCount[i] = io.MouseClickedLastCount[i];\r\n            io.MouseDragMaxDistanceSqr[i] = 0.0f;\r\n        }\r\n        else if (io.MouseDown[i])\r\n        {\r\n            // Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold\r\n            float delta_sqr_click_pos = IsMousePosValid(&io.MousePos) ? ImLengthSqr(io.MousePos - io.MouseClickedPos[i]) : 0.0f;\r\n            io.MouseDragMaxDistanceSqr[i] = ImMax(io.MouseDragMaxDistanceSqr[i], delta_sqr_click_pos);\r\n        }\r\n\r\n        // We provide io.MouseDoubleClicked[] as a legacy service\r\n        io.MouseDoubleClicked[i] = (io.MouseClickedCount[i] == 2);\r\n\r\n        // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation\r\n        if (io.MouseClicked[i])\r\n            g.NavDisableMouseHover = false;\r\n    }\r\n}\r\n\r\nstatic void StartLockWheelingWindow(ImGuiWindow* window)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    if (g.WheelingWindow == window)\r\n        return;\r\n    g.WheelingWindow = window;\r\n    g.WheelingWindowRefMousePos = g.IO.MousePos;\r\n    g.WheelingWindowTimer = WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER;\r\n}\r\n\r\nvoid ImGui::UpdateMouseWheel()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n\r\n    // Reset the locked window if we move the mouse or after the timer elapses\r\n    if (g.WheelingWindow != NULL)\r\n    {\r\n        g.WheelingWindowTimer -= g.IO.DeltaTime;\r\n        if (IsMousePosValid() && ImLengthSqr(g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold)\r\n            g.WheelingWindowTimer = 0.0f;\r\n        if (g.WheelingWindowTimer <= 0.0f)\r\n        {\r\n            g.WheelingWindow = NULL;\r\n            g.WheelingWindowTimer = 0.0f;\r\n        }\r\n    }\r\n\r\n    if (g.IO.MouseWheel == 0.0f && g.IO.MouseWheelH == 0.0f)\r\n        return;\r\n\r\n    if ((g.ActiveId != 0 && g.ActiveIdUsingMouseWheel) || (g.HoveredIdPreviousFrame != 0 && g.HoveredIdPreviousFrameUsingMouseWheel))\r\n        return;\r\n\r\n    ImGuiWindow* window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow;\r\n    if (!window || window->Collapsed)\r\n        return;\r\n\r\n    // Zoom / Scale window\r\n    // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned.\r\n    if (g.IO.MouseWheel != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling)\r\n    {\r\n        StartLockWheelingWindow(window);\r\n        const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);\r\n        const float scale = new_font_scale / window->FontWindowScale;\r\n        window->FontWindowScale = new_font_scale;\r\n        if (window == window->RootWindow)\r\n        {\r\n            const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;\r\n            SetWindowPos(window, window->Pos + offset, 0);\r\n            window->Size = ImFloor(window->Size * scale);\r\n            window->SizeFull = ImFloor(window->SizeFull * scale);\r\n        }\r\n        return;\r\n    }\r\n\r\n    // Mouse wheel scrolling\r\n    // If a child window has the ImGuiWindowFlags_NoScrollWithMouse flag, we give a chance to scroll its parent\r\n    if (g.IO.KeyCtrl)\r\n        return;\r\n\r\n    // As a standard behavior holding SHIFT while using Vertical Mouse Wheel triggers Horizontal scroll instead\r\n    // (we avoid doing it on OSX as it the OS input layer handles this already)\r\n    const bool swap_axis = g.IO.KeyShift && !g.IO.ConfigMacOSXBehaviors;\r\n    const float wheel_y = swap_axis ? 0.0f : g.IO.MouseWheel;\r\n    const float wheel_x = swap_axis ? g.IO.MouseWheel : g.IO.MouseWheelH;\r\n\r\n    // Vertical Mouse Wheel scrolling\r\n    if (wheel_y != 0.0f)\r\n    {\r\n        StartLockWheelingWindow(window);\r\n        while ((window->Flags & ImGuiWindowFlags_ChildWindow) && ((window->ScrollMax.y == 0.0f) || ((window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))))\r\n            window = window->ParentWindow;\r\n        if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))\r\n        {\r\n            float max_step = window->InnerRect.GetHeight() * 0.67f;\r\n            float scroll_step = ImFloor(ImMin(5 * window->CalcFontSize(), max_step));\r\n            SetScrollY(window, window->Scroll.y - wheel_y * scroll_step);\r\n        }\r\n    }\r\n\r\n    // Horizontal Mouse Wheel scrolling, or Vertical Mouse Wheel w/ Shift held\r\n    if (wheel_x != 0.0f)\r\n    {\r\n        StartLockWheelingWindow(window);\r\n        while ((window->Flags & ImGuiWindowFlags_ChildWindow) && ((window->ScrollMax.x == 0.0f) || ((window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))))\r\n            window = window->ParentWindow;\r\n        if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))\r\n        {\r\n            float max_step = window->InnerRect.GetWidth() * 0.67f;\r\n            float scroll_step = ImFloor(ImMin(2 * window->CalcFontSize(), max_step));\r\n            SetScrollX(window, window->Scroll.x - wheel_x * scroll_step);\r\n        }\r\n    }\r\n}\r\n\r\n// The reason this is exposed in imgui_internal.h is: on touch-based system that don't have hovering, we want to dispatch inputs to the right target (imgui vs imgui+app)\r\nvoid ImGui::UpdateHoveredWindowAndCaptureFlags()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiIO& io = g.IO;\r\n    g.WindowsHoverPadding = ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_HOVER_PADDING, WINDOWS_HOVER_PADDING));\r\n\r\n    // Find the window hovered by mouse:\r\n    // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.\r\n    // - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point of the frame.\r\n    // - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms.\r\n    bool clear_hovered_windows = false;\r\n    FindHoveredWindow();\r\n\r\n    // Modal windows prevents mouse from hovering behind them.\r\n    ImGuiWindow* modal_window = GetTopMostPopupModal();\r\n    if (modal_window && g.HoveredWindow && !IsWindowWithinBeginStackOf(g.HoveredWindow->RootWindow, modal_window))\r\n        clear_hovered_windows = true;\r\n\r\n    // Disabled mouse?\r\n    if (io.ConfigFlags & ImGuiConfigFlags_NoMouse)\r\n        clear_hovered_windows = true;\r\n\r\n    // We track click ownership. When clicked outside of a window the click is owned by the application and\r\n    // won't report hovering nor request capture even while dragging over our windows afterward.\r\n    const bool has_open_popup = (g.OpenPopupStack.Size > 0);\r\n    const bool has_open_modal = (modal_window != NULL);\r\n    int mouse_earliest_down = -1;\r\n    bool mouse_any_down = false;\r\n    for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)\r\n    {\r\n        if (io.MouseClicked[i])\r\n        {\r\n            io.MouseDownOwned[i] = (g.HoveredWindow != NULL) || has_open_popup;\r\n            io.MouseDownOwnedUnlessPopupClose[i] = (g.HoveredWindow != NULL) || has_open_modal;\r\n        }\r\n        mouse_any_down |= io.MouseDown[i];\r\n        if (io.MouseDown[i])\r\n            if (mouse_earliest_down == -1 || io.MouseClickedTime[i] < io.MouseClickedTime[mouse_earliest_down])\r\n                mouse_earliest_down = i;\r\n    }\r\n    const bool mouse_avail = (mouse_earliest_down == -1) || io.MouseDownOwned[mouse_earliest_down];\r\n    const bool mouse_avail_unless_popup_close = (mouse_earliest_down == -1) || io.MouseDownOwnedUnlessPopupClose[mouse_earliest_down];\r\n\r\n    // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.\r\n    // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)\r\n    const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;\r\n    if (!mouse_avail && !mouse_dragging_extern_payload)\r\n        clear_hovered_windows = true;\r\n\r\n    if (clear_hovered_windows)\r\n        g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;\r\n\r\n    // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to Dear ImGui only, false = dispatch mouse to Dear ImGui + underlying app)\r\n    // Update io.WantCaptureMouseAllowPopupClose (experimental) to give a chance for app to react to popup closure with a drag\r\n    if (g.WantCaptureMouseNextFrame != -1)\r\n    {\r\n        io.WantCaptureMouse = io.WantCaptureMouseUnlessPopupClose = (g.WantCaptureMouseNextFrame != 0);\r\n    }\r\n    else\r\n    {\r\n        io.WantCaptureMouse = (mouse_avail && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_popup;\r\n        io.WantCaptureMouseUnlessPopupClose = (mouse_avail_unless_popup_close && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_modal;\r\n    }\r\n\r\n    // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to Dear ImGui only, false = dispatch keyboard info to Dear ImGui + underlying app)\r\n    if (g.WantCaptureKeyboardNextFrame != -1)\r\n        io.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);\r\n    else\r\n        io.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL);\r\n    if (io.NavActive && (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(io.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard))\r\n        io.WantCaptureKeyboard = true;\r\n\r\n    // Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible\r\n    io.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;\r\n}\r\n\r\nImGuiKeyModFlags ImGui::GetMergedKeyModFlags()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiKeyModFlags key_mod_flags = ImGuiKeyModFlags_None;\r\n    if (g.IO.KeyCtrl)   { key_mod_flags |= ImGuiKeyModFlags_Ctrl; }\r\n    if (g.IO.KeyShift)  { key_mod_flags |= ImGuiKeyModFlags_Shift; }\r\n    if (g.IO.KeyAlt)    { key_mod_flags |= ImGuiKeyModFlags_Alt; }\r\n    if (g.IO.KeySuper)  { key_mod_flags |= ImGuiKeyModFlags_Super; }\r\n    return key_mod_flags;\r\n}\r\n\r\nvoid ImGui::NewFrame()\r\n{\r\n    IM_ASSERT(GImGui != NULL && \"No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?\");\r\n    ImGuiContext& g = *GImGui;\r\n\r\n    // Remove pending delete hooks before frame start.\r\n    // This deferred removal avoid issues of removal while iterating the hook vector\r\n    for (int n = g.Hooks.Size - 1; n >= 0; n--)\r\n        if (g.Hooks[n].Type == ImGuiContextHookType_PendingRemoval_)\r\n            g.Hooks.erase(&g.Hooks[n]);\r\n\r\n    CallContextHooks(&g, ImGuiContextHookType_NewFramePre);\r\n\r\n    // Check and assert for various common IO and Configuration mistakes\r\n    ErrorCheckNewFrameSanityChecks();\r\n\r\n    // Load settings on first frame, save settings when modified (after a delay)\r\n    UpdateSettings();\r\n\r\n    g.Time += g.IO.DeltaTime;\r\n    g.WithinFrameScope = true;\r\n    g.FrameCount += 1;\r\n    g.TooltipOverrideCount = 0;\r\n    g.WindowsActiveCount = 0;\r\n    g.MenusIdSubmittedThisFrame.resize(0);\r\n\r\n    // Calculate frame-rate for the user, as a purely luxurious feature\r\n    g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];\r\n    g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;\r\n    g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);\r\n    g.FramerateSecPerFrameCount = ImMin(g.FramerateSecPerFrameCount + 1, IM_ARRAYSIZE(g.FramerateSecPerFrame));\r\n    g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)g.FramerateSecPerFrameCount)) : FLT_MAX;\r\n\r\n    UpdateViewportsNewFrame();\r\n\r\n    // Setup current font and draw list shared data\r\n    g.IO.Fonts->Locked = true;\r\n    SetCurrentFont(GetDefaultFont());\r\n    IM_ASSERT(g.Font->IsLoaded());\r\n    ImRect virtual_space(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);\r\n    for (int n = 0; n < g.Viewports.Size; n++)\r\n        virtual_space.Add(g.Viewports[n]->GetMainRect());\r\n    g.DrawListSharedData.ClipRectFullscreen = virtual_space.ToVec4();\r\n    g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;\r\n    g.DrawListSharedData.SetCircleTessellationMaxError(g.Style.CircleTessellationMaxError);\r\n    g.DrawListSharedData.InitialFlags = ImDrawListFlags_None;\r\n    if (g.Style.AntiAliasedLines)\r\n        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines;\r\n    if (g.Style.AntiAliasedLinesUseTex && !(g.Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoBakedLines))\r\n        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex;\r\n    if (g.Style.AntiAliasedFill)\r\n        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;\r\n    if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)\r\n        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset;\r\n\r\n    // Mark rendering data as invalid to prevent user who may have a handle on it to use it.\r\n    for (int n = 0; n < g.Viewports.Size; n++)\r\n    {\r\n        ImGuiViewportP* viewport = g.Viewports[n];\r\n        viewport->DrawDataP.Clear();\r\n    }\r\n\r\n    // Drag and drop keep the source ID alive so even if the source disappear our state is consistent\r\n    if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)\r\n        KeepAliveID(g.DragDropPayload.SourceId);\r\n\r\n    // Update HoveredId data\r\n    if (!g.HoveredIdPreviousFrame)\r\n        g.HoveredIdTimer = 0.0f;\r\n    if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))\r\n        g.HoveredIdNotActiveTimer = 0.0f;\r\n    if (g.HoveredId)\r\n        g.HoveredIdTimer += g.IO.DeltaTime;\r\n    if (g.HoveredId && g.ActiveId != g.HoveredId)\r\n        g.HoveredIdNotActiveTimer += g.IO.DeltaTime;\r\n    g.HoveredIdPreviousFrame = g.HoveredId;\r\n    g.HoveredIdPreviousFrameUsingMouseWheel = g.HoveredIdUsingMouseWheel;\r\n    g.HoveredId = 0;\r\n    g.HoveredIdAllowOverlap = false;\r\n    g.HoveredIdUsingMouseWheel = false;\r\n    g.HoveredIdDisabled = false;\r\n\r\n    // Update ActiveId data (clear reference to active widget if the widget isn't alive anymore)\r\n    if (g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId && g.ActiveId != 0)\r\n        ClearActiveID();\r\n    if (g.ActiveId)\r\n        g.ActiveIdTimer += g.IO.DeltaTime;\r\n    g.LastActiveIdTimer += g.IO.DeltaTime;\r\n    g.ActiveIdPreviousFrame = g.ActiveId;\r\n    g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow;\r\n    g.ActiveIdPreviousFrameHasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore;\r\n    g.ActiveIdIsAlive = 0;\r\n    g.ActiveIdHasBeenEditedThisFrame = false;\r\n    g.ActiveIdPreviousFrameIsAlive = false;\r\n    g.ActiveIdIsJustActivated = false;\r\n    if (g.TempInputId != 0 && g.ActiveId != g.TempInputId)\r\n        g.TempInputId = 0;\r\n    if (g.ActiveId == 0)\r\n    {\r\n        g.ActiveIdUsingNavDirMask = 0x00;\r\n        g.ActiveIdUsingNavInputMask = 0x00;\r\n        g.ActiveIdUsingKeyInputMask.ClearAllBits();\r\n    }\r\n\r\n    // Drag and drop\r\n    g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;\r\n    g.DragDropAcceptIdCurr = 0;\r\n    g.DragDropAcceptIdCurrRectSurface = FLT_MAX;\r\n    g.DragDropWithinSource = false;\r\n    g.DragDropWithinTarget = false;\r\n    g.DragDropHoldJustPressedId = 0;\r\n\r\n    // Close popups on focus lost (currently wip/opt-in)\r\n    //if (g.IO.AppFocusLost)\r\n    //    ClosePopupsExceptModals();\r\n\r\n    // Process input queue (trickle as many events as possible)\r\n    g.InputEventsTrail.resize(0);\r\n    UpdateInputEvents(g.IO.ConfigInputTrickleEventQueue);\r\n\r\n    // Update keyboard input state\r\n    UpdateKeyboardInputs();\r\n\r\n    //IM_ASSERT(g.IO.KeyCtrl == IsKeyDown(ImGuiKey_LeftCtrl) || IsKeyDown(ImGuiKey_RightCtrl));\r\n    //IM_ASSERT(g.IO.KeyShift == IsKeyDown(ImGuiKey_LeftShift) || IsKeyDown(ImGuiKey_RightShift));\r\n    //IM_ASSERT(g.IO.KeyAlt == IsKeyDown(ImGuiKey_LeftAlt) || IsKeyDown(ImGuiKey_RightAlt));\r\n    //IM_ASSERT(g.IO.KeySuper == IsKeyDown(ImGuiKey_LeftSuper) || IsKeyDown(ImGuiKey_RightSuper));\r\n\r\n    // Update gamepad/keyboard navigation\r\n    NavUpdate();\r\n\r\n    // Update mouse input state\r\n    UpdateMouseInputs();\r\n\r\n    // Find hovered window\r\n    // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)\r\n    UpdateHoveredWindowAndCaptureFlags();\r\n\r\n    // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)\r\n    UpdateMouseMovingWindowNewFrame();\r\n\r\n    // Background darkening/whitening\r\n    if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))\r\n        g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f);\r\n    else\r\n        g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f);\r\n\r\n    g.MouseCursor = ImGuiMouseCursor_Arrow;\r\n    g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;\r\n\r\n    // Platform IME data: reset for the frame\r\n    g.PlatformImeDataPrev = g.PlatformImeData;\r\n    g.PlatformImeData.WantVisible = false;\r\n\r\n    // Mouse wheel scrolling, scale\r\n    UpdateMouseWheel();\r\n\r\n    // Mark all windows as not visible and compact unused memory.\r\n    IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size);\r\n    const float memory_compact_start_time = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f) ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer;\r\n    for (int i = 0; i != g.Windows.Size; i++)\r\n    {\r\n        ImGuiWindow* window = g.Windows[i];\r\n        window->WasActive = window->Active;\r\n        window->BeginCount = 0;\r\n        window->Active = false;\r\n        window->WriteAccessed = false;\r\n\r\n        // Garbage collect transient buffers of recently unused windows\r\n        if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time)\r\n            GcCompactTransientWindowBuffers(window);\r\n    }\r\n\r\n    // Garbage collect transient buffers of recently unused tables\r\n    for (int i = 0; i < g.TablesLastTimeActive.Size; i++)\r\n        if (g.TablesLastTimeActive[i] >= 0.0f && g.TablesLastTimeActive[i] < memory_compact_start_time)\r\n            TableGcCompactTransientBuffers(g.Tables.GetByIndex(i));\r\n    for (int i = 0; i < g.TablesTempData.Size; i++)\r\n        if (g.TablesTempData[i].LastTimeActive >= 0.0f && g.TablesTempData[i].LastTimeActive < memory_compact_start_time)\r\n            TableGcCompactTransientBuffers(&g.TablesTempData[i]);\r\n    if (g.GcCompactAll)\r\n        GcCompactTransientMiscBuffers();\r\n    g.GcCompactAll = false;\r\n\r\n    // Closing the focused window restore focus to the first active root window in descending z-order\r\n    if (g.NavWindow && !g.NavWindow->WasActive)\r\n        FocusTopMostWindowUnderOne(NULL, NULL);\r\n\r\n    // No window should be open at the beginning of the frame.\r\n    // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.\r\n    g.CurrentWindowStack.resize(0);\r\n    g.BeginPopupStack.resize(0);\r\n    g.ItemFlagsStack.resize(0);\r\n    g.ItemFlagsStack.push_back(ImGuiItemFlags_None);\r\n    g.GroupStack.resize(0);\r\n\r\n    // [DEBUG] Update debug features\r\n    UpdateDebugToolItemPicker();\r\n    UpdateDebugToolStackQueries();\r\n\r\n    // Create implicit/fallback window - which we will only render it if the user has added something to it.\r\n    // We don't use \"Debug\" to avoid colliding with user trying to create a \"Debug\" window with custom flags.\r\n    // This fallback is particularly important as it avoid ImGui:: calls from crashing.\r\n    g.WithinFrameScopeWithImplicitWindow = true;\r\n    SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver);\r\n    Begin(\"Debug##Default\");\r\n    IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true);\r\n\r\n    CallContextHooks(&g, ImGuiContextHookType_NewFramePost);\r\n}\r\n\r\nvoid ImGui::Initialize(ImGuiContext* context)\r\n{\r\n    ImGuiContext& g = *context;\r\n    IM_ASSERT(!g.Initialized && !g.SettingsLoaded);\r\n\r\n    // Add .ini handle for ImGuiWindow type\r\n    {\r\n        ImGuiSettingsHandler ini_handler;\r\n        ini_handler.TypeName = \"Window\";\r\n        ini_handler.TypeHash = ImHashStr(\"Window\");\r\n        ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll;\r\n        ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen;\r\n        ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine;\r\n        ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll;\r\n        ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll;\r\n        g.SettingsHandlers.push_back(ini_handler);\r\n    }\r\n\r\n    // Add .ini handle for ImGuiTable type\r\n    TableSettingsInstallHandler(context);\r\n\r\n    // Create default viewport\r\n    ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)();\r\n    g.Viewports.push_back(viewport);\r\n\r\n#ifdef IMGUI_HAS_DOCK\r\n#endif\r\n\r\n    g.Initialized = true;\r\n}\r\n\r\n// This function is merely here to free heap allocations.\r\nvoid ImGui::Shutdown(ImGuiContext* context)\r\n{\r\n    // The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame)\r\n    ImGuiContext& g = *context;\r\n    if (g.IO.Fonts && g.FontAtlasOwnedByContext)\r\n    {\r\n        g.IO.Fonts->Locked = false;\r\n        IM_DELETE(g.IO.Fonts);\r\n    }\r\n    g.IO.Fonts = NULL;\r\n\r\n    // Cleanup of other data are conditional on actually having initialized Dear ImGui.\r\n    if (!g.Initialized)\r\n        return;\r\n\r\n    // Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)\r\n    if (g.SettingsLoaded && g.IO.IniFilename != NULL)\r\n    {\r\n        ImGuiContext* backup_context = GImGui;\r\n        SetCurrentContext(&g);\r\n        SaveIniSettingsToDisk(g.IO.IniFilename);\r\n        SetCurrentContext(backup_context);\r\n    }\r\n\r\n    CallContextHooks(&g, ImGuiContextHookType_Shutdown);\r\n\r\n    // Clear everything else\r\n    g.Windows.clear_delete();\r\n    g.WindowsFocusOrder.clear();\r\n    g.WindowsTempSortBuffer.clear();\r\n    g.CurrentWindow = NULL;\r\n    g.CurrentWindowStack.clear();\r\n    g.WindowsById.Clear();\r\n    g.NavWindow = NULL;\r\n    g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;\r\n    g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL;\r\n    g.MovingWindow = NULL;\r\n    g.ColorStack.clear();\r\n    g.StyleVarStack.clear();\r\n    g.FontStack.clear();\r\n    g.OpenPopupStack.clear();\r\n    g.BeginPopupStack.clear();\r\n\r\n    g.Viewports.clear_delete();\r\n\r\n    g.TabBars.Clear();\r\n    g.CurrentTabBarStack.clear();\r\n    g.ShrinkWidthBuffer.clear();\r\n\r\n    g.ClipperTempData.clear_destruct();\r\n\r\n    g.Tables.Clear();\r\n    g.TablesTempData.clear_destruct();\r\n    g.DrawChannelsTempMergeBuffer.clear();\r\n\r\n    g.ClipboardHandlerData.clear();\r\n    g.MenusIdSubmittedThisFrame.clear();\r\n    g.InputTextState.ClearFreeMemory();\r\n\r\n    g.SettingsWindows.clear();\r\n    g.SettingsHandlers.clear();\r\n\r\n    if (g.LogFile)\r\n    {\r\n#ifndef IMGUI_DISABLE_TTY_FUNCTIONS\r\n        if (g.LogFile != stdout)\r\n#endif\r\n            ImFileClose(g.LogFile);\r\n        g.LogFile = NULL;\r\n    }\r\n    g.LogBuffer.clear();\r\n\r\n    g.Initialized = false;\r\n}\r\n\r\n// FIXME: Add a more explicit sort order in the window structure.\r\nstatic int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)\r\n{\r\n    const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;\r\n    const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs;\r\n    if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))\r\n        return d;\r\n    if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))\r\n        return d;\r\n    return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);\r\n}\r\n\r\nstatic void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)\r\n{\r\n    out_sorted_windows->push_back(window);\r\n    if (window->Active)\r\n    {\r\n        int count = window->DC.ChildWindows.Size;\r\n        ImQsort(window->DC.ChildWindows.Data, (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);\r\n        for (int i = 0; i < count; i++)\r\n        {\r\n            ImGuiWindow* child = window->DC.ChildWindows[i];\r\n            if (child->Active)\r\n                AddWindowToSortBuffer(out_sorted_windows, child);\r\n        }\r\n    }\r\n}\r\n\r\nstatic void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list)\r\n{\r\n    if (draw_list->CmdBuffer.Size == 0)\r\n        return;\r\n    if (draw_list->CmdBuffer.Size == 1 && draw_list->CmdBuffer[0].ElemCount == 0 && draw_list->CmdBuffer[0].UserCallback == NULL)\r\n        return;\r\n\r\n    // Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc.\r\n    // May trigger for you if you are using PrimXXX functions incorrectly.\r\n    IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size);\r\n    IM_ASSERT(draw_list->IdxBuffer.Size == 0 || draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size);\r\n    if (!(draw_list->Flags & ImDrawListFlags_AllowVtxOffset))\r\n        IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size);\r\n\r\n    // Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = unsigned short = 2 bytes = 64K vertices per ImDrawList = per window)\r\n    // If this assert triggers because you are drawing lots of stuff manually:\r\n    // - First, make sure you are coarse clipping yourself and not trying to draw many things outside visible bounds.\r\n    //   Be mindful that the ImDrawList API doesn't filter vertices. Use the Metrics/Debugger window to inspect draw list contents.\r\n    // - If you want large meshes with more than 64K vertices, you can either:\r\n    //   (A) Handle the ImDrawCmd::VtxOffset value in your renderer backend, and set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset'.\r\n    //       Most example backends already support this from 1.71. Pre-1.71 backends won't.\r\n    //       Some graphics API such as GL ES 1/2 don't have a way to offset the starting vertex so it is not supported for them.\r\n    //   (B) Or handle 32-bit indices in your renderer backend, and uncomment '#define ImDrawIdx unsigned int' line in imconfig.h.\r\n    //       Most example backends already support this. For example, the OpenGL example code detect index size at compile-time:\r\n    //         glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);\r\n    //       Your own engine or render API may use different parameters or function calls to specify index sizes.\r\n    //       2 and 4 bytes indices are generally supported by most graphics API.\r\n    // - If for some reason neither of those solutions works for you, a workaround is to call BeginChild()/EndChild() before reaching\r\n    //   the 64K limit to split your draw commands in multiple draw lists.\r\n    if (sizeof(ImDrawIdx) == 2)\r\n        IM_ASSERT(draw_list->_VtxCurrentIdx < (1 << 16) && \"Too many vertices in ImDrawList using 16-bit indices. Read comment above\");\r\n\r\n    out_list->push_back(draw_list);\r\n}\r\n\r\nstatic void AddWindowToDrawData(ImGuiWindow* window, int layer)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiViewportP* viewport = g.Viewports[0];\r\n    g.IO.MetricsRenderWindows++;\r\n    AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[layer], window->DrawList);\r\n    for (int i = 0; i < window->DC.ChildWindows.Size; i++)\r\n    {\r\n        ImGuiWindow* child = window->DC.ChildWindows[i];\r\n        if (IsWindowActiveAndVisible(child)) // Clipped children may have been marked not active\r\n            AddWindowToDrawData(child, layer);\r\n    }\r\n}\r\n\r\nstatic inline int GetWindowDisplayLayer(ImGuiWindow* window)\r\n{\r\n    return (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0;\r\n}\r\n\r\n// Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)\r\nstatic inline void AddRootWindowToDrawData(ImGuiWindow* window)\r\n{\r\n    AddWindowToDrawData(window, GetWindowDisplayLayer(window));\r\n}\r\n\r\nvoid ImDrawDataBuilder::FlattenIntoSingleLayer()\r\n{\r\n    int n = Layers[0].Size;\r\n    int size = n;\r\n    for (int i = 1; i < IM_ARRAYSIZE(Layers); i++)\r\n        size += Layers[i].Size;\r\n    Layers[0].resize(size);\r\n    for (int layer_n = 1; layer_n < IM_ARRAYSIZE(Layers); layer_n++)\r\n    {\r\n        ImVector<ImDrawList*>& layer = Layers[layer_n];\r\n        if (layer.empty())\r\n            continue;\r\n        memcpy(&Layers[0][n], &layer[0], layer.Size * sizeof(ImDrawList*));\r\n        n += layer.Size;\r\n        layer.resize(0);\r\n    }\r\n}\r\n\r\nstatic void SetupViewportDrawData(ImGuiViewportP* viewport, ImVector<ImDrawList*>* draw_lists)\r\n{\r\n    ImGuiIO& io = ImGui::GetIO();\r\n    ImDrawData* draw_data = &viewport->DrawDataP;\r\n    draw_data->Valid = true;\r\n    draw_data->CmdLists = (draw_lists->Size > 0) ? draw_lists->Data : NULL;\r\n    draw_data->CmdListsCount = draw_lists->Size;\r\n    draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;\r\n    draw_data->DisplayPos = viewport->Pos;\r\n    draw_data->DisplaySize = viewport->Size;\r\n    draw_data->FramebufferScale = io.DisplayFramebufferScale;\r\n    for (int n = 0; n < draw_lists->Size; n++)\r\n    {\r\n        ImDrawList* draw_list = draw_lists->Data[n];\r\n        draw_list->_PopUnusedDrawCmd();\r\n        draw_data->TotalVtxCount += draw_list->VtxBuffer.Size;\r\n        draw_data->TotalIdxCount += draw_list->IdxBuffer.Size;\r\n    }\r\n}\r\n\r\n// Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering.\r\n// - When using this function it is sane to ensure that float are perfectly rounded to integer values,\r\n//   so that e.g. (int)(max.x-min.x) in user's render produce correct result.\r\n// - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect():\r\n//   some frequently called functions which to modify both channels and clipping simultaneously tend to use the\r\n//   more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds.\r\nvoid ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);\r\n    window->ClipRect = window->DrawList->_ClipRectStack.back();\r\n}\r\n\r\nvoid ImGui::PopClipRect()\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    window->DrawList->PopClipRect();\r\n    window->ClipRect = window->DrawList->_ClipRectStack.back();\r\n}\r\n\r\nstatic void ImGui::RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col)\r\n{\r\n    if ((col & IM_COL32_A_MASK) == 0)\r\n        return;\r\n\r\n    ImGuiViewportP* viewport = (ImGuiViewportP*)GetMainViewport();\r\n    ImRect viewport_rect = viewport->GetMainRect();\r\n\r\n    // Draw behind window by moving the draw command at the FRONT of the draw list\r\n    {\r\n        // We've already called AddWindowToDrawData() which called DrawList->ChannelsMerge() on DockNodeHost windows,\r\n        // and draw list have been trimmed already, hence the explicit recreation of a draw command if missing.\r\n        // FIXME: This is creating complication, might be simpler if we could inject a drawlist in drawdata at a given position and not attempt to manipulate ImDrawCmd order.\r\n        ImDrawList* draw_list = window->RootWindow->DrawList;\r\n        if (draw_list->CmdBuffer.Size == 0)\r\n            draw_list->AddDrawCmd();\r\n        draw_list->PushClipRect(viewport_rect.Min - ImVec2(1, 1), viewport_rect.Max + ImVec2(1, 1), false); // Ensure ImDrawCmd are not merged\r\n        draw_list->AddRectFilled(viewport_rect.Min, viewport_rect.Max, col);\r\n        ImDrawCmd cmd = draw_list->CmdBuffer.back();\r\n        IM_ASSERT(cmd.ElemCount == 6);\r\n        draw_list->CmdBuffer.pop_back();\r\n        draw_list->CmdBuffer.push_front(cmd);\r\n        draw_list->PopClipRect();\r\n        draw_list->AddDrawCmd(); // We need to create a command as CmdBuffer.back().IdxOffset won't be correct if we append to same command.\r\n    }\r\n}\r\n\r\nImGuiWindow* ImGui::FindBottomMostVisibleWindowWithinBeginStack(ImGuiWindow* parent_window)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* bottom_most_visible_window = parent_window;\r\n    for (int i = FindWindowDisplayIndex(parent_window); i >= 0; i--)\r\n    {\r\n        ImGuiWindow* window = g.Windows[i];\r\n        if (window->Flags & ImGuiWindowFlags_ChildWindow)\r\n            continue;\r\n        if (!IsWindowWithinBeginStackOf(window, parent_window))\r\n            break;\r\n        if (IsWindowActiveAndVisible(window) && GetWindowDisplayLayer(window) <= GetWindowDisplayLayer(parent_window))\r\n            bottom_most_visible_window = window;\r\n    }\r\n    return bottom_most_visible_window;\r\n}\r\n\r\nstatic void ImGui::RenderDimmedBackgrounds()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* modal_window = GetTopMostAndVisiblePopupModal();\r\n    if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)\r\n        return;\r\n    const bool dim_bg_for_modal = (modal_window != NULL);\r\n    const bool dim_bg_for_window_list = (g.NavWindowingTargetAnim != NULL && g.NavWindowingTargetAnim->Active);\r\n    if (!dim_bg_for_modal && !dim_bg_for_window_list)\r\n        return;\r\n\r\n    if (dim_bg_for_modal)\r\n    {\r\n        // Draw dimming behind modal or a begin stack child, whichever comes first in draw order.\r\n        ImGuiWindow* dim_behind_window = FindBottomMostVisibleWindowWithinBeginStack(modal_window);\r\n        RenderDimmedBackgroundBehindWindow(dim_behind_window, GetColorU32(ImGuiCol_ModalWindowDimBg, g.DimBgRatio));\r\n    }\r\n    else if (dim_bg_for_window_list)\r\n    {\r\n        // Draw dimming behind CTRL+Tab target window\r\n        RenderDimmedBackgroundBehindWindow(g.NavWindowingTargetAnim, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));\r\n\r\n        // Draw border around CTRL+Tab target window\r\n        ImGuiWindow* window = g.NavWindowingTargetAnim;\r\n        ImGuiViewport* viewport = GetMainViewport();\r\n        float distance = g.FontSize;\r\n        ImRect bb = window->Rect();\r\n        bb.Expand(distance);\r\n        if (bb.GetWidth() >= viewport->Size.x && bb.GetHeight() >= viewport->Size.y)\r\n            bb.Expand(-distance - 1.0f); // If a window fits the entire viewport, adjust its highlight inward\r\n        if (window->DrawList->CmdBuffer.Size == 0)\r\n            window->DrawList->AddDrawCmd();\r\n        window->DrawList->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size);\r\n        window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), window->WindowRounding, 0, 3.0f);\r\n        window->DrawList->PopClipRect();\r\n    }\r\n}\r\n\r\n// This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal.\r\nvoid ImGui::EndFrame()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(g.Initialized);\r\n\r\n    // Don't process EndFrame() multiple times.\r\n    if (g.FrameCountEnded == g.FrameCount)\r\n        return;\r\n    IM_ASSERT(g.WithinFrameScope && \"Forgot to call ImGui::NewFrame()?\");\r\n\r\n    CallContextHooks(&g, ImGuiContextHookType_EndFramePre);\r\n\r\n    ErrorCheckEndFrameSanityChecks();\r\n\r\n    // Notify Platform/OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)\r\n    if (g.IO.SetPlatformImeDataFn && memcmp(&g.PlatformImeData, &g.PlatformImeDataPrev, sizeof(ImGuiPlatformImeData)) != 0)\r\n        g.IO.SetPlatformImeDataFn(GetMainViewport(), &g.PlatformImeData);\r\n\r\n    // Hide implicit/fallback \"Debug\" window if it hasn't been used\r\n    g.WithinFrameScopeWithImplicitWindow = false;\r\n    if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)\r\n        g.CurrentWindow->Active = false;\r\n    End();\r\n\r\n    // Update navigation: CTRL+Tab, wrap-around requests\r\n    NavEndFrame();\r\n\r\n    // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)\r\n    if (g.DragDropActive)\r\n    {\r\n        bool is_delivered = g.DragDropPayload.Delivery;\r\n        bool is_elapsed = (g.DragDropPayload.DataFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceAutoExpirePayload) || !IsMouseDown(g.DragDropMouseButton));\r\n        if (is_delivered || is_elapsed)\r\n            ClearDragDrop();\r\n    }\r\n\r\n    // Drag and Drop: Fallback for source tooltip. This is not ideal but better than nothing.\r\n    if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))\r\n    {\r\n        g.DragDropWithinSource = true;\r\n        SetTooltip(\"...\");\r\n        g.DragDropWithinSource = false;\r\n    }\r\n\r\n    // End frame\r\n    g.WithinFrameScope = false;\r\n    g.FrameCountEnded = g.FrameCount;\r\n\r\n    // Initiate moving window + handle left-click and right-click focus\r\n    UpdateMouseMovingWindowEndFrame();\r\n\r\n    // Sort the window list so that all child windows are after their parent\r\n    // We cannot do that on FocusWindow() because children may not exist yet\r\n    g.WindowsTempSortBuffer.resize(0);\r\n    g.WindowsTempSortBuffer.reserve(g.Windows.Size);\r\n    for (int i = 0; i != g.Windows.Size; i++)\r\n    {\r\n        ImGuiWindow* window = g.Windows[i];\r\n        if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow))       // if a child is active its parent will add it\r\n            continue;\r\n        AddWindowToSortBuffer(&g.WindowsTempSortBuffer, window);\r\n    }\r\n\r\n    // This usually assert if there is a mismatch between the ImGuiWindowFlags_ChildWindow / ParentWindow values and DC.ChildWindows[] in parents, aka we've done something wrong.\r\n    IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size);\r\n    g.Windows.swap(g.WindowsTempSortBuffer);\r\n    g.IO.MetricsActiveWindows = g.WindowsActiveCount;\r\n\r\n    // Unlock font atlas\r\n    g.IO.Fonts->Locked = false;\r\n\r\n    // Clear Input data for next frame\r\n    g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;\r\n    g.IO.InputQueueCharacters.resize(0);\r\n    g.IO.KeyModsPrev = g.IO.KeyMods; // doing it here is better than in NewFrame() as we'll tolerate backend writing to KeyMods. If we want to firmly disallow it we should detect it.\r\n    memset(g.IO.NavInputs, 0, sizeof(g.IO.NavInputs));\r\n\r\n    CallContextHooks(&g, ImGuiContextHookType_EndFramePost);\r\n}\r\n\r\n// Prepare the data for rendering so you can call GetDrawData()\r\n// (As with anything within the ImGui:: namspace this doesn't touch your GPU or graphics API at all:\r\n// it is the role of the ImGui_ImplXXXX_RenderDrawData() function provided by the renderer backend)\r\nvoid ImGui::Render()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(g.Initialized);\r\n\r\n    if (g.FrameCountEnded != g.FrameCount)\r\n        EndFrame();\r\n    const bool first_render_of_frame = (g.FrameCountRendered != g.FrameCount);\r\n    g.FrameCountRendered = g.FrameCount;\r\n    g.IO.MetricsRenderWindows = 0;\r\n\r\n    CallContextHooks(&g, ImGuiContextHookType_RenderPre);\r\n\r\n    // Add background ImDrawList (for each active viewport)\r\n    for (int n = 0; n != g.Viewports.Size; n++)\r\n    {\r\n        ImGuiViewportP* viewport = g.Viewports[n];\r\n        viewport->DrawDataBuilder.Clear();\r\n        if (viewport->DrawLists[0] != NULL)\r\n            AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[0], GetBackgroundDrawList(viewport));\r\n    }\r\n\r\n    // Draw modal/window whitening backgrounds\r\n    if (first_render_of_frame)\r\n        RenderDimmedBackgrounds();\r\n\r\n    // Add ImDrawList to render\r\n    ImGuiWindow* windows_to_render_top_most[2];\r\n    windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindow : NULL;\r\n    windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingListWindow : NULL);\r\n    for (int n = 0; n != g.Windows.Size; n++)\r\n    {\r\n        ImGuiWindow* window = g.Windows[n];\r\n        IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive \"warning C6011: Dereferencing NULL pointer 'window'\"\r\n        if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1])\r\n            AddRootWindowToDrawData(window);\r\n    }\r\n    for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++)\r\n        if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window\r\n            AddRootWindowToDrawData(windows_to_render_top_most[n]);\r\n\r\n    // Setup ImDrawData structures for end-user\r\n    g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = 0;\r\n    for (int n = 0; n < g.Viewports.Size; n++)\r\n    {\r\n        ImGuiViewportP* viewport = g.Viewports[n];\r\n        viewport->DrawDataBuilder.FlattenIntoSingleLayer();\r\n\r\n        // Draw software mouse cursor if requested by io.MouseDrawCursor flag\r\n        if (g.IO.MouseDrawCursor && first_render_of_frame)\r\n            RenderMouseCursor(GetForegroundDrawList(viewport), g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48));\r\n\r\n        // Add foreground ImDrawList (for each active viewport)\r\n        if (viewport->DrawLists[1] != NULL)\r\n            AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[0], GetForegroundDrawList(viewport));\r\n\r\n        SetupViewportDrawData(viewport, &viewport->DrawDataBuilder.Layers[0]);\r\n        ImDrawData* draw_data = &viewport->DrawDataP;\r\n        g.IO.MetricsRenderVertices += draw_data->TotalVtxCount;\r\n        g.IO.MetricsRenderIndices += draw_data->TotalIdxCount;\r\n    }\r\n\r\n    CallContextHooks(&g, ImGuiContextHookType_RenderPost);\r\n}\r\n\r\n// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.\r\n// CalcTextSize(\"\") should return ImVec2(0.0f, g.FontSize)\r\nImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n\r\n    const char* text_display_end;\r\n    if (hide_text_after_double_hash)\r\n        text_display_end = FindRenderedTextEnd(text, text_end);      // Hide anything after a '##' string\r\n    else\r\n        text_display_end = text_end;\r\n\r\n    ImFont* font = g.Font;\r\n    const float font_size = g.FontSize;\r\n    if (text == text_display_end)\r\n        return ImVec2(0.0f, font_size);\r\n    ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);\r\n\r\n    // Round\r\n    // FIXME: This has been here since Dec 2015 (7b0bf230) but down the line we want this out.\r\n    // FIXME: Investigate using ceilf or e.g.\r\n    // - https://git.musl-libc.org/cgit/musl/tree/src/math/ceilf.c\r\n    // - https://embarkstudios.github.io/rust-gpu/api/src/libm/math/ceilf.rs.html\r\n    text_size.x = IM_FLOOR(text_size.x + 0.99999f);\r\n\r\n    return text_size;\r\n}\r\n\r\n// Find window given position, search front-to-back\r\n// FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically\r\n// with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is\r\n// called, aka before the next Begin(). Moving window isn't affected.\r\nstatic void FindHoveredWindow()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n\r\n    ImGuiWindow* hovered_window = NULL;\r\n    ImGuiWindow* hovered_window_ignoring_moving_window = NULL;\r\n    if (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))\r\n        hovered_window = g.MovingWindow;\r\n\r\n    ImVec2 padding_regular = g.Style.TouchExtraPadding;\r\n    ImVec2 padding_for_resize = g.IO.ConfigWindowsResizeFromEdges ? g.WindowsHoverPadding : padding_regular;\r\n    for (int i = g.Windows.Size - 1; i >= 0; i--)\r\n    {\r\n        ImGuiWindow* window = g.Windows[i];\r\n        IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.\r\n        if (!window->Active || window->Hidden)\r\n            continue;\r\n        if (window->Flags & ImGuiWindowFlags_NoMouseInputs)\r\n            continue;\r\n\r\n        // Using the clipped AABB, a child window will typically be clipped by its parent (not always)\r\n        ImRect bb(window->OuterRectClipped);\r\n        if (window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize))\r\n            bb.Expand(padding_regular);\r\n        else\r\n            bb.Expand(padding_for_resize);\r\n        if (!bb.Contains(g.IO.MousePos))\r\n            continue;\r\n\r\n        // Support for one rectangular hole in any given window\r\n        // FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512)\r\n        if (window->HitTestHoleSize.x != 0)\r\n        {\r\n            ImVec2 hole_pos(window->Pos.x + (float)window->HitTestHoleOffset.x, window->Pos.y + (float)window->HitTestHoleOffset.y);\r\n            ImVec2 hole_size((float)window->HitTestHoleSize.x, (float)window->HitTestHoleSize.y);\r\n            if (ImRect(hole_pos, hole_pos + hole_size).Contains(g.IO.MousePos))\r\n                continue;\r\n        }\r\n\r\n        if (hovered_window == NULL)\r\n            hovered_window = window;\r\n        IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.\r\n        if (hovered_window_ignoring_moving_window == NULL && (!g.MovingWindow || window->RootWindow != g.MovingWindow->RootWindow))\r\n            hovered_window_ignoring_moving_window = window;\r\n        if (hovered_window && hovered_window_ignoring_moving_window)\r\n            break;\r\n    }\r\n\r\n    g.HoveredWindow = hovered_window;\r\n    g.HoveredWindowUnderMovingWindow = hovered_window_ignoring_moving_window;\r\n}\r\n\r\nbool ImGui::IsItemActive()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    if (g.ActiveId)\r\n        return g.ActiveId == g.LastItemData.ID;\r\n    return false;\r\n}\r\n\r\nbool ImGui::IsItemActivated()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    if (g.ActiveId)\r\n        if (g.ActiveId == g.LastItemData.ID && g.ActiveIdPreviousFrame != g.LastItemData.ID)\r\n            return true;\r\n    return false;\r\n}\r\n\r\nbool ImGui::IsItemDeactivated()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDeactivated)\r\n        return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Deactivated) != 0;\r\n    return (g.ActiveIdPreviousFrame == g.LastItemData.ID && g.ActiveIdPreviousFrame != 0 && g.ActiveId != g.LastItemData.ID);\r\n}\r\n\r\nbool ImGui::IsItemDeactivatedAfterEdit()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore));\r\n}\r\n\r\n// == GetItemID() == GetFocusID()\r\nbool ImGui::IsItemFocused()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    if (g.NavId != g.LastItemData.ID || g.NavId == 0)\r\n        return false;\r\n    return true;\r\n}\r\n\r\n// Important: this can be useful but it is NOT equivalent to the behavior of e.g.Button()!\r\n// Most widgets have specific reactions based on mouse-up/down state, mouse position etc.\r\nbool ImGui::IsItemClicked(ImGuiMouseButton mouse_button)\r\n{\r\n    return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None);\r\n}\r\n\r\nbool ImGui::IsItemToggledOpen()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false;\r\n}\r\n\r\nbool ImGui::IsItemToggledSelection()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false;\r\n}\r\n\r\nbool ImGui::IsAnyItemHovered()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;\r\n}\r\n\r\nbool ImGui::IsAnyItemActive()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    return g.ActiveId != 0;\r\n}\r\n\r\nbool ImGui::IsAnyItemFocused()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    return g.NavId != 0 && !g.NavDisableHighlight;\r\n}\r\n\r\nbool ImGui::IsItemVisible()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    return g.CurrentWindow->ClipRect.Overlaps(g.LastItemData.Rect);\r\n}\r\n\r\nbool ImGui::IsItemEdited()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Edited) != 0;\r\n}\r\n\r\n// Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.\r\n// FIXME: Although this is exposed, its interaction and ideal idiom with using ImGuiButtonFlags_AllowItemOverlap flag are extremely confusing, need rework.\r\nvoid ImGui::SetItemAllowOverlap()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiID id = g.LastItemData.ID;\r\n    if (g.HoveredId == id)\r\n        g.HoveredIdAllowOverlap = true;\r\n    if (g.ActiveId == id)\r\n        g.ActiveIdAllowOverlap = true;\r\n}\r\n\r\nvoid ImGui::SetItemUsingMouseWheel()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiID id = g.LastItemData.ID;\r\n    if (g.HoveredId == id)\r\n        g.HoveredIdUsingMouseWheel = true;\r\n    if (g.ActiveId == id)\r\n        g.ActiveIdUsingMouseWheel = true;\r\n}\r\n\r\nvoid ImGui::SetActiveIdUsingNavAndKeys()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(g.ActiveId != 0);\r\n    g.ActiveIdUsingNavDirMask = ~(ImU32)0;\r\n    g.ActiveIdUsingNavInputMask = ~(ImU32)0;\r\n    g.ActiveIdUsingKeyInputMask.SetAllBits();\r\n    NavMoveRequestCancel();\r\n}\r\n\r\nImVec2 ImGui::GetItemRectMin()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    return g.LastItemData.Rect.Min;\r\n}\r\n\r\nImVec2 ImGui::GetItemRectMax()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    return g.LastItemData.Rect.Max;\r\n}\r\n\r\nImVec2 ImGui::GetItemRectSize()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    return g.LastItemData.Rect.GetSize();\r\n}\r\n\r\nbool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* parent_window = g.CurrentWindow;\r\n\r\n    flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_ChildWindow;\r\n    flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove);  // Inherit the NoMove flag\r\n\r\n    // Size\r\n    const ImVec2 content_avail = GetContentRegionAvail();\r\n    ImVec2 size = ImFloor(size_arg);\r\n    const int auto_fit_axises = ((size.x == 0.0f) ? (1 << ImGuiAxis_X) : 0x00) | ((size.y == 0.0f) ? (1 << ImGuiAxis_Y) : 0x00);\r\n    if (size.x <= 0.0f)\r\n        size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)\r\n    if (size.y <= 0.0f)\r\n        size.y = ImMax(content_avail.y + size.y, 4.0f);\r\n    SetNextWindowSize(size);\r\n\r\n    // Build up name. If you need to append to a same child from multiple location in the ID stack, use BeginChild(ImGuiID id) with a stable value.\r\n    if (name)\r\n        ImFormatString(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), \"%s/%s_%08X\", parent_window->Name, name, id);\r\n    else\r\n        ImFormatString(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), \"%s/%08X\", parent_window->Name, id);\r\n\r\n    const float backup_border_size = g.Style.ChildBorderSize;\r\n    if (!border)\r\n        g.Style.ChildBorderSize = 0.0f;\r\n    bool ret = Begin(g.TempBuffer, NULL, flags);\r\n    g.Style.ChildBorderSize = backup_border_size;\r\n\r\n    ImGuiWindow* child_window = g.CurrentWindow;\r\n    child_window->ChildId = id;\r\n    child_window->AutoFitChildAxises = (ImS8)auto_fit_axises;\r\n\r\n    // Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.\r\n    // While this is not really documented/defined, it seems that the expected thing to do.\r\n    if (child_window->BeginCount == 1)\r\n        parent_window->DC.CursorPos = child_window->Pos;\r\n\r\n    // Process navigation-in immediately so NavInit can run on first frame\r\n    if (g.NavActivateId == id && !(flags & ImGuiWindowFlags_NavFlattened) && (child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavHasScroll))\r\n    {\r\n        FocusWindow(child_window);\r\n        NavInitWindow(child_window, false);\r\n        SetActiveID(id + 1, child_window); // Steal ActiveId with another arbitrary id so that key-press won't activate child item\r\n        g.ActiveIdSource = ImGuiInputSource_Nav;\r\n    }\r\n    return ret;\r\n}\r\n\r\nbool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    return BeginChildEx(str_id, window->GetID(str_id), size_arg, border, extra_flags);\r\n}\r\n\r\nbool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)\r\n{\r\n    IM_ASSERT(id != 0);\r\n    return BeginChildEx(NULL, id, size_arg, border, extra_flags);\r\n}\r\n\r\nvoid ImGui::EndChild()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n\r\n    IM_ASSERT(g.WithinEndChild == false);\r\n    IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow);   // Mismatched BeginChild()/EndChild() calls\r\n\r\n    g.WithinEndChild = true;\r\n    if (window->BeginCount > 1)\r\n    {\r\n        End();\r\n    }\r\n    else\r\n    {\r\n        ImVec2 sz = window->Size;\r\n        if (window->AutoFitChildAxises & (1 << ImGuiAxis_X)) // Arbitrary minimum zero-ish child size of 4.0f causes less trouble than a 0.0f\r\n            sz.x = ImMax(4.0f, sz.x);\r\n        if (window->AutoFitChildAxises & (1 << ImGuiAxis_Y))\r\n            sz.y = ImMax(4.0f, sz.y);\r\n        End();\r\n\r\n        ImGuiWindow* parent_window = g.CurrentWindow;\r\n        ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + sz);\r\n        ItemSize(sz);\r\n        if ((window->DC.NavLayersActiveMask != 0 || window->DC.NavHasScroll) && !(window->Flags & ImGuiWindowFlags_NavFlattened))\r\n        {\r\n            ItemAdd(bb, window->ChildId);\r\n            RenderNavHighlight(bb, window->ChildId);\r\n\r\n            // When browsing a window that has no activable items (scroll only) we keep a highlight on the child (pass g.NavId to trick into always displaying)\r\n            if (window->DC.NavLayersActiveMask == 0 && window == g.NavWindow)\r\n                RenderNavHighlight(ImRect(bb.Min - ImVec2(2, 2), bb.Max + ImVec2(2, 2)), g.NavId, ImGuiNavHighlightFlags_TypeThin);\r\n        }\r\n        else\r\n        {\r\n            // Not navigable into\r\n            ItemAdd(bb, 0);\r\n        }\r\n        if (g.HoveredWindow == window)\r\n            g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;\r\n    }\r\n    g.WithinEndChild = false;\r\n    g.LogLinePosY = -FLT_MAX; // To enforce a carriage return\r\n}\r\n\r\n// Helper to create a child window / scrolling region that looks like a normal widget frame.\r\nbool ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    const ImGuiStyle& style = g.Style;\r\n    PushStyleColor(ImGuiCol_ChildBg, style.Colors[ImGuiCol_FrameBg]);\r\n    PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding);\r\n    PushStyleVar(ImGuiStyleVar_ChildBorderSize, style.FrameBorderSize);\r\n    PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding);\r\n    bool ret = BeginChild(id, size, true, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags);\r\n    PopStyleVar(3);\r\n    PopStyleColor();\r\n    return ret;\r\n}\r\n\r\nvoid ImGui::EndChildFrame()\r\n{\r\n    EndChild();\r\n}\r\n\r\nstatic void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)\r\n{\r\n    window->SetWindowPosAllowFlags       = enabled ? (window->SetWindowPosAllowFlags       | flags) : (window->SetWindowPosAllowFlags       & ~flags);\r\n    window->SetWindowSizeAllowFlags      = enabled ? (window->SetWindowSizeAllowFlags      | flags) : (window->SetWindowSizeAllowFlags      & ~flags);\r\n    window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);\r\n}\r\n\r\nImGuiWindow* ImGui::FindWindowByID(ImGuiID id)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id);\r\n}\r\n\r\nImGuiWindow* ImGui::FindWindowByName(const char* name)\r\n{\r\n    ImGuiID id = ImHashStr(name);\r\n    return FindWindowByID(id);\r\n}\r\n\r\nstatic void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)\r\n{\r\n    window->Pos = ImFloor(ImVec2(settings->Pos.x, settings->Pos.y));\r\n    if (settings->Size.x > 0 && settings->Size.y > 0)\r\n        window->Size = window->SizeFull = ImFloor(ImVec2(settings->Size.x, settings->Size.y));\r\n    window->Collapsed = settings->Collapsed;\r\n}\r\n\r\nstatic void UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n\r\n    const bool new_is_explicit_child = (new_flags & ImGuiWindowFlags_ChildWindow) != 0;\r\n    const bool child_flag_changed = new_is_explicit_child != window->IsExplicitChild;\r\n    if ((just_created || child_flag_changed) && !new_is_explicit_child)\r\n    {\r\n        IM_ASSERT(!g.WindowsFocusOrder.contains(window));\r\n        g.WindowsFocusOrder.push_back(window);\r\n        window->FocusOrder = (short)(g.WindowsFocusOrder.Size - 1);\r\n    }\r\n    else if (!just_created && child_flag_changed && new_is_explicit_child)\r\n    {\r\n        IM_ASSERT(g.WindowsFocusOrder[window->FocusOrder] == window);\r\n        for (int n = window->FocusOrder + 1; n < g.WindowsFocusOrder.Size; n++)\r\n            g.WindowsFocusOrder[n]->FocusOrder--;\r\n        g.WindowsFocusOrder.erase(g.WindowsFocusOrder.Data + window->FocusOrder);\r\n        window->FocusOrder = -1;\r\n    }\r\n    window->IsExplicitChild = new_is_explicit_child;\r\n}\r\n\r\nstatic ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    //IMGUI_DEBUG_LOG(\"CreateNewWindow '%s', flags = 0x%08X\\n\", name, flags);\r\n\r\n    // Create window the first time\r\n    ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);\r\n    window->Flags = flags;\r\n    g.WindowsById.SetVoidPtr(window->ID, window);\r\n\r\n    // Default/arbitrary window position. Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.\r\n    const ImGuiViewport* main_viewport = ImGui::GetMainViewport();\r\n    window->Pos = main_viewport->Pos + ImVec2(60, 60);\r\n\r\n    // User can disable loading and saving of settings. Tooltip and child windows also don't store settings.\r\n    if (!(flags & ImGuiWindowFlags_NoSavedSettings))\r\n        if (ImGuiWindowSettings* settings = ImGui::FindWindowSettings(window->ID))\r\n        {\r\n            // Retrieve settings from .ini file\r\n            window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);\r\n            SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);\r\n            ApplyWindowSettings(window, settings);\r\n        }\r\n    window->DC.CursorStartPos = window->DC.CursorMaxPos = window->Pos; // So first call to CalcContentSize() doesn't return crazy values\r\n\r\n    if ((flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)\r\n    {\r\n        window->AutoFitFramesX = window->AutoFitFramesY = 2;\r\n        window->AutoFitOnlyGrows = false;\r\n    }\r\n    else\r\n    {\r\n        if (window->Size.x <= 0.0f)\r\n            window->AutoFitFramesX = 2;\r\n        if (window->Size.y <= 0.0f)\r\n            window->AutoFitFramesY = 2;\r\n        window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);\r\n    }\r\n\r\n    if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)\r\n        g.Windows.push_front(window); // Quite slow but rare and only once\r\n    else\r\n        g.Windows.push_back(window);\r\n    UpdateWindowInFocusOrderList(window, true, window->Flags);\r\n\r\n    return window;\r\n}\r\n\r\nstatic ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, const ImVec2& size_desired)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImVec2 new_size = size_desired;\r\n    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)\r\n    {\r\n        // Using -1,-1 on either X/Y axis to preserve the current size.\r\n        ImRect cr = g.NextWindowData.SizeConstraintRect;\r\n        new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;\r\n        new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;\r\n        if (g.NextWindowData.SizeCallback)\r\n        {\r\n            ImGuiSizeCallbackData data;\r\n            data.UserData = g.NextWindowData.SizeCallbackUserData;\r\n            data.Pos = window->Pos;\r\n            data.CurrentSize = window->SizeFull;\r\n            data.DesiredSize = new_size;\r\n            g.NextWindowData.SizeCallback(&data);\r\n            new_size = data.DesiredSize;\r\n        }\r\n        new_size.x = IM_FLOOR(new_size.x);\r\n        new_size.y = IM_FLOOR(new_size.y);\r\n    }\r\n\r\n    // Minimum size\r\n    if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize)))\r\n    {\r\n        ImGuiWindow* window_for_height = window;\r\n        const float decoration_up_height = window_for_height->TitleBarHeight() + window_for_height->MenuBarHeight();\r\n        new_size = ImMax(new_size, g.Style.WindowMinSize);\r\n        new_size.y = ImMax(new_size.y, decoration_up_height + ImMax(0.0f, g.Style.WindowRounding - 1.0f)); // Reduce artifacts with very small windows\r\n    }\r\n    return new_size;\r\n}\r\n\r\nstatic void CalcWindowContentSizes(ImGuiWindow* window, ImVec2* content_size_current, ImVec2* content_size_ideal)\r\n{\r\n    bool preserve_old_content_sizes = false;\r\n    if (window->Collapsed && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)\r\n        preserve_old_content_sizes = true;\r\n    else if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0)\r\n        preserve_old_content_sizes = true;\r\n    if (preserve_old_content_sizes)\r\n    {\r\n        *content_size_current = window->ContentSize;\r\n        *content_size_ideal = window->ContentSizeIdeal;\r\n        return;\r\n    }\r\n\r\n    content_size_current->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_FLOOR(window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);\r\n    content_size_current->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_FLOOR(window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);\r\n    content_size_ideal->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_FLOOR(ImMax(window->DC.CursorMaxPos.x, window->DC.IdealMaxPos.x) - window->DC.CursorStartPos.x);\r\n    content_size_ideal->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_FLOOR(ImMax(window->DC.CursorMaxPos.y, window->DC.IdealMaxPos.y) - window->DC.CursorStartPos.y);\r\n}\r\n\r\nstatic ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiStyle& style = g.Style;\r\n    const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight();\r\n    ImVec2 size_pad = window->WindowPadding * 2.0f;\r\n    ImVec2 size_desired = size_contents + size_pad + ImVec2(0.0f, decoration_up_height);\r\n    if (window->Flags & ImGuiWindowFlags_Tooltip)\r\n    {\r\n        // Tooltip always resize\r\n        return size_desired;\r\n    }\r\n    else\r\n    {\r\n        // Maximum window size is determined by the viewport size or monitor size\r\n        const bool is_popup = (window->Flags & ImGuiWindowFlags_Popup) != 0;\r\n        const bool is_menu = (window->Flags & ImGuiWindowFlags_ChildMenu) != 0;\r\n        ImVec2 size_min = style.WindowMinSize;\r\n        if (is_popup || is_menu) // Popups and menus bypass style.WindowMinSize by default, but we give then a non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups)\r\n            size_min = ImMin(size_min, ImVec2(4.0f, 4.0f));\r\n\r\n        // FIXME-VIEWPORT-WORKAREA: May want to use GetWorkSize() instead of Size depending on the type of windows?\r\n        ImVec2 avail_size = ImGui::GetMainViewport()->Size;\r\n        ImVec2 size_auto_fit = ImClamp(size_desired, size_min, ImMax(size_min, avail_size - style.DisplaySafeAreaPadding * 2.0f));\r\n\r\n        // When the window cannot fit all contents (either because of constraints, either because screen is too small),\r\n        // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding.\r\n        ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit);\r\n        bool will_have_scrollbar_x = (size_auto_fit_after_constraint.x - size_pad.x - 0.0f                 < size_contents.x && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar);\r\n        bool will_have_scrollbar_y = (size_auto_fit_after_constraint.y - size_pad.y - decoration_up_height < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysVerticalScrollbar);\r\n        if (will_have_scrollbar_x)\r\n            size_auto_fit.y += style.ScrollbarSize;\r\n        if (will_have_scrollbar_y)\r\n            size_auto_fit.x += style.ScrollbarSize;\r\n        return size_auto_fit;\r\n    }\r\n}\r\n\r\nImVec2 ImGui::CalcWindowNextAutoFitSize(ImGuiWindow* window)\r\n{\r\n    ImVec2 size_contents_current;\r\n    ImVec2 size_contents_ideal;\r\n    CalcWindowContentSizes(window, &size_contents_current, &size_contents_ideal);\r\n    ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents_ideal);\r\n    ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_auto_fit);\r\n    return size_final;\r\n}\r\n\r\nstatic ImGuiCol GetWindowBgColorIdx(ImGuiWindow* window)\r\n{\r\n    if (window->Flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))\r\n        return ImGuiCol_PopupBg;\r\n    if (window->Flags & ImGuiWindowFlags_ChildWindow)\r\n        return ImGuiCol_ChildBg;\r\n    return ImGuiCol_WindowBg;\r\n}\r\n\r\nstatic void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)\r\n{\r\n    ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm);                // Expected window upper-left\r\n    ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right\r\n    ImVec2 size_expected = pos_max - pos_min;\r\n    ImVec2 size_constrained = CalcWindowSizeAfterConstraint(window, size_expected);\r\n    *out_pos = pos_min;\r\n    if (corner_norm.x == 0.0f)\r\n        out_pos->x -= (size_constrained.x - size_expected.x);\r\n    if (corner_norm.y == 0.0f)\r\n        out_pos->y -= (size_constrained.y - size_expected.y);\r\n    *out_size = size_constrained;\r\n}\r\n\r\n// Data for resizing from corner\r\nstruct ImGuiResizeGripDef\r\n{\r\n    ImVec2  CornerPosN;\r\n    ImVec2  InnerDir;\r\n    int     AngleMin12, AngleMax12;\r\n};\r\nstatic const ImGuiResizeGripDef resize_grip_def[4] =\r\n{\r\n    { ImVec2(1, 1), ImVec2(-1, -1), 0, 3 },  // Lower-right\r\n    { ImVec2(0, 1), ImVec2(+1, -1), 3, 6 },  // Lower-left\r\n    { ImVec2(0, 0), ImVec2(+1, +1), 6, 9 },  // Upper-left (Unused)\r\n    { ImVec2(1, 0), ImVec2(-1, +1), 9, 12 }  // Upper-right (Unused)\r\n};\r\n\r\n// Data for resizing from borders\r\nstruct ImGuiResizeBorderDef\r\n{\r\n    ImVec2 InnerDir;\r\n    ImVec2 SegmentN1, SegmentN2;\r\n    float  OuterAngle;\r\n};\r\nstatic const ImGuiResizeBorderDef resize_border_def[4] =\r\n{\r\n    { ImVec2(+1, 0), ImVec2(0, 1), ImVec2(0, 0), IM_PI * 1.00f }, // Left\r\n    { ImVec2(-1, 0), ImVec2(1, 0), ImVec2(1, 1), IM_PI * 0.00f }, // Right\r\n    { ImVec2(0, +1), ImVec2(0, 0), ImVec2(1, 0), IM_PI * 1.50f }, // Up\r\n    { ImVec2(0, -1), ImVec2(1, 1), ImVec2(0, 1), IM_PI * 0.50f }  // Down\r\n};\r\n\r\nstatic ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)\r\n{\r\n    ImRect rect = window->Rect();\r\n    if (thickness == 0.0f)\r\n        rect.Max -= ImVec2(1, 1);\r\n    if (border_n == ImGuiDir_Left)  { return ImRect(rect.Min.x - thickness,    rect.Min.y + perp_padding, rect.Min.x + thickness,    rect.Max.y - perp_padding); }\r\n    if (border_n == ImGuiDir_Right) { return ImRect(rect.Max.x - thickness,    rect.Min.y + perp_padding, rect.Max.x + thickness,    rect.Max.y - perp_padding); }\r\n    if (border_n == ImGuiDir_Up)    { return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness,    rect.Max.x - perp_padding, rect.Min.y + thickness);    }\r\n    if (border_n == ImGuiDir_Down)  { return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness,    rect.Max.x - perp_padding, rect.Max.y + thickness);    }\r\n    IM_ASSERT(0);\r\n    return ImRect();\r\n}\r\n\r\n// 0..3: corners (Lower-right, Lower-left, Unused, Unused)\r\nImGuiID ImGui::GetWindowResizeCornerID(ImGuiWindow* window, int n)\r\n{\r\n    IM_ASSERT(n >= 0 && n < 4);\r\n    ImGuiID id = window->ID;\r\n    id = ImHashStr(\"#RESIZE\", 0, id);\r\n    id = ImHashData(&n, sizeof(int), id);\r\n    return id;\r\n}\r\n\r\n// Borders (Left, Right, Up, Down)\r\nImGuiID ImGui::GetWindowResizeBorderID(ImGuiWindow* window, ImGuiDir dir)\r\n{\r\n    IM_ASSERT(dir >= 0 && dir < 4);\r\n    int n = (int)dir + 4;\r\n    ImGuiID id = window->ID;\r\n    id = ImHashStr(\"#RESIZE\", 0, id);\r\n    id = ImHashData(&n, sizeof(int), id);\r\n    return id;\r\n}\r\n\r\n// Handle resize for: Resize Grips, Borders, Gamepad\r\n// Return true when using auto-fit (double click on resize grip)\r\nstatic bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindowFlags flags = window->Flags;\r\n\r\n    if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)\r\n        return false;\r\n    if (window->WasActive == false) // Early out to avoid running this code for e.g. an hidden implicit/fallback Debug window.\r\n        return false;\r\n\r\n    bool ret_auto_fit = false;\r\n    const int resize_border_count = g.IO.ConfigWindowsResizeFromEdges ? 4 : 0;\r\n    const float grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));\r\n    const float grip_hover_inner_size = IM_FLOOR(grip_draw_size * 0.75f);\r\n    const float grip_hover_outer_size = g.IO.ConfigWindowsResizeFromEdges ? WINDOWS_HOVER_PADDING : 0.0f;\r\n\r\n    ImVec2 pos_target(FLT_MAX, FLT_MAX);\r\n    ImVec2 size_target(FLT_MAX, FLT_MAX);\r\n\r\n    // Resize grips and borders are on layer 1\r\n    window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;\r\n\r\n    // Manual resize grips\r\n    PushID(\"#RESIZE\");\r\n    for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)\r\n    {\r\n        const ImGuiResizeGripDef& def = resize_grip_def[resize_grip_n];\r\n        const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, def.CornerPosN);\r\n\r\n        // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window\r\n        bool hovered, held;\r\n        ImRect resize_rect(corner - def.InnerDir * grip_hover_outer_size, corner + def.InnerDir * grip_hover_inner_size);\r\n        if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x);\r\n        if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y);\r\n        ImGuiID resize_grip_id = window->GetID(resize_grip_n); // == GetWindowResizeCornerID()\r\n        ButtonBehavior(resize_rect, resize_grip_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);\r\n        //GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));\r\n        if (hovered || held)\r\n            g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;\r\n\r\n        if (held && g.IO.MouseClickedCount[0] == 2 && resize_grip_n == 0)\r\n        {\r\n            // Manual auto-fit when double-clicking\r\n            size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit);\r\n            ret_auto_fit = true;\r\n            ClearActiveID();\r\n        }\r\n        else if (held)\r\n        {\r\n            // Resize from any of the four corners\r\n            // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position\r\n            ImVec2 clamp_min = ImVec2(def.CornerPosN.x == 1.0f ? visibility_rect.Min.x : -FLT_MAX, def.CornerPosN.y == 1.0f ? visibility_rect.Min.y : -FLT_MAX);\r\n            ImVec2 clamp_max = ImVec2(def.CornerPosN.x == 0.0f ? visibility_rect.Max.x : +FLT_MAX, def.CornerPosN.y == 0.0f ? visibility_rect.Max.y : +FLT_MAX);\r\n            ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(def.InnerDir * grip_hover_outer_size, def.InnerDir * -grip_hover_inner_size, def.CornerPosN); // Corner of the window corresponding to our corner grip\r\n            corner_target = ImClamp(corner_target, clamp_min, clamp_max);\r\n            CalcResizePosSizeFromAnyCorner(window, corner_target, def.CornerPosN, &pos_target, &size_target);\r\n        }\r\n\r\n        // Only lower-left grip is visible before hovering/activating\r\n        if (resize_grip_n == 0 || held || hovered)\r\n            resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);\r\n    }\r\n    for (int border_n = 0; border_n < resize_border_count; border_n++)\r\n    {\r\n        const ImGuiResizeBorderDef& def = resize_border_def[border_n];\r\n        const ImGuiAxis axis = (border_n == ImGuiDir_Left || border_n == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;\r\n\r\n        bool hovered, held;\r\n        ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_HOVER_PADDING);\r\n        ImGuiID border_id = window->GetID(border_n + 4); // == GetWindowResizeBorderID()\r\n        ButtonBehavior(border_rect, border_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);\r\n        //GetForegroundDrawLists(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));\r\n        if ((hovered && g.HoveredIdTimer > WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER) || held)\r\n        {\r\n            g.MouseCursor = (axis == ImGuiAxis_X) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;\r\n            if (held)\r\n                *border_held = border_n;\r\n        }\r\n        if (held)\r\n        {\r\n            ImVec2 clamp_min(border_n == ImGuiDir_Right ? visibility_rect.Min.x : -FLT_MAX, border_n == ImGuiDir_Down ? visibility_rect.Min.y : -FLT_MAX);\r\n            ImVec2 clamp_max(border_n == ImGuiDir_Left  ? visibility_rect.Max.x : +FLT_MAX, border_n == ImGuiDir_Up   ? visibility_rect.Max.y : +FLT_MAX);\r\n            ImVec2 border_target = window->Pos;\r\n            border_target[axis] = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + WINDOWS_HOVER_PADDING;\r\n            border_target = ImClamp(border_target, clamp_min, clamp_max);\r\n            CalcResizePosSizeFromAnyCorner(window, border_target, ImMin(def.SegmentN1, def.SegmentN2), &pos_target, &size_target);\r\n        }\r\n    }\r\n    PopID();\r\n\r\n    // Restore nav layer\r\n    window->DC.NavLayerCurrent = ImGuiNavLayer_Main;\r\n\r\n    // Navigation resize (keyboard/gamepad)\r\n    if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindow == window)\r\n    {\r\n        ImVec2 nav_resize_delta;\r\n        if (g.NavInputSource == ImGuiInputSource_Keyboard && g.IO.KeyShift)\r\n            nav_resize_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_RawKeyboard, ImGuiInputReadMode_Down);\r\n        if (g.NavInputSource == ImGuiInputSource_Gamepad)\r\n            nav_resize_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_Down);\r\n        if (nav_resize_delta.x != 0.0f || nav_resize_delta.y != 0.0f)\r\n        {\r\n            const float NAV_RESIZE_SPEED = 600.0f;\r\n            nav_resize_delta *= ImFloor(NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y));\r\n            nav_resize_delta = ImMax(nav_resize_delta, visibility_rect.Min - window->Pos - window->Size);\r\n            g.NavWindowingToggleLayer = false;\r\n            g.NavDisableMouseHover = true;\r\n            resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);\r\n            // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.\r\n            size_target = CalcWindowSizeAfterConstraint(window, window->SizeFull + nav_resize_delta);\r\n        }\r\n    }\r\n\r\n    // Apply back modified position/size to window\r\n    if (size_target.x != FLT_MAX)\r\n    {\r\n        window->SizeFull = size_target;\r\n        MarkIniSettingsDirty(window);\r\n    }\r\n    if (pos_target.x != FLT_MAX)\r\n    {\r\n        window->Pos = ImFloor(pos_target);\r\n        MarkIniSettingsDirty(window);\r\n    }\r\n\r\n    window->Size = window->SizeFull;\r\n    return ret_auto_fit;\r\n}\r\n\r\nstatic inline void ClampWindowRect(ImGuiWindow* window, const ImRect& visibility_rect)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImVec2 size_for_clamping = window->Size;\r\n    if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar))\r\n        size_for_clamping.y = window->TitleBarHeight();\r\n    window->Pos = ImClamp(window->Pos, visibility_rect.Min - size_for_clamping, visibility_rect.Max);\r\n}\r\n\r\nstatic void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    float rounding = window->WindowRounding;\r\n    float border_size = window->WindowBorderSize;\r\n    if (border_size > 0.0f && !(window->Flags & ImGuiWindowFlags_NoBackground))\r\n        window->DrawList->AddRect(window->Pos, window->Pos + window->Size, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);\r\n\r\n    int border_held = window->ResizeBorderHeld;\r\n    if (border_held != -1)\r\n    {\r\n        const ImGuiResizeBorderDef& def = resize_border_def[border_held];\r\n        ImRect border_r = GetResizeBorderRect(window, border_held, rounding, 0.0f);\r\n        window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI * 0.25f, def.OuterAngle);\r\n        window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI * 0.25f);\r\n        window->DrawList->PathStroke(GetColorU32(ImGuiCol_SeparatorActive), 0, ImMax(2.0f, border_size)); // Thicker than usual\r\n    }\r\n    if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar))\r\n    {\r\n        float y = window->Pos.y + window->TitleBarHeight() - 1;\r\n        window->DrawList->AddLine(ImVec2(window->Pos.x + border_size, y), ImVec2(window->Pos.x + window->Size.x - border_size, y), GetColorU32(ImGuiCol_Border), g.Style.FrameBorderSize);\r\n    }\r\n}\r\n\r\n// Draw background and borders\r\n// Draw and handle scrollbars\r\nvoid ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiStyle& style = g.Style;\r\n    ImGuiWindowFlags flags = window->Flags;\r\n\r\n    // Ensure that ScrollBar doesn't read last frame's SkipItems\r\n    IM_ASSERT(window->BeginCount == 0);\r\n    window->SkipItems = false;\r\n\r\n    // Draw window + handle manual resize\r\n    // As we highlight the title bar when want_focus is set, multiple reappearing windows will have have their title bar highlighted on their reappearing frame.\r\n    const float window_rounding = window->WindowRounding;\r\n    const float window_border_size = window->WindowBorderSize;\r\n    if (window->Collapsed)\r\n    {\r\n        // Title bar only\r\n        float backup_border_size = style.FrameBorderSize;\r\n        g.Style.FrameBorderSize = window->WindowBorderSize;\r\n        ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);\r\n        RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);\r\n        g.Style.FrameBorderSize = backup_border_size;\r\n    }\r\n    else\r\n    {\r\n        // Window background\r\n        if (!(flags & ImGuiWindowFlags_NoBackground))\r\n        {\r\n            ImU32 bg_col = GetColorU32(GetWindowBgColorIdx(window));\r\n            bool override_alpha = false;\r\n            float alpha = 1.0f;\r\n            if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha)\r\n            {\r\n                alpha = g.NextWindowData.BgAlphaVal;\r\n                override_alpha = true;\r\n            }\r\n            if (override_alpha)\r\n                bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);\r\n            window->DrawList->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight()), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? 0 : ImDrawFlags_RoundCornersBottom);\r\n        }\r\n\r\n        // Title bar\r\n        if (!(flags & ImGuiWindowFlags_NoTitleBar))\r\n        {\r\n            ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);\r\n            window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawFlags_RoundCornersTop);\r\n        }\r\n\r\n        // Menu bar\r\n        if (flags & ImGuiWindowFlags_MenuBar)\r\n        {\r\n            ImRect menu_bar_rect = window->MenuBarRect();\r\n            menu_bar_rect.ClipWith(window->Rect());  // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them.\r\n            window->DrawList->AddRectFilled(menu_bar_rect.Min + ImVec2(window_border_size, 0), menu_bar_rect.Max - ImVec2(window_border_size, 0), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawFlags_RoundCornersTop);\r\n            if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)\r\n                window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);\r\n        }\r\n\r\n        // Scrollbars\r\n        if (window->ScrollbarX)\r\n            Scrollbar(ImGuiAxis_X);\r\n        if (window->ScrollbarY)\r\n            Scrollbar(ImGuiAxis_Y);\r\n\r\n        // Render resize grips (after their input handling so we don't have a frame of latency)\r\n        if (!(flags & ImGuiWindowFlags_NoResize))\r\n        {\r\n            for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)\r\n            {\r\n                const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];\r\n                const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);\r\n                window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, window_border_size)));\r\n                window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, window_border_size) : ImVec2(window_border_size, resize_grip_draw_size)));\r\n                window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + window_border_size), corner.y + grip.InnerDir.y * (window_rounding + window_border_size)), window_rounding, grip.AngleMin12, grip.AngleMax12);\r\n                window->DrawList->PathFillConvex(resize_grip_col[resize_grip_n]);\r\n            }\r\n        }\r\n\r\n        // Borders\r\n        RenderWindowOuterBorders(window);\r\n    }\r\n}\r\n\r\n// Render title text, collapse button, close button\r\nvoid ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiStyle& style = g.Style;\r\n    ImGuiWindowFlags flags = window->Flags;\r\n\r\n    const bool has_close_button = (p_open != NULL);\r\n    const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse) && (style.WindowMenuButtonPosition != ImGuiDir_None);\r\n\r\n    // Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer)\r\n    // FIXME-NAV: Might want (or not?) to set the equivalent of ImGuiButtonFlags_NoNavFocus so that mouse clicks on standard title bar items don't necessarily set nav/keyboard ref?\r\n    const ImGuiItemFlags item_flags_backup = g.CurrentItemFlags;\r\n    g.CurrentItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;\r\n    window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;\r\n\r\n    // Layout buttons\r\n    // FIXME: Would be nice to generalize the subtleties expressed here into reusable code.\r\n    float pad_l = style.FramePadding.x;\r\n    float pad_r = style.FramePadding.x;\r\n    float button_sz = g.FontSize;\r\n    ImVec2 close_button_pos;\r\n    ImVec2 collapse_button_pos;\r\n    if (has_close_button)\r\n    {\r\n        pad_r += button_sz;\r\n        close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y);\r\n    }\r\n    if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right)\r\n    {\r\n        pad_r += button_sz;\r\n        collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y);\r\n    }\r\n    if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left)\r\n    {\r\n        collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l - style.FramePadding.x, title_bar_rect.Min.y);\r\n        pad_l += button_sz;\r\n    }\r\n\r\n    // Collapse button (submitting first so it gets priority when choosing a navigation init fallback)\r\n    if (has_collapse_button)\r\n        if (CollapseButton(window->GetID(\"#COLLAPSE\"), collapse_button_pos))\r\n            window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function\r\n\r\n    // Close button\r\n    if (has_close_button)\r\n        if (CloseButton(window->GetID(\"#CLOSE\"), close_button_pos))\r\n            *p_open = false;\r\n\r\n    window->DC.NavLayerCurrent = ImGuiNavLayer_Main;\r\n    g.CurrentItemFlags = item_flags_backup;\r\n\r\n    // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional \"unsaved document\" marker)\r\n    // FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code..\r\n    const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? button_sz * 0.80f : 0.0f;\r\n    const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f);\r\n\r\n    // As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button,\r\n    // while uncentered title text will still reach edges correctly.\r\n    if (pad_l > style.FramePadding.x)\r\n        pad_l += g.Style.ItemInnerSpacing.x;\r\n    if (pad_r > style.FramePadding.x)\r\n        pad_r += g.Style.ItemInnerSpacing.x;\r\n    if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f)\r\n    {\r\n        float centerness = ImSaturate(1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center\r\n        float pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x);\r\n        pad_l = ImMax(pad_l, pad_extend * centerness);\r\n        pad_r = ImMax(pad_r, pad_extend * centerness);\r\n    }\r\n\r\n    ImRect layout_r(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y);\r\n    ImRect clip_r(layout_r.Min.x, layout_r.Min.y, ImMin(layout_r.Max.x + g.Style.ItemInnerSpacing.x, title_bar_rect.Max.x), layout_r.Max.y);\r\n    if (flags & ImGuiWindowFlags_UnsavedDocument)\r\n    {\r\n        ImVec2 marker_pos;\r\n        marker_pos.x = ImClamp(layout_r.Min.x + (layout_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x + text_size.x, layout_r.Min.x, layout_r.Max.x);\r\n        marker_pos.y = (layout_r.Min.y + layout_r.Max.y) * 0.5f;\r\n        if (marker_pos.x > layout_r.Min.x)\r\n        {\r\n            RenderBullet(window->DrawList, marker_pos, GetColorU32(ImGuiCol_Text));\r\n            clip_r.Max.x = ImMin(clip_r.Max.x, marker_pos.x - (int)(marker_size_x * 0.5f));\r\n        }\r\n    }\r\n    //if (g.IO.KeyShift) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]\r\n    //if (g.IO.KeyCtrl) window->DrawList->AddRect(clip_r.Min, clip_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]\r\n    RenderTextClipped(layout_r.Min, layout_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_r);\r\n}\r\n\r\nvoid ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)\r\n{\r\n    window->ParentWindow = parent_window;\r\n    window->RootWindow = window->RootWindowPopupTree = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;\r\n    if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))\r\n        window->RootWindow = parent_window->RootWindow;\r\n    if (parent_window && (flags & ImGuiWindowFlags_Popup))\r\n        window->RootWindowPopupTree = parent_window->RootWindowPopupTree;\r\n    if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)))\r\n        window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;\r\n    while (window->RootWindowForNav->Flags & ImGuiWindowFlags_NavFlattened)\r\n    {\r\n        IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL);\r\n        window->RootWindowForNav = window->RootWindowForNav->ParentWindow;\r\n    }\r\n}\r\n\r\n// When a modal popup is open, newly created windows that want focus (i.e. are not popups and do not specify ImGuiWindowFlags_NoFocusOnAppearing)\r\n// should be positioned behind that modal window, unless the window was created inside the modal begin-stack.\r\n// In case of multiple stacked modals newly created window honors begin stack order and does not go below its own modal parent.\r\n// - Window             // FindBlockingModal() returns Modal1\r\n//   - Window           //                  .. returns Modal1\r\n//   - Modal1           //                  .. returns Modal2\r\n//      - Window        //                  .. returns Modal2\r\n//          - Window    //                  .. returns Modal2\r\n//          - Modal2    //                  .. returns Modal2\r\nstatic ImGuiWindow* ImGui::FindBlockingModal(ImGuiWindow* window)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    if (g.OpenPopupStack.Size <= 0)\r\n        return NULL;\r\n\r\n    // Find a modal that has common parent with specified window. Specified window should be positioned behind that modal.\r\n    for (int i = g.OpenPopupStack.Size - 1; i >= 0; i--)\r\n    {\r\n        ImGuiWindow* popup_window = g.OpenPopupStack.Data[i].Window;\r\n        if (popup_window == NULL || !(popup_window->Flags & ImGuiWindowFlags_Modal))\r\n            continue;\r\n        if (!popup_window->Active && !popup_window->WasActive)      // Check WasActive, because this code may run before popup renders on current frame, also check Active to handle newly created windows.\r\n            continue;\r\n        if (IsWindowWithinBeginStackOf(window, popup_window))       // Window is rendered over last modal, no render order change needed.\r\n            break;\r\n        for (ImGuiWindow* parent = popup_window->ParentWindowInBeginStack->RootWindow; parent != NULL; parent = parent->ParentWindowInBeginStack->RootWindow)\r\n            if (IsWindowWithinBeginStackOf(window, parent))\r\n                return popup_window;                                // Place window above its begin stack parent.\r\n    }\r\n    return NULL;\r\n}\r\n\r\n// Push a new Dear ImGui window to add widgets to.\r\n// - A default window called \"Debug\" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair.\r\n// - Begin/End can be called multiple times during the frame with the same window name to append content.\r\n// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).\r\n//   You can use the \"##\" or \"###\" markers to use the same label with different id, or same id with different label. See documentation at the top of this file.\r\n// - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned.\r\n// - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed.\r\nbool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    const ImGuiStyle& style = g.Style;\r\n    IM_ASSERT(name != NULL && name[0] != '\\0');     // Window name required\r\n    IM_ASSERT(g.WithinFrameScope);                  // Forgot to call ImGui::NewFrame()\r\n    IM_ASSERT(g.FrameCountEnded != g.FrameCount);   // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet\r\n\r\n    // Find or create\r\n    ImGuiWindow* window = FindWindowByName(name);\r\n    const bool window_just_created = (window == NULL);\r\n    if (window_just_created)\r\n        window = CreateNewWindow(name, flags);\r\n    else\r\n        UpdateWindowInFocusOrderList(window, window_just_created, flags);\r\n\r\n    // Automatically disable manual moving/resizing when NoInputs is set\r\n    if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs)\r\n        flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;\r\n\r\n    if (flags & ImGuiWindowFlags_NavFlattened)\r\n        IM_ASSERT(flags & ImGuiWindowFlags_ChildWindow);\r\n\r\n    const int current_frame = g.FrameCount;\r\n    const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);\r\n    window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow);\r\n\r\n    // Update the Appearing flag\r\n    bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1);   // Not using !WasActive because the implicit \"Debug\" window would always toggle off->on\r\n    if (flags & ImGuiWindowFlags_Popup)\r\n    {\r\n        ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];\r\n        window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed\r\n        window_just_activated_by_user |= (window != popup_ref.Window);\r\n    }\r\n    window->Appearing = window_just_activated_by_user;\r\n    if (window->Appearing)\r\n        SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);\r\n\r\n    // Update Flags, LastFrameActive, BeginOrderXXX fields\r\n    if (first_begin_of_the_frame)\r\n    {\r\n        window->Flags = (ImGuiWindowFlags)flags;\r\n        window->LastFrameActive = current_frame;\r\n        window->LastTimeActive = (float)g.Time;\r\n        window->BeginOrderWithinParent = 0;\r\n        window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);\r\n    }\r\n    else\r\n    {\r\n        flags = window->Flags;\r\n    }\r\n\r\n    // Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack\r\n    ImGuiWindow* parent_window_in_stack = g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back().Window;\r\n    ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;\r\n    IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));\r\n\r\n    // We allow window memory to be compacted so recreate the base stack when needed.\r\n    if (window->IDStack.Size == 0)\r\n        window->IDStack.push_back(window->ID);\r\n\r\n    // Add to stack\r\n    // We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()\r\n    g.CurrentWindow = window;\r\n    ImGuiWindowStackData window_stack_data;\r\n    window_stack_data.Window = window;\r\n    window_stack_data.ParentLastItemDataBackup = g.LastItemData;\r\n    window_stack_data.StackSizesOnBegin.SetToCurrentState();\r\n    g.CurrentWindowStack.push_back(window_stack_data);\r\n    g.CurrentWindow = NULL;\r\n    if (flags & ImGuiWindowFlags_ChildMenu)\r\n        g.BeginMenuCount++;\r\n\r\n    if (flags & ImGuiWindowFlags_Popup)\r\n    {\r\n        ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];\r\n        popup_ref.Window = window;\r\n        g.BeginPopupStack.push_back(popup_ref);\r\n        window->PopupId = popup_ref.PopupId;\r\n    }\r\n\r\n    // Update ->RootWindow and others pointers (before any possible call to FocusWindow)\r\n    if (first_begin_of_the_frame)\r\n    {\r\n        UpdateWindowParentAndRootLinks(window, flags, parent_window);\r\n        window->ParentWindowInBeginStack = parent_window_in_stack;\r\n    }\r\n\r\n    // Process SetNextWindow***() calls\r\n    // (FIXME: Consider splitting the HasXXX flags into X/Y components\r\n    bool window_pos_set_by_api = false;\r\n    bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;\r\n    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos)\r\n    {\r\n        window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;\r\n        if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)\r\n        {\r\n            // May be processed on the next frame if this is our first frame and we are measuring size\r\n            // FIXME: Look into removing the branch so everything can go through this same code path for consistency.\r\n            window->SetWindowPosVal = g.NextWindowData.PosVal;\r\n            window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;\r\n            window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);\r\n        }\r\n        else\r\n        {\r\n            SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);\r\n        }\r\n    }\r\n    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize)\r\n    {\r\n        window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);\r\n        window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);\r\n        SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);\r\n    }\r\n    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasScroll)\r\n    {\r\n        if (g.NextWindowData.ScrollVal.x >= 0.0f)\r\n        {\r\n            window->ScrollTarget.x = g.NextWindowData.ScrollVal.x;\r\n            window->ScrollTargetCenterRatio.x = 0.0f;\r\n        }\r\n        if (g.NextWindowData.ScrollVal.y >= 0.0f)\r\n        {\r\n            window->ScrollTarget.y = g.NextWindowData.ScrollVal.y;\r\n            window->ScrollTargetCenterRatio.y = 0.0f;\r\n        }\r\n    }\r\n    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasContentSize)\r\n        window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal;\r\n    else if (first_begin_of_the_frame)\r\n        window->ContentSizeExplicit = ImVec2(0.0f, 0.0f);\r\n    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed)\r\n        SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);\r\n    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus)\r\n        FocusWindow(window);\r\n    if (window->Appearing)\r\n        SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);\r\n\r\n    // When reusing window again multiple times a frame, just append content (don't need to setup again)\r\n    if (first_begin_of_the_frame)\r\n    {\r\n        // Initialize\r\n        const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)\r\n        const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0);\r\n        window->Active = true;\r\n        window->HasCloseButton = (p_open != NULL);\r\n        window->ClipRect = ImVec4(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX);\r\n        window->IDStack.resize(1);\r\n        window->DrawList->_ResetForNewFrame();\r\n        window->DC.CurrentTableIdx = -1;\r\n\r\n        // Restore buffer capacity when woken from a compacted state, to avoid\r\n        if (window->MemoryCompacted)\r\n            GcAwakeTransientWindowBuffers(window);\r\n\r\n        // Update stored window name when it changes (which can _only_ happen with the \"###\" operator, so the ID would stay unchanged).\r\n        // The title bar always display the 'name' parameter, so we only update the string storage if it needs to be visible to the end-user elsewhere.\r\n        bool window_title_visible_elsewhere = false;\r\n        if (g.NavWindowingListWindow != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0)   // Window titles visible when using CTRL+TAB\r\n            window_title_visible_elsewhere = true;\r\n        if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0)\r\n        {\r\n            size_t buf_len = (size_t)window->NameBufLen;\r\n            window->Name = ImStrdupcpy(window->Name, &buf_len, name);\r\n            window->NameBufLen = (int)buf_len;\r\n        }\r\n\r\n        // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS\r\n\r\n        // Update contents size from last frame for auto-fitting (or use explicit size)\r\n        CalcWindowContentSizes(window, &window->ContentSize, &window->ContentSizeIdeal);\r\n        if (window->HiddenFramesCanSkipItems > 0)\r\n            window->HiddenFramesCanSkipItems--;\r\n        if (window->HiddenFramesCannotSkipItems > 0)\r\n            window->HiddenFramesCannotSkipItems--;\r\n        if (window->HiddenFramesForRenderOnly > 0)\r\n            window->HiddenFramesForRenderOnly--;\r\n\r\n        // Hide new windows for one frame until they calculate their size\r\n        if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))\r\n            window->HiddenFramesCannotSkipItems = 1;\r\n\r\n        // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)\r\n        // We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.\r\n        if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)\r\n        {\r\n            window->HiddenFramesCannotSkipItems = 1;\r\n            if (flags & ImGuiWindowFlags_AlwaysAutoResize)\r\n            {\r\n                if (!window_size_x_set_by_api)\r\n                    window->Size.x = window->SizeFull.x = 0.f;\r\n                if (!window_size_y_set_by_api)\r\n                    window->Size.y = window->SizeFull.y = 0.f;\r\n                window->ContentSize = window->ContentSizeIdeal = ImVec2(0.f, 0.f);\r\n            }\r\n        }\r\n\r\n        // SELECT VIEWPORT\r\n        // FIXME-VIEWPORT: In the docking/viewport branch, this is the point where we select the current viewport (which may affect the style)\r\n        SetCurrentWindow(window);\r\n\r\n        // LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies)\r\n\r\n        if (flags & ImGuiWindowFlags_ChildWindow)\r\n            window->WindowBorderSize = style.ChildBorderSize;\r\n        else\r\n            window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;\r\n        window->WindowPadding = style.WindowPadding;\r\n        if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_Popup)) && window->WindowBorderSize == 0.0f)\r\n            window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);\r\n\r\n        // Lock menu offset so size calculation can use it as menu-bar windows need a minimum size.\r\n        window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x);\r\n        window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;\r\n\r\n        // Collapse window by double-clicking on title bar\r\n        // At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing\r\n        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse))\r\n        {\r\n            // We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed), so verify that we don't have items over the title bar.\r\n            ImRect title_bar_rect = window->TitleBarRect();\r\n            if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseClickedCount[0] == 2)\r\n                window->WantCollapseToggle = true;\r\n            if (window->WantCollapseToggle)\r\n            {\r\n                window->Collapsed = !window->Collapsed;\r\n                MarkIniSettingsDirty(window);\r\n            }\r\n        }\r\n        else\r\n        {\r\n            window->Collapsed = false;\r\n        }\r\n        window->WantCollapseToggle = false;\r\n\r\n        // SIZE\r\n\r\n        // Calculate auto-fit size, handle automatic resize\r\n        const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal);\r\n        bool use_current_size_for_scrollbar_x = window_just_created;\r\n        bool use_current_size_for_scrollbar_y = window_just_created;\r\n        if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed)\r\n        {\r\n            // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.\r\n            if (!window_size_x_set_by_api)\r\n            {\r\n                window->SizeFull.x = size_auto_fit.x;\r\n                use_current_size_for_scrollbar_x = true;\r\n            }\r\n            if (!window_size_y_set_by_api)\r\n            {\r\n                window->SizeFull.y = size_auto_fit.y;\r\n                use_current_size_for_scrollbar_y = true;\r\n            }\r\n        }\r\n        else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)\r\n        {\r\n            // Auto-fit may only grow window during the first few frames\r\n            // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.\r\n            if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)\r\n            {\r\n                window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;\r\n                use_current_size_for_scrollbar_x = true;\r\n            }\r\n            if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)\r\n            {\r\n                window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;\r\n                use_current_size_for_scrollbar_y = true;\r\n            }\r\n            if (!window->Collapsed)\r\n                MarkIniSettingsDirty(window);\r\n        }\r\n\r\n        // Apply minimum/maximum window size constraints and final size\r\n        window->SizeFull = CalcWindowSizeAfterConstraint(window, window->SizeFull);\r\n        window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;\r\n\r\n        // Decoration size\r\n        const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight();\r\n\r\n        // POSITION\r\n\r\n        // Popup latch its initial position, will position itself when it appears next frame\r\n        if (window_just_activated_by_user)\r\n        {\r\n            window->AutoPosLastDirection = ImGuiDir_None;\r\n            if ((flags & ImGuiWindowFlags_Popup) != 0 && !(flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api) // FIXME: BeginPopup() could use SetNextWindowPos()\r\n                window->Pos = g.BeginPopupStack.back().OpenPopupPos;\r\n        }\r\n\r\n        // Position child window\r\n        if (flags & ImGuiWindowFlags_ChildWindow)\r\n        {\r\n            IM_ASSERT(parent_window && parent_window->Active);\r\n            window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size;\r\n            parent_window->DC.ChildWindows.push_back(window);\r\n            if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)\r\n                window->Pos = parent_window->DC.CursorPos;\r\n        }\r\n\r\n        const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0);\r\n        if (window_pos_with_pivot)\r\n            SetWindowPos(window, window->SetWindowPosVal - window->Size * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering)\r\n        else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)\r\n            window->Pos = FindBestWindowPosForPopup(window);\r\n        else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)\r\n            window->Pos = FindBestWindowPosForPopup(window);\r\n        else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)\r\n            window->Pos = FindBestWindowPosForPopup(window);\r\n\r\n        // Calculate the range of allowed position for that window (to be movable and visible past safe area padding)\r\n        // When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect.\r\n        ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)GetMainViewport();\r\n        ImRect viewport_rect(viewport->GetMainRect());\r\n        ImRect viewport_work_rect(viewport->GetWorkRect());\r\n        ImVec2 visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);\r\n        ImRect visibility_rect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding);\r\n\r\n        // Clamp position/size so window stays visible within its viewport or monitor\r\n        // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.\r\n        if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)\r\n            if (viewport_rect.GetWidth() > 0.0f && viewport_rect.GetHeight() > 0.0f)\r\n                ClampWindowRect(window, visibility_rect);\r\n        window->Pos = ImFloor(window->Pos);\r\n\r\n        // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)\r\n        // Large values tend to lead to variety of artifacts and are not recommended.\r\n        window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;\r\n\r\n        // For windows with title bar or menu bar, we clamp to FrameHeight(FontSize + FramePadding.y * 2.0f) to completely hide artifacts.\r\n        //if ((window->Flags & ImGuiWindowFlags_MenuBar) || !(window->Flags & ImGuiWindowFlags_NoTitleBar))\r\n        //    window->WindowRounding = ImMin(window->WindowRounding, g.FontSize + style.FramePadding.y * 2.0f);\r\n\r\n        // Apply window focus (new and reactivated windows are moved to front)\r\n        bool want_focus = false;\r\n        if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))\r\n        {\r\n            if (flags & ImGuiWindowFlags_Popup)\r\n                want_focus = true;\r\n            else if ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Tooltip)) == 0)\r\n                want_focus = true;\r\n\r\n            ImGuiWindow* modal = GetTopMostPopupModal();\r\n            if (modal != NULL && !IsWindowWithinBeginStackOf(window, modal))\r\n            {\r\n                // Avoid focusing a window that is created outside of active modal. This will prevent active modal from being closed.\r\n                // Since window is not focused it would reappear at the same display position like the last time it was visible.\r\n                // In case of completely new windows it would go to the top (over current modal), but input to such window would still be blocked by modal.\r\n                // Position window behind a modal that is not a begin-parent of this window.\r\n                want_focus = false;\r\n                if (window == window->RootWindow)\r\n                {\r\n                    ImGuiWindow* blocking_modal = FindBlockingModal(window);\r\n                    IM_ASSERT(blocking_modal != NULL);\r\n                    BringWindowToDisplayBehind(window, blocking_modal);\r\n                }\r\n            }\r\n        }\r\n\r\n        // [Test Engine] Register whole window in the item system\r\n#ifdef IMGUI_ENABLE_TEST_ENGINE\r\n        if (g.TestEngineHookItems)\r\n        {\r\n            IM_ASSERT(window->IDStack.Size == 1);\r\n            window->IDStack.Size = 0;\r\n            IMGUI_TEST_ENGINE_ITEM_ADD(window->Rect(), window->ID);\r\n            IMGUI_TEST_ENGINE_ITEM_INFO(window->ID, window->Name, (g.HoveredWindow == window) ? ImGuiItemStatusFlags_HoveredRect : 0);\r\n            window->IDStack.Size = 1;\r\n        }\r\n#endif\r\n\r\n        // Handle manual resize: Resize Grips, Borders, Gamepad\r\n        int border_held = -1;\r\n        ImU32 resize_grip_col[4] = {};\r\n        const int resize_grip_count = g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it.\r\n        const float resize_grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.10f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));\r\n        if (!window->Collapsed)\r\n            if (UpdateWindowManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect))\r\n                use_current_size_for_scrollbar_x = use_current_size_for_scrollbar_y = true;\r\n        window->ResizeBorderHeld = (signed char)border_held;\r\n\r\n        // SCROLLBAR VISIBILITY\r\n\r\n        // Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size).\r\n        if (!window->Collapsed)\r\n        {\r\n            // When reading the current size we need to read it after size constraints have been applied.\r\n            // When we use InnerRect here we are intentionally reading last frame size, same for ScrollbarSizes values before we set them again.\r\n            ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - decoration_up_height);\r\n            ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + window->ScrollbarSizes;\r\n            ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f;\r\n            float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x;\r\n            float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y;\r\n            //bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons?\r\n            window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));\r\n            window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((needed_size_from_last_frame.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));\r\n            if (window->ScrollbarX && !window->ScrollbarY)\r\n                window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar);\r\n            window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);\r\n        }\r\n\r\n        // UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING)\r\n        // Update various regions. Variables they depends on should be set above in this function.\r\n        // We set this up after processing the resize grip so that our rectangles doesn't lag by a frame.\r\n\r\n        // Outer rectangle\r\n        // Not affected by window border size. Used by:\r\n        // - FindHoveredWindow() (w/ extra padding when border resize is enabled)\r\n        // - Begin() initial clipping rect for drawing window background and borders.\r\n        // - Begin() clipping whole child\r\n        const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect;\r\n        const ImRect outer_rect = window->Rect();\r\n        const ImRect title_bar_rect = window->TitleBarRect();\r\n        window->OuterRectClipped = outer_rect;\r\n        window->OuterRectClipped.ClipWith(host_rect);\r\n\r\n        // Inner rectangle\r\n        // Not affected by window border size. Used by:\r\n        // - InnerClipRect\r\n        // - ScrollToRectEx()\r\n        // - NavUpdatePageUpPageDown()\r\n        // - Scrollbar()\r\n        window->InnerRect.Min.x = window->Pos.x;\r\n        window->InnerRect.Min.y = window->Pos.y + decoration_up_height;\r\n        window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->ScrollbarSizes.x;\r\n        window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->ScrollbarSizes.y;\r\n\r\n        // Inner clipping rectangle.\r\n        // Will extend a little bit outside the normal work region.\r\n        // This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space.\r\n        // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.\r\n        // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.\r\n        // Affected by window/frame border size. Used by:\r\n        // - Begin() initial clip rect\r\n        float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);\r\n        window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize));\r\n        window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y + top_border_size);\r\n        window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize));\r\n        window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y - window->WindowBorderSize);\r\n        window->InnerClipRect.ClipWithFull(host_rect);\r\n\r\n        // Default item width. Make it proportional to window size if window manually resizes\r\n        if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))\r\n            window->ItemWidthDefault = ImFloor(window->Size.x * 0.65f);\r\n        else\r\n            window->ItemWidthDefault = ImFloor(g.FontSize * 16.0f);\r\n\r\n        // SCROLLING\r\n\r\n        // Lock down maximum scrolling\r\n        // The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate\r\n        // for right/bottom aligned items without creating a scrollbar.\r\n        window->ScrollMax.x = ImMax(0.0f, window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth());\r\n        window->ScrollMax.y = ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight());\r\n\r\n        // Apply scrolling\r\n        window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window);\r\n        window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);\r\n\r\n        // DRAWING\r\n\r\n        // Setup draw list and outer clipping rectangle\r\n        IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0);\r\n        window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);\r\n        PushClipRect(host_rect.Min, host_rect.Max, false);\r\n\r\n        // Child windows can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call (since 1.71)\r\n        // When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order.\r\n        // FIXME: User code may rely on explicit sorting of overlapping child window and would need to disable this somehow. Please get in contact if you are affected (github #4493)\r\n        {\r\n            bool render_decorations_in_parent = false;\r\n            if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)\r\n            {\r\n                // - We test overlap with the previous child window only (testing all would end up being O(log N) not a good investment here)\r\n                // - We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping childs\r\n                ImGuiWindow* previous_child = parent_window->DC.ChildWindows.Size >= 2 ? parent_window->DC.ChildWindows[parent_window->DC.ChildWindows.Size - 2] : NULL;\r\n                bool previous_child_overlapping = previous_child ? previous_child->Rect().Overlaps(window->Rect()) : false;\r\n                bool parent_is_empty = parent_window->DrawList->VtxBuffer.Size > 0;\r\n                if (window->DrawList->CmdBuffer.back().ElemCount == 0 && parent_is_empty && !previous_child_overlapping)\r\n                    render_decorations_in_parent = true;\r\n            }\r\n            if (render_decorations_in_parent)\r\n                window->DrawList = parent_window->DrawList;\r\n\r\n            // Handle title bar, scrollbar, resize grips and resize borders\r\n            const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;\r\n            const bool title_bar_is_highlight = want_focus || (window_to_highlight && window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight);\r\n            RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, resize_grip_count, resize_grip_col, resize_grip_draw_size);\r\n\r\n            if (render_decorations_in_parent)\r\n                window->DrawList = &window->DrawListInst;\r\n        }\r\n\r\n        // UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING)\r\n\r\n        // Work rectangle.\r\n        // Affected by window padding and border size. Used by:\r\n        // - Columns() for right-most edge\r\n        // - TreeNode(), CollapsingHeader() for right-most edge\r\n        // - BeginTabBar() for right-most edge\r\n        const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar);\r\n        const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar);\r\n        const float work_rect_size_x = (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : ImMax(allow_scrollbar_x ? window->ContentSize.x : 0.0f, window->Size.x - window->WindowPadding.x * 2.0f - window->ScrollbarSizes.x));\r\n        const float work_rect_size_y = (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : ImMax(allow_scrollbar_y ? window->ContentSize.y : 0.0f, window->Size.y - window->WindowPadding.y * 2.0f - decoration_up_height - window->ScrollbarSizes.y));\r\n        window->WorkRect.Min.x = ImFloor(window->InnerRect.Min.x - window->Scroll.x + ImMax(window->WindowPadding.x, window->WindowBorderSize));\r\n        window->WorkRect.Min.y = ImFloor(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize));\r\n        window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x;\r\n        window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y;\r\n        window->ParentWorkRect = window->WorkRect;\r\n\r\n        // [LEGACY] Content Region\r\n        // FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.\r\n        // Used by:\r\n        // - Mouse wheel scrolling + many other things\r\n        window->ContentRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x;\r\n        window->ContentRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + decoration_up_height;\r\n        window->ContentRegionRect.Max.x = window->ContentRegionRect.Min.x + (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : (window->Size.x - window->WindowPadding.x * 2.0f - window->ScrollbarSizes.x));\r\n        window->ContentRegionRect.Max.y = window->ContentRegionRect.Min.y + (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : (window->Size.y - window->WindowPadding.y * 2.0f - decoration_up_height - window->ScrollbarSizes.y));\r\n\r\n        // Setup drawing context\r\n        // (NB: That term \"drawing context / DC\" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.)\r\n        window->DC.Indent.x = 0.0f + window->WindowPadding.x - window->Scroll.x;\r\n        window->DC.GroupOffset.x = 0.0f;\r\n        window->DC.ColumnsOffset.x = 0.0f;\r\n\r\n        // Record the loss of precision of CursorStartPos which can happen due to really large scrolling amount.\r\n        // This is used by clipper to compensate and fix the most common use case of large scroll area. Easy and cheap, next best thing compared to switching everything to double or ImU64.\r\n        double start_pos_highp_x = (double)window->Pos.x + window->WindowPadding.x - (double)window->Scroll.x + window->DC.ColumnsOffset.x;\r\n        double start_pos_highp_y = (double)window->Pos.y + window->WindowPadding.y - (double)window->Scroll.y + decoration_up_height;\r\n        window->DC.CursorStartPos  = ImVec2((float)start_pos_highp_x, (float)start_pos_highp_y);\r\n        window->DC.CursorStartPosLossyness = ImVec2((float)(start_pos_highp_x - window->DC.CursorStartPos.x), (float)(start_pos_highp_y - window->DC.CursorStartPos.y));\r\n        window->DC.CursorPos = window->DC.CursorStartPos;\r\n        window->DC.CursorPosPrevLine = window->DC.CursorPos;\r\n        window->DC.CursorMaxPos = window->DC.CursorStartPos;\r\n        window->DC.IdealMaxPos = window->DC.CursorStartPos;\r\n        window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);\r\n        window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;\r\n\r\n        window->DC.NavLayerCurrent = ImGuiNavLayer_Main;\r\n        window->DC.NavLayersActiveMask = window->DC.NavLayersActiveMaskNext;\r\n        window->DC.NavLayersActiveMaskNext = 0x00;\r\n        window->DC.NavHideHighlightOneFrame = false;\r\n        window->DC.NavHasScroll = (window->ScrollMax.y > 0.0f);\r\n\r\n        window->DC.MenuBarAppending = false;\r\n        window->DC.MenuColumns.Update(style.ItemSpacing.x, window_just_activated_by_user);\r\n        window->DC.TreeDepth = 0;\r\n        window->DC.TreeJumpToParentOnPopMask = 0x00;\r\n        window->DC.ChildWindows.resize(0);\r\n        window->DC.StateStorage = &window->StateStorage;\r\n        window->DC.CurrentColumns = NULL;\r\n        window->DC.LayoutType = ImGuiLayoutType_Vertical;\r\n        window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;\r\n\r\n        window->DC.ItemWidth = window->ItemWidthDefault;\r\n        window->DC.TextWrapPos = -1.0f; // disabled\r\n        window->DC.ItemWidthStack.resize(0);\r\n        window->DC.TextWrapPosStack.resize(0);\r\n\r\n        if (window->AutoFitFramesX > 0)\r\n            window->AutoFitFramesX--;\r\n        if (window->AutoFitFramesY > 0)\r\n            window->AutoFitFramesY--;\r\n\r\n        // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)\r\n        if (want_focus)\r\n        {\r\n            FocusWindow(window);\r\n            NavInitWindow(window, false); // <-- this is in the way for us to be able to defer and sort reappearing FocusWindow() calls\r\n        }\r\n\r\n        // Title bar\r\n        if (!(flags & ImGuiWindowFlags_NoTitleBar))\r\n            RenderWindowTitleBarContents(window, ImRect(title_bar_rect.Min.x + window->WindowBorderSize, title_bar_rect.Min.y, title_bar_rect.Max.x - window->WindowBorderSize, title_bar_rect.Max.y), name, p_open);\r\n\r\n        // Clear hit test shape every frame\r\n        window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0;\r\n\r\n        // Pressing CTRL+C while holding on a window copy its content to the clipboard\r\n        // This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope.\r\n        // Maybe we can support CTRL+C on every element?\r\n        /*\r\n        //if (g.NavWindow == window && g.ActiveId == 0)\r\n        if (g.ActiveId == window->MoveId)\r\n            if (g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_C))\r\n                LogToClipboard();\r\n        */\r\n\r\n        // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().\r\n        // This is useful to allow creating context menus on title bar only, etc.\r\n        SetLastItemData(window->MoveId, g.CurrentItemFlags, IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0, title_bar_rect);\r\n\r\n        // [Test Engine] Register title bar / tab\r\n        if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))\r\n            IMGUI_TEST_ENGINE_ITEM_ADD(g.LastItemData.Rect, g.LastItemData.ID);\r\n    }\r\n    else\r\n    {\r\n        // Append\r\n        SetCurrentWindow(window);\r\n    }\r\n\r\n    // Pull/inherit current state\r\n    window->DC.NavFocusScopeIdCurrent = (flags & ImGuiWindowFlags_ChildWindow) ? parent_window->DC.NavFocusScopeIdCurrent : window->GetID(\"#FOCUSSCOPE\"); // Inherit from parent only // -V595\r\n\r\n    PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true);\r\n\r\n    // Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default \"Debug\" window is unused)\r\n    window->WriteAccessed = false;\r\n    window->BeginCount++;\r\n    g.NextWindowData.ClearFlags();\r\n\r\n    // Update visibility\r\n    if (first_begin_of_the_frame)\r\n    {\r\n        if (flags & ImGuiWindowFlags_ChildWindow)\r\n        {\r\n            // Child window can be out of sight and have \"negative\" clip windows.\r\n            // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).\r\n            IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0);\r\n            if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) // FIXME: Doesn't make sense for ChildWindow??\r\n            {\r\n                const bool nav_request = (flags & ImGuiWindowFlags_NavFlattened) && (g.NavAnyRequest && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);\r\n                if (!g.LogEnabled && !nav_request)\r\n                    if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)\r\n                        window->HiddenFramesCanSkipItems = 1;\r\n            }\r\n\r\n            // Hide along with parent or if parent is collapsed\r\n            if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0))\r\n                window->HiddenFramesCanSkipItems = 1;\r\n            if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0))\r\n                window->HiddenFramesCannotSkipItems = 1;\r\n        }\r\n\r\n        // Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point)\r\n        if (style.Alpha <= 0.0f)\r\n            window->HiddenFramesCanSkipItems = 1;\r\n\r\n        // Update the Hidden flag\r\n        bool hidden_regular = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0);\r\n        window->Hidden = hidden_regular || (window->HiddenFramesForRenderOnly > 0);\r\n\r\n        // Disable inputs for requested number of frames\r\n        if (window->DisableInputsFrames > 0)\r\n        {\r\n            window->DisableInputsFrames--;\r\n            window->Flags |= ImGuiWindowFlags_NoInputs;\r\n        }\r\n\r\n        // Update the SkipItems flag, used to early out of all items functions (no layout required)\r\n        bool skip_items = false;\r\n        if (window->Collapsed || !window->Active || hidden_regular)\r\n            if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0)\r\n                skip_items = true;\r\n        window->SkipItems = skip_items;\r\n    }\r\n\r\n    return !window->SkipItems;\r\n}\r\n\r\nvoid ImGui::End()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n\r\n    // Error checking: verify that user hasn't called End() too many times!\r\n    if (g.CurrentWindowStack.Size <= 1 && g.WithinFrameScopeWithImplicitWindow)\r\n    {\r\n        IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, \"Calling End() too many times!\");\r\n        return;\r\n    }\r\n    IM_ASSERT(g.CurrentWindowStack.Size > 0);\r\n\r\n    // Error checking: verify that user doesn't directly call End() on a child window.\r\n    if (window->Flags & ImGuiWindowFlags_ChildWindow)\r\n        IM_ASSERT_USER_ERROR(g.WithinEndChild, \"Must call EndChild() and not End()!\");\r\n\r\n    // Close anything that is open\r\n    if (window->DC.CurrentColumns)\r\n        EndColumns();\r\n    PopClipRect();   // Inner window clip rectangle\r\n\r\n    // Stop logging\r\n    if (!(window->Flags & ImGuiWindowFlags_ChildWindow))    // FIXME: add more options for scope of logging\r\n        LogFinish();\r\n\r\n    // Pop from window stack\r\n    g.LastItemData = g.CurrentWindowStack.back().ParentLastItemDataBackup;\r\n    if (window->Flags & ImGuiWindowFlags_ChildMenu)\r\n        g.BeginMenuCount--;\r\n    if (window->Flags & ImGuiWindowFlags_Popup)\r\n        g.BeginPopupStack.pop_back();\r\n    g.CurrentWindowStack.back().StackSizesOnBegin.CompareWithCurrentState();\r\n    g.CurrentWindowStack.pop_back();\r\n    SetCurrentWindow(g.CurrentWindowStack.Size == 0 ? NULL : g.CurrentWindowStack.back().Window);\r\n}\r\n\r\nvoid ImGui::BringWindowToFocusFront(ImGuiWindow* window)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(window == window->RootWindow);\r\n\r\n    const int cur_order = window->FocusOrder;\r\n    IM_ASSERT(g.WindowsFocusOrder[cur_order] == window);\r\n    if (g.WindowsFocusOrder.back() == window)\r\n        return;\r\n\r\n    const int new_order = g.WindowsFocusOrder.Size - 1;\r\n    for (int n = cur_order; n < new_order; n++)\r\n    {\r\n        g.WindowsFocusOrder[n] = g.WindowsFocusOrder[n + 1];\r\n        g.WindowsFocusOrder[n]->FocusOrder--;\r\n        IM_ASSERT(g.WindowsFocusOrder[n]->FocusOrder == n);\r\n    }\r\n    g.WindowsFocusOrder[new_order] = window;\r\n    window->FocusOrder = (short)new_order;\r\n}\r\n\r\nvoid ImGui::BringWindowToDisplayFront(ImGuiWindow* window)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* current_front_window = g.Windows.back();\r\n    if (current_front_window == window || current_front_window->RootWindow == window) // Cheap early out (could be better)\r\n        return;\r\n    for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window\r\n        if (g.Windows[i] == window)\r\n        {\r\n            memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));\r\n            g.Windows[g.Windows.Size - 1] = window;\r\n            break;\r\n        }\r\n}\r\n\r\nvoid ImGui::BringWindowToDisplayBack(ImGuiWindow* window)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    if (g.Windows[0] == window)\r\n        return;\r\n    for (int i = 0; i < g.Windows.Size; i++)\r\n        if (g.Windows[i] == window)\r\n        {\r\n            memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*));\r\n            g.Windows[0] = window;\r\n            break;\r\n        }\r\n}\r\n\r\nvoid ImGui::BringWindowToDisplayBehind(ImGuiWindow* window, ImGuiWindow* behind_window)\r\n{\r\n    IM_ASSERT(window != NULL && behind_window != NULL);\r\n    ImGuiContext& g = *GImGui;\r\n    window = window->RootWindow;\r\n    behind_window = behind_window->RootWindow;\r\n    int pos_wnd = FindWindowDisplayIndex(window);\r\n    int pos_beh = FindWindowDisplayIndex(behind_window);\r\n    if (pos_wnd < pos_beh)\r\n    {\r\n        size_t copy_bytes = (pos_beh - pos_wnd - 1) * sizeof(ImGuiWindow*);\r\n        memmove(&g.Windows.Data[pos_wnd], &g.Windows.Data[pos_wnd + 1], copy_bytes);\r\n        g.Windows[pos_beh - 1] = window;\r\n    }\r\n    else\r\n    {\r\n        size_t copy_bytes = (pos_wnd - pos_beh) * sizeof(ImGuiWindow*);\r\n        memmove(&g.Windows.Data[pos_beh + 1], &g.Windows.Data[pos_beh], copy_bytes);\r\n        g.Windows[pos_beh] = window;\r\n    }\r\n}\r\n\r\nint ImGui::FindWindowDisplayIndex(ImGuiWindow* window)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    return g.Windows.index_from_ptr(g.Windows.find(window));\r\n}\r\n\r\n// Moving window to front of display and set focus (which happens to be back of our sorted list)\r\nvoid ImGui::FocusWindow(ImGuiWindow* window)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n\r\n    if (g.NavWindow != window)\r\n    {\r\n        g.NavWindow = window;\r\n        if (window && g.NavDisableMouseHover)\r\n            g.NavMousePosDirty = true;\r\n        g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId\r\n        g.NavFocusScopeId = 0;\r\n        g.NavIdIsAlive = false;\r\n        g.NavLayer = ImGuiNavLayer_Main;\r\n        g.NavInitRequest = g.NavMoveSubmitted = g.NavMoveScoringItems = false;\r\n        NavUpdateAnyRequestFlag();\r\n        //IMGUI_DEBUG_LOG(\"FocusWindow(\\\"%s\\\")\\n\", window ? window->Name : NULL);\r\n    }\r\n\r\n    // Close popups if any\r\n    ClosePopupsOverWindow(window, false);\r\n\r\n    // Move the root window to the top of the pile\r\n    IM_ASSERT(window == NULL || window->RootWindow != NULL);\r\n    ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL; // NB: In docking branch this is window->RootWindowDockStop\r\n    ImGuiWindow* display_front_window = window ? window->RootWindow : NULL;\r\n\r\n    // Steal active widgets. Some of the cases it triggers includes:\r\n    // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run.\r\n    // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId)\r\n    if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window)\r\n        if (!g.ActiveIdNoClearOnFocusLoss)\r\n            ClearActiveID();\r\n\r\n    // Passing NULL allow to disable keyboard focus\r\n    if (!window)\r\n        return;\r\n\r\n    // Bring to front\r\n    BringWindowToFocusFront(focus_front_window);\r\n    if (((window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)\r\n        BringWindowToDisplayFront(display_front_window);\r\n}\r\n\r\nvoid ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    int start_idx = g.WindowsFocusOrder.Size - 1;\r\n    if (under_this_window != NULL)\r\n    {\r\n        // Aim at root window behind us, if we are in a child window that's our own root (see #4640)\r\n        int offset = -1;\r\n        while (under_this_window->Flags & ImGuiWindowFlags_ChildWindow)\r\n        {\r\n            under_this_window = under_this_window->ParentWindow;\r\n            offset = 0;\r\n        }\r\n        start_idx = FindWindowFocusIndex(under_this_window) + offset;\r\n    }\r\n    for (int i = start_idx; i >= 0; i--)\r\n    {\r\n        // We may later decide to test for different NoXXXInputs based on the active navigation input (mouse vs nav) but that may feel more confusing to the user.\r\n        ImGuiWindow* window = g.WindowsFocusOrder[i];\r\n        IM_ASSERT(window == window->RootWindow);\r\n        if (window != ignore_window && window->WasActive)\r\n            if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))\r\n            {\r\n                ImGuiWindow* focus_window = NavRestoreLastChildNavWindow(window);\r\n                FocusWindow(focus_window);\r\n                return;\r\n            }\r\n    }\r\n    FocusWindow(NULL);\r\n}\r\n\r\n// Important: this alone doesn't alter current ImDrawList state. This is called by PushFont/PopFont only.\r\nvoid ImGui::SetCurrentFont(ImFont* font)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(font && font->IsLoaded());    // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?\r\n    IM_ASSERT(font->Scale > 0.0f);\r\n    g.Font = font;\r\n    g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale);\r\n    g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;\r\n\r\n    ImFontAtlas* atlas = g.Font->ContainerAtlas;\r\n    g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel;\r\n    g.DrawListSharedData.TexUvLines = atlas->TexUvLines;\r\n    g.DrawListSharedData.Font = g.Font;\r\n    g.DrawListSharedData.FontSize = g.FontSize;\r\n}\r\n\r\nvoid ImGui::PushFont(ImFont* font)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    if (!font)\r\n        font = GetDefaultFont();\r\n    SetCurrentFont(font);\r\n    g.FontStack.push_back(font);\r\n    g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID);\r\n}\r\n\r\nvoid  ImGui::PopFont()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    g.CurrentWindow->DrawList->PopTextureID();\r\n    g.FontStack.pop_back();\r\n    SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back());\r\n}\r\n\r\nvoid ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiItemFlags item_flags = g.CurrentItemFlags;\r\n    IM_ASSERT(item_flags == g.ItemFlagsStack.back());\r\n    if (enabled)\r\n        item_flags |= option;\r\n    else\r\n        item_flags &= ~option;\r\n    g.CurrentItemFlags = item_flags;\r\n    g.ItemFlagsStack.push_back(item_flags);\r\n}\r\n\r\nvoid ImGui::PopItemFlag()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(g.ItemFlagsStack.Size > 1); // Too many calls to PopItemFlag() - we always leave a 0 at the bottom of the stack.\r\n    g.ItemFlagsStack.pop_back();\r\n    g.CurrentItemFlags = g.ItemFlagsStack.back();\r\n}\r\n\r\n// BeginDisabled()/EndDisabled()\r\n// - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled)\r\n// - Visually this is currently altering alpha, but it is expected that in a future styling system this would work differently.\r\n// - Feedback welcome at https://github.com/ocornut/imgui/issues/211\r\n// - BeginDisabled(false) essentially does nothing useful but is provided to facilitate use of boolean expressions. If you can avoid calling BeginDisabled(False)/EndDisabled() best to avoid it.\r\n// - Optimized shortcuts instead of PushStyleVar() + PushItemFlag()\r\nvoid ImGui::BeginDisabled(bool disabled)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;\r\n    if (!was_disabled && disabled)\r\n    {\r\n        g.DisabledAlphaBackup = g.Style.Alpha;\r\n        g.Style.Alpha *= g.Style.DisabledAlpha; // PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * g.Style.DisabledAlpha);\r\n    }\r\n    if (was_disabled || disabled)\r\n        g.CurrentItemFlags |= ImGuiItemFlags_Disabled;\r\n    g.ItemFlagsStack.push_back(g.CurrentItemFlags);\r\n    g.DisabledStackSize++;\r\n}\r\n\r\nvoid ImGui::EndDisabled()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(g.DisabledStackSize > 0);\r\n    g.DisabledStackSize--;\r\n    bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;\r\n    //PopItemFlag();\r\n    g.ItemFlagsStack.pop_back();\r\n    g.CurrentItemFlags = g.ItemFlagsStack.back();\r\n    if (was_disabled && (g.CurrentItemFlags & ImGuiItemFlags_Disabled) == 0)\r\n        g.Style.Alpha = g.DisabledAlphaBackup; //PopStyleVar();\r\n}\r\n\r\n// FIXME: Look into renaming this once we have settled the new Focus/Activation/TabStop system.\r\nvoid ImGui::PushAllowKeyboardFocus(bool allow_keyboard_focus)\r\n{\r\n    PushItemFlag(ImGuiItemFlags_NoTabStop, !allow_keyboard_focus);\r\n}\r\n\r\nvoid ImGui::PopAllowKeyboardFocus()\r\n{\r\n    PopItemFlag();\r\n}\r\n\r\nvoid ImGui::PushButtonRepeat(bool repeat)\r\n{\r\n    PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat);\r\n}\r\n\r\nvoid ImGui::PopButtonRepeat()\r\n{\r\n    PopItemFlag();\r\n}\r\n\r\nvoid ImGui::PushTextWrapPos(float wrap_pos_x)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    window->DC.TextWrapPosStack.push_back(window->DC.TextWrapPos);\r\n    window->DC.TextWrapPos = wrap_pos_x;\r\n}\r\n\r\nvoid ImGui::PopTextWrapPos()\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    window->DC.TextWrapPos = window->DC.TextWrapPosStack.back();\r\n    window->DC.TextWrapPosStack.pop_back();\r\n}\r\n\r\nstatic ImGuiWindow* GetCombinedRootWindow(ImGuiWindow* window, bool popup_hierarchy)\r\n{\r\n    ImGuiWindow* last_window = NULL;\r\n    while (last_window != window)\r\n    {\r\n        last_window = window;\r\n        window = window->RootWindow;\r\n        if (popup_hierarchy)\r\n            window = window->RootWindowPopupTree;\r\n    }\r\n    return window;\r\n}\r\n\r\nbool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent, bool popup_hierarchy)\r\n{\r\n    ImGuiWindow* window_root = GetCombinedRootWindow(window, popup_hierarchy);\r\n    if (window_root == potential_parent)\r\n        return true;\r\n    while (window != NULL)\r\n    {\r\n        if (window == potential_parent)\r\n            return true;\r\n        if (window == window_root) // end of chain\r\n            return false;\r\n        window = window->ParentWindow;\r\n    }\r\n    return false;\r\n}\r\n\r\nbool ImGui::IsWindowWithinBeginStackOf(ImGuiWindow* window, ImGuiWindow* potential_parent)\r\n{\r\n    if (window->RootWindow == potential_parent)\r\n        return true;\r\n    while (window != NULL)\r\n    {\r\n        if (window == potential_parent)\r\n            return true;\r\n        window = window->ParentWindowInBeginStack;\r\n    }\r\n    return false;\r\n}\r\n\r\nbool ImGui::IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n\r\n    // It would be saner to ensure that display layer is always reflected in the g.Windows[] order, which would likely requires altering all manipulations of that array\r\n    const int display_layer_delta = GetWindowDisplayLayer(potential_above) - GetWindowDisplayLayer(potential_below);\r\n    if (display_layer_delta != 0)\r\n        return display_layer_delta > 0;\r\n\r\n    for (int i = g.Windows.Size - 1; i >= 0; i--)\r\n    {\r\n        ImGuiWindow* candidate_window = g.Windows[i];\r\n        if (candidate_window == potential_above)\r\n            return true;\r\n        if (candidate_window == potential_below)\r\n            return false;\r\n    }\r\n    return false;\r\n}\r\n\r\nbool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)\r\n{\r\n    IM_ASSERT((flags & (ImGuiHoveredFlags_AllowWhenOverlapped | ImGuiHoveredFlags_AllowWhenDisabled)) == 0);   // Flags not supported by this function\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* ref_window = g.HoveredWindow;\r\n    ImGuiWindow* cur_window = g.CurrentWindow;\r\n    if (ref_window == NULL)\r\n        return false;\r\n\r\n    if ((flags & ImGuiHoveredFlags_AnyWindow) == 0)\r\n    {\r\n        IM_ASSERT(cur_window); // Not inside a Begin()/End()\r\n        const bool popup_hierarchy = (flags & ImGuiHoveredFlags_NoPopupHierarchy) == 0;\r\n        if (flags & ImGuiHoveredFlags_RootWindow)\r\n            cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy);\r\n\r\n        bool result;\r\n        if (flags & ImGuiHoveredFlags_ChildWindows)\r\n            result = IsWindowChildOf(ref_window, cur_window, popup_hierarchy);\r\n        else\r\n            result = (ref_window == cur_window);\r\n        if (!result)\r\n            return false;\r\n    }\r\n\r\n    if (!IsWindowContentHoverable(ref_window, flags))\r\n        return false;\r\n    if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))\r\n        if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != ref_window->MoveId)\r\n            return false;\r\n    return true;\r\n}\r\n\r\nbool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* ref_window = g.NavWindow;\r\n    ImGuiWindow* cur_window = g.CurrentWindow;\r\n\r\n    if (ref_window == NULL)\r\n        return false;\r\n    if (flags & ImGuiFocusedFlags_AnyWindow)\r\n        return true;\r\n\r\n    IM_ASSERT(cur_window); // Not inside a Begin()/End()\r\n    const bool popup_hierarchy = (flags & ImGuiFocusedFlags_NoPopupHierarchy) == 0;\r\n    if (flags & ImGuiHoveredFlags_RootWindow)\r\n        cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy);\r\n\r\n    if (flags & ImGuiHoveredFlags_ChildWindows)\r\n        return IsWindowChildOf(ref_window, cur_window, popup_hierarchy);\r\n    else\r\n        return (ref_window == cur_window);\r\n}\r\n\r\n// Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)\r\n// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically.\r\n// If you want a window to never be focused, you may use the e.g. NoInputs flag.\r\nbool ImGui::IsWindowNavFocusable(ImGuiWindow* window)\r\n{\r\n    return window->WasActive && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);\r\n}\r\n\r\nfloat ImGui::GetWindowWidth()\r\n{\r\n    ImGuiWindow* window = GImGui->CurrentWindow;\r\n    return window->Size.x;\r\n}\r\n\r\nfloat ImGui::GetWindowHeight()\r\n{\r\n    ImGuiWindow* window = GImGui->CurrentWindow;\r\n    return window->Size.y;\r\n}\r\n\r\nImVec2 ImGui::GetWindowPos()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    return window->Pos;\r\n}\r\n\r\nvoid ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)\r\n{\r\n    // Test condition (NB: bit 0 is always true) and clear flags for next time\r\n    if (cond && (window->SetWindowPosAllowFlags & cond) == 0)\r\n        return;\r\n\r\n    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.\r\n    window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);\r\n    window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);\r\n\r\n    // Set\r\n    const ImVec2 old_pos = window->Pos;\r\n    window->Pos = ImFloor(pos);\r\n    ImVec2 offset = window->Pos - old_pos;\r\n    window->DC.CursorPos += offset;         // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor\r\n    window->DC.CursorMaxPos += offset;      // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected.\r\n    window->DC.IdealMaxPos += offset;\r\n    window->DC.CursorStartPos += offset;\r\n}\r\n\r\nvoid ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindowRead();\r\n    SetWindowPos(window, pos, cond);\r\n}\r\n\r\nvoid ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)\r\n{\r\n    if (ImGuiWindow* window = FindWindowByName(name))\r\n        SetWindowPos(window, pos, cond);\r\n}\r\n\r\nImVec2 ImGui::GetWindowSize()\r\n{\r\n    ImGuiWindow* window = GetCurrentWindowRead();\r\n    return window->Size;\r\n}\r\n\r\nvoid ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)\r\n{\r\n    // Test condition (NB: bit 0 is always true) and clear flags for next time\r\n    if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)\r\n        return;\r\n\r\n    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.\r\n    window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);\r\n\r\n    // Set\r\n    if (size.x > 0.0f)\r\n    {\r\n        window->AutoFitFramesX = 0;\r\n        window->SizeFull.x = IM_FLOOR(size.x);\r\n    }\r\n    else\r\n    {\r\n        window->AutoFitFramesX = 2;\r\n        window->AutoFitOnlyGrows = false;\r\n    }\r\n    if (size.y > 0.0f)\r\n    {\r\n        window->AutoFitFramesY = 0;\r\n        window->SizeFull.y = IM_FLOOR(size.y);\r\n    }\r\n    else\r\n    {\r\n        window->AutoFitFramesY = 2;\r\n        window->AutoFitOnlyGrows = false;\r\n    }\r\n}\r\n\r\nvoid ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)\r\n{\r\n    SetWindowSize(GImGui->CurrentWindow, size, cond);\r\n}\r\n\r\nvoid ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)\r\n{\r\n    if (ImGuiWindow* window = FindWindowByName(name))\r\n        SetWindowSize(window, size, cond);\r\n}\r\n\r\nvoid ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)\r\n{\r\n    // Test condition (NB: bit 0 is always true) and clear flags for next time\r\n    if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)\r\n        return;\r\n    window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);\r\n\r\n    // Set\r\n    window->Collapsed = collapsed;\r\n}\r\n\r\nvoid ImGui::SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size)\r\n{\r\n    IM_ASSERT(window->HitTestHoleSize.x == 0);     // We don't support multiple holes/hit test filters\r\n    window->HitTestHoleSize = ImVec2ih(size);\r\n    window->HitTestHoleOffset = ImVec2ih(pos - window->Pos);\r\n}\r\n\r\nvoid ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)\r\n{\r\n    SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);\r\n}\r\n\r\nbool ImGui::IsWindowCollapsed()\r\n{\r\n    ImGuiWindow* window = GetCurrentWindowRead();\r\n    return window->Collapsed;\r\n}\r\n\r\nbool ImGui::IsWindowAppearing()\r\n{\r\n    ImGuiWindow* window = GetCurrentWindowRead();\r\n    return window->Appearing;\r\n}\r\n\r\nvoid ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)\r\n{\r\n    if (ImGuiWindow* window = FindWindowByName(name))\r\n        SetWindowCollapsed(window, collapsed, cond);\r\n}\r\n\r\nvoid ImGui::SetWindowFocus()\r\n{\r\n    FocusWindow(GImGui->CurrentWindow);\r\n}\r\n\r\nvoid ImGui::SetWindowFocus(const char* name)\r\n{\r\n    if (name)\r\n    {\r\n        if (ImGuiWindow* window = FindWindowByName(name))\r\n            FocusWindow(window);\r\n    }\r\n    else\r\n    {\r\n        FocusWindow(NULL);\r\n    }\r\n}\r\n\r\nvoid ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.\r\n    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasPos;\r\n    g.NextWindowData.PosVal = pos;\r\n    g.NextWindowData.PosPivotVal = pivot;\r\n    g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;\r\n}\r\n\r\nvoid ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.\r\n    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSize;\r\n    g.NextWindowData.SizeVal = size;\r\n    g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;\r\n}\r\n\r\nvoid ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSizeConstraint;\r\n    g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);\r\n    g.NextWindowData.SizeCallback = custom_callback;\r\n    g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;\r\n}\r\n\r\n// Content size = inner scrollable rectangle, padded with WindowPadding.\r\n// SetNextWindowContentSize(ImVec2(100,100) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item.\r\nvoid ImGui::SetNextWindowContentSize(const ImVec2& size)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasContentSize;\r\n    g.NextWindowData.ContentSizeVal = ImFloor(size);\r\n}\r\n\r\nvoid ImGui::SetNextWindowScroll(const ImVec2& scroll)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasScroll;\r\n    g.NextWindowData.ScrollVal = scroll;\r\n}\r\n\r\nvoid ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.\r\n    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasCollapsed;\r\n    g.NextWindowData.CollapsedVal = collapsed;\r\n    g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;\r\n}\r\n\r\nvoid ImGui::SetNextWindowFocus()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasFocus;\r\n}\r\n\r\nvoid ImGui::SetNextWindowBgAlpha(float alpha)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasBgAlpha;\r\n    g.NextWindowData.BgAlphaVal = alpha;\r\n}\r\n\r\nImDrawList* ImGui::GetWindowDrawList()\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    return window->DrawList;\r\n}\r\n\r\nImFont* ImGui::GetFont()\r\n{\r\n    return GImGui->Font;\r\n}\r\n\r\nfloat ImGui::GetFontSize()\r\n{\r\n    return GImGui->FontSize;\r\n}\r\n\r\nImVec2 ImGui::GetFontTexUvWhitePixel()\r\n{\r\n    return GImGui->DrawListSharedData.TexUvWhitePixel;\r\n}\r\n\r\nvoid ImGui::SetWindowFontScale(float scale)\r\n{\r\n    IM_ASSERT(scale > 0.0f);\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    window->FontWindowScale = scale;\r\n    g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();\r\n}\r\n\r\nvoid ImGui::ActivateItem(ImGuiID id)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    g.NavNextActivateId = id;\r\n    g.NavNextActivateFlags = ImGuiActivateFlags_None;\r\n}\r\n\r\nvoid ImGui::PushFocusScope(ImGuiID id)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    g.FocusScopeStack.push_back(window->DC.NavFocusScopeIdCurrent);\r\n    window->DC.NavFocusScopeIdCurrent = id;\r\n}\r\n\r\nvoid ImGui::PopFocusScope()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    IM_ASSERT(g.FocusScopeStack.Size > 0); // Too many PopFocusScope() ?\r\n    window->DC.NavFocusScopeIdCurrent = g.FocusScopeStack.back();\r\n    g.FocusScopeStack.pop_back();\r\n}\r\n\r\nvoid ImGui::SetKeyboardFocusHere(int offset)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    IM_ASSERT(offset >= -1);    // -1 is allowed but not below\r\n    g.NavWindow = window;\r\n    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;\r\n    NavMoveRequestSubmit(ImGuiDir_None, offset < 0 ? ImGuiDir_Up : ImGuiDir_Down, ImGuiNavMoveFlags_Tabbing | ImGuiNavMoveFlags_FocusApi, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.\r\n    if (offset == -1)\r\n    {\r\n        NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);\r\n    }\r\n    else\r\n    {\r\n        g.NavTabbingDir = 1;\r\n        g.NavTabbingCounter = offset + 1;\r\n    }\r\n}\r\n\r\nvoid ImGui::SetItemDefaultFocus()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    if (!window->Appearing)\r\n        return;\r\n    if (g.NavWindow != window->RootWindowForNav || (!g.NavInitRequest && g.NavInitResultId == 0) || g.NavLayer != window->DC.NavLayerCurrent)\r\n        return;\r\n\r\n    g.NavInitRequest = false;\r\n    g.NavInitResultId = g.LastItemData.ID;\r\n    g.NavInitResultRectRel = WindowRectAbsToRel(window, g.LastItemData.Rect);\r\n    NavUpdateAnyRequestFlag();\r\n\r\n    // Scroll could be done in NavInitRequestApplyResult() via a opt-in flag (we however don't want regular init requests to scroll)\r\n    if (!IsItemVisible())\r\n        ScrollToRectEx(window, g.LastItemData.Rect, ImGuiScrollFlags_None);\r\n}\r\n\r\nvoid ImGui::SetStateStorage(ImGuiStorage* tree)\r\n{\r\n    ImGuiWindow* window = GImGui->CurrentWindow;\r\n    window->DC.StateStorage = tree ? tree : &window->StateStorage;\r\n}\r\n\r\nImGuiStorage* ImGui::GetStateStorage()\r\n{\r\n    ImGuiWindow* window = GImGui->CurrentWindow;\r\n    return window->DC.StateStorage;\r\n}\r\n\r\nvoid ImGui::PushID(const char* str_id)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    ImGuiID id = window->GetIDNoKeepAlive(str_id);\r\n    window->IDStack.push_back(id);\r\n}\r\n\r\nvoid ImGui::PushID(const char* str_id_begin, const char* str_id_end)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    ImGuiID id = window->GetIDNoKeepAlive(str_id_begin, str_id_end);\r\n    window->IDStack.push_back(id);\r\n}\r\n\r\nvoid ImGui::PushID(const void* ptr_id)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    ImGuiID id = window->GetIDNoKeepAlive(ptr_id);\r\n    window->IDStack.push_back(id);\r\n}\r\n\r\nvoid ImGui::PushID(int int_id)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    ImGuiID id = window->GetIDNoKeepAlive(int_id);\r\n    window->IDStack.push_back(id);\r\n}\r\n\r\n// Push a given id value ignoring the ID stack as a seed.\r\nvoid ImGui::PushOverrideID(ImGuiID id)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    if (g.DebugHookIdInfo == id)\r\n        DebugHookIdInfo(id, ImGuiDataType_ID, NULL, NULL);\r\n    window->IDStack.push_back(id);\r\n}\r\n\r\n// Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call\r\n// (note that when using this pattern, TestEngine's \"Stack Tool\" will tend to not display the intermediate stack level.\r\n//  for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more)\r\nImGuiID ImGui::GetIDWithSeed(const char* str, const char* str_end, ImGuiID seed)\r\n{\r\n    ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);\r\n    KeepAliveID(id);\r\n    ImGuiContext& g = *GImGui;\r\n    if (g.DebugHookIdInfo == id)\r\n        DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);\r\n    return id;\r\n}\r\n\r\nvoid ImGui::PopID()\r\n{\r\n    ImGuiWindow* window = GImGui->CurrentWindow;\r\n    IM_ASSERT(window->IDStack.Size > 1); // Too many PopID(), or could be popping in a wrong/different window?\r\n    window->IDStack.pop_back();\r\n}\r\n\r\nImGuiID ImGui::GetID(const char* str_id)\r\n{\r\n    ImGuiWindow* window = GImGui->CurrentWindow;\r\n    return window->GetID(str_id);\r\n}\r\n\r\nImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)\r\n{\r\n    ImGuiWindow* window = GImGui->CurrentWindow;\r\n    return window->GetID(str_id_begin, str_id_end);\r\n}\r\n\r\nImGuiID ImGui::GetID(const void* ptr_id)\r\n{\r\n    ImGuiWindow* window = GImGui->CurrentWindow;\r\n    return window->GetID(ptr_id);\r\n}\r\n\r\nbool ImGui::IsRectVisible(const ImVec2& size)\r\n{\r\n    ImGuiWindow* window = GImGui->CurrentWindow;\r\n    return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));\r\n}\r\n\r\nbool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)\r\n{\r\n    ImGuiWindow* window = GImGui->CurrentWindow;\r\n    return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));\r\n}\r\n\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] INPUTS\r\n//-----------------------------------------------------------------------------\r\n\r\n// Test if mouse cursor is hovering given rectangle\r\n// NB- Rectangle is clipped by our current clip setting\r\n// NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)\r\nbool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n\r\n    // Clip\r\n    ImRect rect_clipped(r_min, r_max);\r\n    if (clip)\r\n        rect_clipped.ClipWith(g.CurrentWindow->ClipRect);\r\n\r\n    // Expand for touch input\r\n    const ImRect rect_for_touch(rect_clipped.Min - g.Style.TouchExtraPadding, rect_clipped.Max + g.Style.TouchExtraPadding);\r\n    if (!rect_for_touch.Contains(g.IO.MousePos))\r\n        return false;\r\n    return true;\r\n}\r\n\r\nImGuiKeyData* ImGui::GetKeyData(ImGuiKey key)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    int index;\r\n#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO\r\n    IM_ASSERT(key >= ImGuiKey_LegacyNativeKey_BEGIN && key < ImGuiKey_NamedKey_END);\r\n    if (IsLegacyKey(key))\r\n        index = (g.IO.KeyMap[key] != -1) ? g.IO.KeyMap[key] : key; // Remap native->imgui or imgui->native\r\n    else\r\n        index = key;\r\n#else\r\n    IM_ASSERT(IsNamedKey(key) && \"Support for user key indices was dropped in favor of ImGuiKey. Please update backend & user code.\");\r\n    index = key - ImGuiKey_NamedKey_BEGIN;\r\n#endif\r\n    return &g.IO.KeysData[index];\r\n}\r\n\r\n#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO\r\nint ImGui::GetKeyIndex(ImGuiKey key)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(IsNamedKey(key));\r\n    const ImGuiKeyData* key_data = GetKeyData(key);\r\n    return (int)(key_data - g.IO.KeysData);\r\n}\r\n#endif\r\n\r\n// Those names a provided for debugging purpose and are not meant to be saved persistently not compared.\r\nstatic const char* const GKeyNames[] =\r\n{\r\n    \"Tab\", \"LeftArrow\", \"RightArrow\", \"UpArrow\", \"DownArrow\", \"PageUp\", \"PageDown\",\r\n    \"Home\", \"End\", \"Insert\", \"Delete\", \"Backspace\", \"Space\", \"Enter\", \"Escape\",\r\n    \"LeftCtrl\", \"LeftShift\", \"LeftAlt\", \"LeftSuper\", \"RightCtrl\", \"RightShift\", \"RightAlt\", \"RightSuper\", \"Menu\",\r\n    \"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\",\r\n    \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\",\r\n    \"F1\", \"F2\", \"F3\", \"F4\", \"F5\", \"F6\", \"F7\", \"F8\", \"F9\", \"F10\", \"F11\", \"F12\",\r\n    \"Apostrophe\", \"Comma\", \"Minus\", \"Period\", \"Slash\", \"Semicolon\", \"Equal\", \"LeftBracket\",\r\n    \"Backslash\", \"RightBracket\", \"GraveAccent\", \"CapsLock\", \"ScrollLock\", \"NumLock\", \"PrintScreen\",\r\n    \"Pause\", \"Keypad0\", \"Keypad1\", \"Keypad2\", \"Keypad3\", \"Keypad4\", \"Keypad5\", \"Keypad6\",\r\n    \"Keypad7\", \"Keypad8\", \"Keypad9\", \"KeypadDecimal\", \"KeypadDivide\", \"KeypadMultiply\",\r\n    \"KeypadSubtract\", \"KeypadAdd\", \"KeypadEnter\", \"KeypadEqual\",\r\n    \"GamepadStart\", \"GamepadBack\", \"GamepadFaceUp\", \"GamepadFaceDown\", \"GamepadFaceLeft\", \"GamepadFaceRight\",\r\n    \"GamepadDpadUp\", \"GamepadDpadDown\", \"GamepadDpadLeft\", \"GamepadDpadRight\",\r\n    \"GamepadL1\", \"GamepadR1\", \"GamepadL2\", \"GamepadR2\", \"GamepadL3\", \"GamepadR3\",\r\n    \"GamepadLStickUp\", \"GamepadLStickDown\", \"GamepadLStickLeft\", \"GamepadLStickRight\",\r\n    \"GamepadRStickUp\", \"GamepadRStickDown\", \"GamepadRStickLeft\", \"GamepadRStickRight\",\r\n    \"ModCtrl\", \"ModShift\", \"ModAlt\", \"ModSuper\"\r\n};\r\nIM_STATIC_ASSERT(ImGuiKey_NamedKey_COUNT == IM_ARRAYSIZE(GKeyNames));\r\n\r\nconst char* ImGui::GetKeyName(ImGuiKey key)\r\n{\r\n#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO\r\n    IM_ASSERT((IsNamedKey(key) || key == ImGuiKey_None) && \"Support for user key indices was dropped in favor of ImGuiKey. Please update backend and user code.\");\r\n#else\r\n    if (IsLegacyKey(key))\r\n    {\r\n        ImGuiIO& io = GetIO();\r\n        if (io.KeyMap[key] == -1)\r\n            return \"N/A\";\r\n        IM_ASSERT(IsNamedKey((ImGuiKey)io.KeyMap[key]));\r\n        key = (ImGuiKey)io.KeyMap[key];\r\n    }\r\n#endif\r\n    if (key == ImGuiKey_None)\r\n        return \"None\";\r\n    if (!IsNamedKey(key))\r\n        return \"Unknown\";\r\n\r\n    return GKeyNames[key - ImGuiKey_NamedKey_BEGIN];\r\n}\r\n\r\n// Note that Dear ImGui doesn't know the meaning/semantic of ImGuiKey from 0..511: they are legacy native keycodes.\r\n// Consider transitioning from 'IsKeyDown(MY_ENGINE_KEY_A)' (<1.87) to IsKeyDown(ImGuiKey_A) (>= 1.87)\r\nbool ImGui::IsKeyDown(ImGuiKey key)\r\n{\r\n    const ImGuiKeyData* key_data = GetKeyData(key);\r\n    return key_data->Down;\r\n}\r\n\r\n// t0 = previous time (e.g.: g.Time - g.IO.DeltaTime)\r\n// t1 = current time (e.g.: g.Time)\r\n// An event is triggered at:\r\n//  t = 0.0f     t = repeat_delay,    t = repeat_delay + repeat_rate*N\r\nint ImGui::CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate)\r\n{\r\n    if (t1 == 0.0f)\r\n        return 1;\r\n    if (t0 >= t1)\r\n        return 0;\r\n    if (repeat_rate <= 0.0f)\r\n        return (t0 < repeat_delay) && (t1 >= repeat_delay);\r\n    const int count_t0 = (t0 < repeat_delay) ? -1 : (int)((t0 - repeat_delay) / repeat_rate);\r\n    const int count_t1 = (t1 < repeat_delay) ? -1 : (int)((t1 - repeat_delay) / repeat_rate);\r\n    const int count = count_t1 - count_t0;\r\n    return count;\r\n}\r\n\r\nint ImGui::GetKeyPressedAmount(ImGuiKey key, float repeat_delay, float repeat_rate)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    const ImGuiKeyData* key_data = GetKeyData(key);\r\n    const float t = key_data->DownDuration;\r\n    return CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, repeat_delay, repeat_rate);\r\n}\r\n\r\nbool ImGui::IsKeyPressed(ImGuiKey key, bool repeat)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    const ImGuiKeyData* key_data = GetKeyData(key);\r\n    const float t = key_data->DownDuration;\r\n    if (t == 0.0f)\r\n        return true;\r\n    if (repeat && t > g.IO.KeyRepeatDelay)\r\n        return GetKeyPressedAmount(key, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0;\r\n    return false;\r\n}\r\n\r\nbool ImGui::IsKeyReleased(ImGuiKey key)\r\n{\r\n    const ImGuiKeyData* key_data = GetKeyData(key);\r\n    return key_data->DownDurationPrev >= 0.0f && !key_data->Down;\r\n}\r\n\r\nbool ImGui::IsMouseDown(ImGuiMouseButton button)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));\r\n    return g.IO.MouseDown[button];\r\n}\r\n\r\nbool ImGui::IsMouseClicked(ImGuiMouseButton button, bool repeat)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));\r\n    const float t = g.IO.MouseDownDuration[button];\r\n    if (t == 0.0f)\r\n        return true;\r\n\r\n    if (repeat && t > g.IO.KeyRepeatDelay)\r\n    {\r\n        // FIXME: 2019/05/03: Our old repeat code was wrong here and led to doubling the repeat rate, which made it an ok rate for repeat on mouse hold.\r\n        int amount = CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate * 0.50f);\r\n        if (amount > 0)\r\n            return true;\r\n    }\r\n    return false;\r\n}\r\n\r\nbool ImGui::IsMouseReleased(ImGuiMouseButton button)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));\r\n    return g.IO.MouseReleased[button];\r\n}\r\n\r\nbool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));\r\n    return g.IO.MouseClickedCount[button] == 2;\r\n}\r\n\r\nint ImGui::GetMouseClickedCount(ImGuiMouseButton button)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));\r\n    return g.IO.MouseClickedCount[button];\r\n}\r\n\r\n// Return if a mouse click/drag went past the given threshold. Valid to call during the MouseReleased frame.\r\n// [Internal] This doesn't test if the button is pressed\r\nbool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));\r\n    if (lock_threshold < 0.0f)\r\n        lock_threshold = g.IO.MouseDragThreshold;\r\n    return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;\r\n}\r\n\r\nbool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));\r\n    if (!g.IO.MouseDown[button])\r\n        return false;\r\n    return IsMouseDragPastThreshold(button, lock_threshold);\r\n}\r\n\r\nImVec2 ImGui::GetMousePos()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    return g.IO.MousePos;\r\n}\r\n\r\n// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!\r\nImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    if (g.BeginPopupStack.Size > 0)\r\n        return g.OpenPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos;\r\n    return g.IO.MousePos;\r\n}\r\n\r\n// We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position.\r\nbool ImGui::IsMousePosValid(const ImVec2* mouse_pos)\r\n{\r\n    // The assert is only to silence a false-positive in XCode Static Analysis.\r\n    // Because GImGui is not dereferenced in every code path, the static analyzer assume that it may be NULL (which it doesn't for other functions).\r\n    IM_ASSERT(GImGui != NULL);\r\n    const float MOUSE_INVALID = -256000.0f;\r\n    ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos;\r\n    return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID;\r\n}\r\n\r\n// [WILL OBSOLETE] This was designed for backends, but prefer having backend maintain a mask of held mouse buttons, because upcoming input queue system will make this invalid.\r\nbool ImGui::IsAnyMouseDown()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)\r\n        if (g.IO.MouseDown[n])\r\n            return true;\r\n    return false;\r\n}\r\n\r\n// Return the delta from the initial clicking position while the mouse button is clicked or was just released.\r\n// This is locked and return 0.0f until the mouse moves past a distance threshold at least once.\r\n// NB: This is only valid if IsMousePosValid(). backends in theory should always keep mouse position valid when dragging even outside the client window.\r\nImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));\r\n    if (lock_threshold < 0.0f)\r\n        lock_threshold = g.IO.MouseDragThreshold;\r\n    if (g.IO.MouseDown[button] || g.IO.MouseReleased[button])\r\n        if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)\r\n            if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MouseClickedPos[button]))\r\n                return g.IO.MousePos - g.IO.MouseClickedPos[button];\r\n    return ImVec2(0.0f, 0.0f);\r\n}\r\n\r\nvoid ImGui::ResetMouseDragDelta(ImGuiMouseButton button)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));\r\n    // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr\r\n    g.IO.MouseClickedPos[button] = g.IO.MousePos;\r\n}\r\n\r\nImGuiMouseCursor ImGui::GetMouseCursor()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    return g.MouseCursor;\r\n}\r\n\r\nvoid ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    g.MouseCursor = cursor_type;\r\n}\r\n\r\nvoid ImGui::CaptureKeyboardFromApp(bool capture)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    g.WantCaptureKeyboardNextFrame = capture ? 1 : 0;\r\n}\r\n\r\nvoid ImGui::CaptureMouseFromApp(bool capture)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    g.WantCaptureMouseNextFrame = capture ? 1 : 0;\r\n}\r\n\r\nstatic const char* GetInputSourceName(ImGuiInputSource source)\r\n{\r\n    const char* input_source_names[] = { \"None\", \"Mouse\", \"Keyboard\", \"Gamepad\", \"Nav\", \"Clipboard\" };\r\n    IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT && source >= 0 && source < ImGuiInputSource_COUNT);\r\n    return input_source_names[source];\r\n}\r\n\r\n\r\n// Process input queue\r\n// - trickle_fast_inputs = false : process all events, turn into flattened input state (e.g. successive down/up/down/up will be lost)\r\n// - trickle_fast_inputs = true  : process as many events as possible (successive down/up/down/up will be trickled over several frames so nothing is lost) (new feature in 1.87)\r\nvoid ImGui::UpdateInputEvents(bool trickle_fast_inputs)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiIO& io = g.IO;\r\n\r\n    bool mouse_moved = false, mouse_wheeled = false, key_changed = false, text_inputed = false;\r\n    int  mouse_button_changed = 0x00;\r\n    ImBitArray<ImGuiKey_KeysData_SIZE> key_changed_mask;\r\n\r\n    int event_n = 0;\r\n    for (; event_n < g.InputEventsQueue.Size; event_n++)\r\n    {\r\n        const ImGuiInputEvent* e = &g.InputEventsQueue[event_n];\r\n        if (e->Type == ImGuiInputEventType_MousePos)\r\n        {\r\n            ImVec2 event_pos(e->MousePos.PosX, e->MousePos.PosY);\r\n            if (IsMousePosValid(&event_pos))\r\n                event_pos = ImVec2(ImFloorSigned(event_pos.x), ImFloorSigned(event_pos.y)); // Apply same flooring as UpdateMouseInputs()\r\n            if (io.MousePos.x != event_pos.x || io.MousePos.y != event_pos.y)\r\n            {\r\n                // Trickling Rule: Stop processing queued events if we already handled a mouse button change\r\n                if (trickle_fast_inputs && (mouse_button_changed != 0 || mouse_wheeled || key_changed || text_inputed))\r\n                    break;\r\n                io.MousePos = event_pos;\r\n                mouse_moved = true;\r\n            }\r\n        }\r\n        else if (e->Type == ImGuiInputEventType_MouseButton)\r\n        {\r\n            const ImGuiMouseButton button = e->MouseButton.Button;\r\n            IM_ASSERT(button >= 0 && button < ImGuiMouseButton_COUNT);\r\n            if (io.MouseDown[button] != e->MouseButton.Down)\r\n            {\r\n                // Trickling Rule: Stop processing queued events if we got multiple action on the same button\r\n                if (trickle_fast_inputs && ((mouse_button_changed & (1 << button)) || mouse_wheeled))\r\n                    break;\r\n                io.MouseDown[button] = e->MouseButton.Down;\r\n                mouse_button_changed |= (1 << button);\r\n            }\r\n        }\r\n        else if (e->Type == ImGuiInputEventType_MouseWheel)\r\n        {\r\n            if (e->MouseWheel.WheelX != 0.0f || e->MouseWheel.WheelY != 0.0f)\r\n            {\r\n                // Trickling Rule: Stop processing queued events if we got multiple action on the event\r\n                if (trickle_fast_inputs && (mouse_wheeled || mouse_button_changed != 0))\r\n                    break;\r\n                io.MouseWheelH += e->MouseWheel.WheelX;\r\n                io.MouseWheel += e->MouseWheel.WheelY;\r\n                mouse_wheeled = true;\r\n            }\r\n        }\r\n        else if (e->Type == ImGuiInputEventType_Key)\r\n        {\r\n            ImGuiKey key = e->Key.Key;\r\n            IM_ASSERT(key != ImGuiKey_None);\r\n            const int keydata_index = (key - ImGuiKey_KeysData_OFFSET);\r\n            ImGuiKeyData* keydata = &io.KeysData[keydata_index];\r\n            if (keydata->Down != e->Key.Down || keydata->AnalogValue != e->Key.AnalogValue)\r\n            {\r\n                // Trickling Rule: Stop processing queued events if we got multiple action on the same button\r\n                if (trickle_fast_inputs && keydata->Down != e->Key.Down && (key_changed_mask.TestBit(keydata_index) || text_inputed || mouse_button_changed != 0))\r\n                    break;\r\n                keydata->Down = e->Key.Down;\r\n                keydata->AnalogValue = e->Key.AnalogValue;\r\n                key_changed = true;\r\n                key_changed_mask.SetBit(keydata_index);\r\n\r\n                if (key == ImGuiKey_ModCtrl || key == ImGuiKey_ModShift || key == ImGuiKey_ModAlt || key == ImGuiKey_ModSuper)\r\n                {\r\n                    if (key == ImGuiKey_ModCtrl) { io.KeyCtrl = keydata->Down; }\r\n                    if (key == ImGuiKey_ModShift) { io.KeyShift = keydata->Down; }\r\n                    if (key == ImGuiKey_ModAlt) { io.KeyAlt = keydata->Down; }\r\n                    if (key == ImGuiKey_ModSuper) { io.KeySuper = keydata->Down; }\r\n                    io.KeyMods = GetMergedKeyModFlags();\r\n                }\r\n            }\r\n        }\r\n        else if (e->Type == ImGuiInputEventType_Char)\r\n        {\r\n            // Trickling Rule: Stop processing queued events if keys/mouse have been interacted with\r\n            if (trickle_fast_inputs && (key_changed || mouse_button_changed != 0 || mouse_moved || mouse_wheeled))\r\n                break;\r\n            unsigned int c = e->Text.Char;\r\n            io.InputQueueCharacters.push_back(c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID);\r\n            text_inputed = true;\r\n        }\r\n        else if (e->Type == ImGuiInputEventType_Focus)\r\n        {\r\n            // We intentionally overwrite this and process lower, in order to give a chance\r\n            // to multi-viewports backends to queue AddFocusEvent(false) + AddFocusEvent(true) in same frame.\r\n            io.AppFocusLost = !e->AppFocused.Focused;\r\n        }\r\n        else\r\n        {\r\n            IM_ASSERT(0 && \"Unknown event!\");\r\n        }\r\n    }\r\n\r\n    // Record trail (for domain-specific applications wanting to access a precise trail)\r\n    //if (event_n != 0) IMGUI_DEBUG_LOG(\"Processed: %d / Remaining: %d\\n\", event_n, g.InputEventsQueue.Size - event_n);\r\n    for (int n = 0; n < event_n; n++)\r\n        g.InputEventsTrail.push_back(g.InputEventsQueue[n]);\r\n\r\n    // Remaining events will be processed on the next frame\r\n    if (event_n == g.InputEventsQueue.Size)\r\n        g.InputEventsQueue.resize(0);\r\n    else\r\n        g.InputEventsQueue.erase(g.InputEventsQueue.Data, g.InputEventsQueue.Data + event_n);\r\n\r\n    // Clear buttons state when focus is lost\r\n    // (this is useful so e.g. releasing Alt after focus loss on Alt-Tab doesn't trigger the Alt menu toggle)\r\n    if (g.IO.AppFocusLost)\r\n    {\r\n        g.IO.ClearInputKeys();\r\n        g.IO.AppFocusLost = false;\r\n    }\r\n}\r\n\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] ERROR CHECKING\r\n//-----------------------------------------------------------------------------\r\n\r\n// Helper function to verify ABI compatibility between caller code and compiled version of Dear ImGui.\r\n// Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit\r\n// If the user has inconsistent compilation settings, imgui configuration #define, packing pragma, etc. your user code\r\n// may see different structures than what imgui.cpp sees, which is problematic.\r\n// We usually require settings to be in imconfig.h to make sure that they are accessible to all compilation units involved with Dear ImGui.\r\nbool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert, size_t sz_idx)\r\n{\r\n    bool error = false;\r\n    if (strcmp(version, IMGUI_VERSION) != 0) { error = true; IM_ASSERT(strcmp(version, IMGUI_VERSION) == 0 && \"Mismatched version string!\"); }\r\n    if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && \"Mismatched struct layout!\"); }\r\n    if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && \"Mismatched struct layout!\"); }\r\n    if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && \"Mismatched struct layout!\"); }\r\n    if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && \"Mismatched struct layout!\"); }\r\n    if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && \"Mismatched struct layout!\"); }\r\n    if (sz_idx != sizeof(ImDrawIdx)) { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && \"Mismatched struct layout!\"); }\r\n    return !error;\r\n}\r\n\r\nstatic void ImGui::ErrorCheckNewFrameSanityChecks()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n\r\n    // Check user IM_ASSERT macro\r\n    // (IF YOU GET A WARNING OR COMPILE ERROR HERE: it means your assert macro is incorrectly defined!\r\n    //  If your macro uses multiple statements, it NEEDS to be surrounded by a 'do { ... } while (0)' block.\r\n    //  This is a common C/C++ idiom to allow multiple statements macros to be used in control flow blocks.)\r\n    // #define IM_ASSERT(EXPR)   if (SomeCode(EXPR)) SomeMoreCode();                    // Wrong!\r\n    // #define IM_ASSERT(EXPR)   do { if (SomeCode(EXPR)) SomeMoreCode(); } while (0)   // Correct!\r\n    if (true) IM_ASSERT(1); else IM_ASSERT(0);\r\n\r\n    // Check user data\r\n    // (We pass an error message in the assert expression to make it visible to programmers who are not using a debugger, as most assert handlers display their argument)\r\n    IM_ASSERT(g.Initialized);\r\n    IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0)              && \"Need a positive DeltaTime!\");\r\n    IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount)  && \"Forgot to call Render() or EndFrame() at the end of the previous frame?\");\r\n    IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f  && \"Invalid DisplaySize value!\");\r\n    IM_ASSERT(g.IO.Fonts->IsBuilt()                                     && \"Font Atlas not built! Make sure you called ImGui_ImplXXXX_NewFrame() function for renderer backend, which should call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()\");\r\n    IM_ASSERT(g.Style.CurveTessellationTol > 0.0f                       && \"Invalid style setting!\");\r\n    IM_ASSERT(g.Style.CircleTessellationMaxError  > 0.0f                && \"Invalid style setting!\");\r\n    IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f            && \"Invalid style setting!\"); // Allows us to avoid a few clamps in color computations\r\n    IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && \"Invalid style setting.\");\r\n    IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);\r\n#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO\r\n    for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_COUNT; n++)\r\n        IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < IM_ARRAYSIZE(g.IO.KeysDown) && \"io.KeyMap[] contains an out of bound value (need to be 0..511, or -1 for unmapped key)\");\r\n\r\n    // Check: required key mapping (we intentionally do NOT check all keys to not pressure user into setting up everything, but Space is required and was only added in 1.60 WIP)\r\n    if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && g.IO.BackendUsingLegacyKeyArrays == 1)\r\n        IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && \"ImGuiKey_Space is not mapped, required for keyboard navigation.\");\r\n#endif\r\n\r\n    // Check: the io.ConfigWindowsResizeFromEdges option requires backend to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly.\r\n    if (g.IO.ConfigWindowsResizeFromEdges && !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseCursors))\r\n        g.IO.ConfigWindowsResizeFromEdges = false;\r\n}\r\n\r\nstatic void ImGui::ErrorCheckEndFrameSanityChecks()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n\r\n    // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame()\r\n    // One possible reason leading to this assert is that your backends update inputs _AFTER_ NewFrame().\r\n    // It is known that when some modal native windows called mid-frame takes focus away, some backends such as GLFW will\r\n    // send key release events mid-frame. This would normally trigger this assertion and lead to sheared inputs.\r\n    // We silently accommodate for this case by ignoring/ the case where all io.KeyXXX modifiers were released (aka key_mod_flags == 0),\r\n    // while still correctly asserting on mid-frame key press events.\r\n    const ImGuiKeyModFlags key_mod_flags = GetMergedKeyModFlags();\r\n    IM_ASSERT((key_mod_flags == 0 || g.IO.KeyMods == key_mod_flags) && \"Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods\");\r\n    IM_UNUSED(key_mod_flags);\r\n\r\n    // Recover from errors\r\n    //ErrorCheckEndFrameRecover();\r\n\r\n    // Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you\r\n    // to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API).\r\n    if (g.CurrentWindowStack.Size != 1)\r\n    {\r\n        if (g.CurrentWindowStack.Size > 1)\r\n        {\r\n            IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, \"Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?\");\r\n            while (g.CurrentWindowStack.Size > 1)\r\n                End();\r\n        }\r\n        else\r\n        {\r\n            IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, \"Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?\");\r\n        }\r\n    }\r\n\r\n    IM_ASSERT_USER_ERROR(g.GroupStack.Size == 0, \"Missing EndGroup call!\");\r\n}\r\n\r\n// Experimental recovery from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls.\r\n// Must be called during or before EndFrame().\r\n// This is generally flawed as we are not necessarily End/Popping things in the right order.\r\n// FIXME: Can't recover from inside BeginTabItem/EndTabItem yet.\r\n// FIXME: Can't recover from interleaved BeginTabBar/Begin\r\nvoid    ImGui::ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void* user_data)\r\n{\r\n    // PVS-Studio V1044 is \"Loop break conditions do not depend on the number of iterations\"\r\n    ImGuiContext& g = *GImGui;\r\n    while (g.CurrentWindowStack.Size > 0) //-V1044\r\n    {\r\n        ErrorCheckEndWindowRecover(log_callback, user_data);\r\n        ImGuiWindow* window = g.CurrentWindow;\r\n        if (g.CurrentWindowStack.Size == 1)\r\n        {\r\n            IM_ASSERT(window->IsFallbackWindow);\r\n            break;\r\n        }\r\n        IM_ASSERT(window == g.CurrentWindow);\r\n        if (window->Flags & ImGuiWindowFlags_ChildWindow)\r\n        {\r\n            if (log_callback) log_callback(user_data, \"Recovered from missing EndChild() for '%s'\", window->Name);\r\n            EndChild();\r\n        }\r\n        else\r\n        {\r\n            if (log_callback) log_callback(user_data, \"Recovered from missing End() for '%s'\", window->Name);\r\n            End();\r\n        }\r\n    }\r\n}\r\n\r\n// Must be called before End()/EndChild()\r\nvoid    ImGui::ErrorCheckEndWindowRecover(ImGuiErrorLogCallback log_callback, void* user_data)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    while (g.CurrentTable && (g.CurrentTable->OuterWindow == g.CurrentWindow || g.CurrentTable->InnerWindow == g.CurrentWindow))\r\n    {\r\n        if (log_callback) log_callback(user_data, \"Recovered from missing EndTable() in '%s'\", g.CurrentTable->OuterWindow->Name);\r\n        EndTable();\r\n    }\r\n\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    ImGuiStackSizes* stack_sizes = &g.CurrentWindowStack.back().StackSizesOnBegin;\r\n    IM_ASSERT(window != NULL);\r\n    while (g.CurrentTabBar != NULL) //-V1044\r\n    {\r\n        if (log_callback) log_callback(user_data, \"Recovered from missing EndTabBar() in '%s'\", window->Name);\r\n        EndTabBar();\r\n    }\r\n    while (window->DC.TreeDepth > 0)\r\n    {\r\n        if (log_callback) log_callback(user_data, \"Recovered from missing TreePop() in '%s'\", window->Name);\r\n        TreePop();\r\n    }\r\n    while (g.GroupStack.Size > stack_sizes->SizeOfGroupStack) //-V1044\r\n    {\r\n        if (log_callback) log_callback(user_data, \"Recovered from missing EndGroup() in '%s'\", window->Name);\r\n        EndGroup();\r\n    }\r\n    while (window->IDStack.Size > 1)\r\n    {\r\n        if (log_callback) log_callback(user_data, \"Recovered from missing PopID() in '%s'\", window->Name);\r\n        PopID();\r\n    }\r\n    while (g.DisabledStackSize > stack_sizes->SizeOfDisabledStack) //-V1044\r\n    {\r\n        if (log_callback) log_callback(user_data, \"Recovered from missing EndDisabled() in '%s'\", window->Name);\r\n        EndDisabled();\r\n    }\r\n    while (g.ColorStack.Size > stack_sizes->SizeOfColorStack)\r\n    {\r\n        if (log_callback) log_callback(user_data, \"Recovered from missing PopStyleColor() in '%s' for ImGuiCol_%s\", window->Name, GetStyleColorName(g.ColorStack.back().Col));\r\n        PopStyleColor();\r\n    }\r\n    while (g.ItemFlagsStack.Size > stack_sizes->SizeOfItemFlagsStack) //-V1044\r\n    {\r\n        if (log_callback) log_callback(user_data, \"Recovered from missing PopItemFlag() in '%s'\", window->Name);\r\n        PopItemFlag();\r\n    }\r\n    while (g.StyleVarStack.Size > stack_sizes->SizeOfStyleVarStack) //-V1044\r\n    {\r\n        if (log_callback) log_callback(user_data, \"Recovered from missing PopStyleVar() in '%s'\", window->Name);\r\n        PopStyleVar();\r\n    }\r\n    while (g.FocusScopeStack.Size > stack_sizes->SizeOfFocusScopeStack) //-V1044\r\n    {\r\n        if (log_callback) log_callback(user_data, \"Recovered from missing PopFocusScope() in '%s'\", window->Name);\r\n        PopFocusScope();\r\n    }\r\n}\r\n\r\n// Save current stack sizes for later compare\r\nvoid ImGuiStackSizes::SetToCurrentState()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    SizeOfIDStack = (short)window->IDStack.Size;\r\n    SizeOfColorStack = (short)g.ColorStack.Size;\r\n    SizeOfStyleVarStack = (short)g.StyleVarStack.Size;\r\n    SizeOfFontStack = (short)g.FontStack.Size;\r\n    SizeOfFocusScopeStack = (short)g.FocusScopeStack.Size;\r\n    SizeOfGroupStack = (short)g.GroupStack.Size;\r\n    SizeOfItemFlagsStack = (short)g.ItemFlagsStack.Size;\r\n    SizeOfBeginPopupStack = (short)g.BeginPopupStack.Size;\r\n    SizeOfDisabledStack = (short)g.DisabledStackSize;\r\n}\r\n\r\n// Compare to detect usage errors\r\nvoid ImGuiStackSizes::CompareWithCurrentState()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    IM_UNUSED(window);\r\n\r\n    // Window stacks\r\n    // NOT checking: DC.ItemWidth, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin)\r\n    IM_ASSERT(SizeOfIDStack         == window->IDStack.Size     && \"PushID/PopID or TreeNode/TreePop Mismatch!\");\r\n\r\n    // Global stacks\r\n    // For color, style and font stacks there is an incentive to use Push/Begin/Pop/.../End patterns, so we relax our checks a little to allow them.\r\n    IM_ASSERT(SizeOfGroupStack      == g.GroupStack.Size        && \"BeginGroup/EndGroup Mismatch!\");\r\n    IM_ASSERT(SizeOfBeginPopupStack == g.BeginPopupStack.Size   && \"BeginPopup/EndPopup or BeginMenu/EndMenu Mismatch!\");\r\n    IM_ASSERT(SizeOfDisabledStack   == g.DisabledStackSize      && \"BeginDisabled/EndDisabled Mismatch!\");\r\n    IM_ASSERT(SizeOfItemFlagsStack  >= g.ItemFlagsStack.Size    && \"PushItemFlag/PopItemFlag Mismatch!\");\r\n    IM_ASSERT(SizeOfColorStack      >= g.ColorStack.Size        && \"PushStyleColor/PopStyleColor Mismatch!\");\r\n    IM_ASSERT(SizeOfStyleVarStack   >= g.StyleVarStack.Size     && \"PushStyleVar/PopStyleVar Mismatch!\");\r\n    IM_ASSERT(SizeOfFontStack       >= g.FontStack.Size         && \"PushFont/PopFont Mismatch!\");\r\n    IM_ASSERT(SizeOfFocusScopeStack == g.FocusScopeStack.Size   && \"PushFocusScope/PopFocusScope Mismatch!\");\r\n}\r\n\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] LAYOUT\r\n//-----------------------------------------------------------------------------\r\n// - ItemSize()\r\n// - ItemAdd()\r\n// - SameLine()\r\n// - GetCursorScreenPos()\r\n// - SetCursorScreenPos()\r\n// - GetCursorPos(), GetCursorPosX(), GetCursorPosY()\r\n// - SetCursorPos(), SetCursorPosX(), SetCursorPosY()\r\n// - GetCursorStartPos()\r\n// - Indent()\r\n// - Unindent()\r\n// - SetNextItemWidth()\r\n// - PushItemWidth()\r\n// - PushMultiItemsWidths()\r\n// - PopItemWidth()\r\n// - CalcItemWidth()\r\n// - CalcItemSize()\r\n// - GetTextLineHeight()\r\n// - GetTextLineHeightWithSpacing()\r\n// - GetFrameHeight()\r\n// - GetFrameHeightWithSpacing()\r\n// - GetContentRegionMax()\r\n// - GetContentRegionMaxAbs() [Internal]\r\n// - GetContentRegionAvail(),\r\n// - GetWindowContentRegionMin(), GetWindowContentRegionMax()\r\n// - BeginGroup()\r\n// - EndGroup()\r\n// Also see in imgui_widgets: tab bars, columns.\r\n//-----------------------------------------------------------------------------\r\n\r\n// Advance cursor given item size for layout.\r\n// Register minimum needed size so it can extend the bounding box used for auto-fit calculation.\r\n// See comments in ItemAdd() about how/why the size provided to ItemSize() vs ItemAdd() may often different.\r\nvoid ImGui::ItemSize(const ImVec2& size, float text_baseline_y)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    if (window->SkipItems)\r\n        return;\r\n\r\n    // We increase the height in this function to accommodate for baseline offset.\r\n    // In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor,\r\n    // but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect.\r\n    const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(0.0f, window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f;\r\n    const float line_height = ImMax(window->DC.CurrLineSize.y, size.y + offset_to_match_baseline_y);\r\n\r\n    // Always align ourselves on pixel boundaries\r\n    //if (g.IO.KeyAlt) window->DrawList->AddRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)); // [DEBUG]\r\n    window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x;\r\n    window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y;\r\n    window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);    // Next line\r\n    window->DC.CursorPos.y = IM_FLOOR(window->DC.CursorPos.y + line_height + g.Style.ItemSpacing.y);        // Next line\r\n    window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);\r\n    window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);\r\n    //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]\r\n\r\n    window->DC.PrevLineSize.y = line_height;\r\n    window->DC.CurrLineSize.y = 0.0f;\r\n    window->DC.PrevLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, text_baseline_y);\r\n    window->DC.CurrLineTextBaseOffset = 0.0f;\r\n\r\n    // Horizontal layout mode\r\n    if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)\r\n        SameLine();\r\n}\r\n\r\nvoid ImGui::ItemSize(const ImRect& bb, float text_baseline_y)\r\n{\r\n    ItemSize(bb.GetSize(), text_baseline_y);\r\n}\r\n\r\n// Declare item bounding box for clipping and interaction.\r\n// Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface\r\n// declare their minimum size requirement to ItemSize() and provide a larger region to ItemAdd() which is used drawing/interaction.\r\nbool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGuiItemFlags extra_flags)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n\r\n    // Set item data\r\n    // (DisplayRect is left untouched, made valid when ImGuiItemStatusFlags_HasDisplayRect is set)\r\n    g.LastItemData.ID = id;\r\n    g.LastItemData.Rect = bb;\r\n    g.LastItemData.NavRect = nav_bb_arg ? *nav_bb_arg : bb;\r\n    g.LastItemData.InFlags = g.CurrentItemFlags | extra_flags;\r\n    g.LastItemData.StatusFlags = ImGuiItemStatusFlags_None;\r\n\r\n    // Directional navigation processing\r\n    if (id != 0)\r\n    {\r\n        // Runs prior to clipping early-out\r\n        //  (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget\r\n        //  (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests\r\n        //      unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of\r\n        //      thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.\r\n        //      We could early out with \"if (is_clipped && !g.NavInitRequest) return false;\" but when we wouldn't be able\r\n        //      to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick).\r\n        // We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.\r\n        // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.\r\n        window->DC.NavLayersActiveMaskNext |= (1 << window->DC.NavLayerCurrent);\r\n        if (g.NavId == id || g.NavAnyRequest)\r\n            if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)\r\n                if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened))\r\n                    NavProcessItem();\r\n\r\n        // [DEBUG] People keep stumbling on this problem and using \"\" as identifier in the root of a window instead of \"##something\".\r\n        // Empty identifier are valid and useful in a small amount of cases, but 99.9% of the time you want to use \"##something\".\r\n        // READ THE FAQ: https://dearimgui.org/faq\r\n        IM_ASSERT(id != window->ID && \"Cannot have an empty ID at the root of a window. If you need an empty label, use ## and read the FAQ about how the ID Stack works!\");\r\n\r\n        // [DEBUG] Item Picker tool, when enabling the \"extended\" version we perform the check in ItemAdd()\r\n#ifdef IMGUI_DEBUG_TOOL_ITEM_PICKER_EX\r\n        if (id == g.DebugItemPickerBreakId)\r\n        {\r\n            IM_DEBUG_BREAK();\r\n            g.DebugItemPickerBreakId = 0;\r\n        }\r\n#endif\r\n    }\r\n    g.NextItemData.Flags = ImGuiNextItemDataFlags_None;\r\n\r\n#ifdef IMGUI_ENABLE_TEST_ENGINE\r\n    if (id != 0)\r\n        IMGUI_TEST_ENGINE_ITEM_ADD(nav_bb_arg ? *nav_bb_arg : bb, id);\r\n#endif\r\n\r\n    // Clipping test\r\n    const bool is_clipped = IsClippedEx(bb, id);\r\n    if (is_clipped)\r\n        return false;\r\n    //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]\r\n\r\n    // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)\r\n    if (IsMouseHoveringRect(bb.Min, bb.Max))\r\n        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredRect;\r\n    return true;\r\n}\r\n\r\n// Gets back to previous line and continue with horizontal layout\r\n//      offset_from_start_x == 0 : follow right after previous item\r\n//      offset_from_start_x != 0 : align to specified x position (relative to window/group left)\r\n//      spacing_w < 0            : use default spacing if pos_x == 0, no spacing if pos_x != 0\r\n//      spacing_w >= 0           : enforce spacing amount\r\nvoid ImGui::SameLine(float offset_from_start_x, float spacing_w)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return;\r\n\r\n    ImGuiContext& g = *GImGui;\r\n    if (offset_from_start_x != 0.0f)\r\n    {\r\n        if (spacing_w < 0.0f) spacing_w = 0.0f;\r\n        window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;\r\n        window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;\r\n    }\r\n    else\r\n    {\r\n        if (spacing_w < 0.0f) spacing_w = g.Style.ItemSpacing.x;\r\n        window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;\r\n        window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;\r\n    }\r\n    window->DC.CurrLineSize = window->DC.PrevLineSize;\r\n    window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;\r\n}\r\n\r\nImVec2 ImGui::GetCursorScreenPos()\r\n{\r\n    ImGuiWindow* window = GetCurrentWindowRead();\r\n    return window->DC.CursorPos;\r\n}\r\n\r\nvoid ImGui::SetCursorScreenPos(const ImVec2& pos)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    window->DC.CursorPos = pos;\r\n    window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);\r\n}\r\n\r\n// User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.\r\n// Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'.\r\nImVec2 ImGui::GetCursorPos()\r\n{\r\n    ImGuiWindow* window = GetCurrentWindowRead();\r\n    return window->DC.CursorPos - window->Pos + window->Scroll;\r\n}\r\n\r\nfloat ImGui::GetCursorPosX()\r\n{\r\n    ImGuiWindow* window = GetCurrentWindowRead();\r\n    return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;\r\n}\r\n\r\nfloat ImGui::GetCursorPosY()\r\n{\r\n    ImGuiWindow* window = GetCurrentWindowRead();\r\n    return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;\r\n}\r\n\r\nvoid ImGui::SetCursorPos(const ImVec2& local_pos)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    window->DC.CursorPos = window->Pos - window->Scroll + local_pos;\r\n    window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);\r\n}\r\n\r\nvoid ImGui::SetCursorPosX(float x)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;\r\n    window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);\r\n}\r\n\r\nvoid ImGui::SetCursorPosY(float y)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;\r\n    window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);\r\n}\r\n\r\nImVec2 ImGui::GetCursorStartPos()\r\n{\r\n    ImGuiWindow* window = GetCurrentWindowRead();\r\n    return window->DC.CursorStartPos - window->Pos;\r\n}\r\n\r\nvoid ImGui::Indent(float indent_w)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;\r\n    window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;\r\n}\r\n\r\nvoid ImGui::Unindent(float indent_w)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;\r\n    window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;\r\n}\r\n\r\n// Affect large frame+labels widgets only.\r\nvoid ImGui::SetNextItemWidth(float item_width)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasWidth;\r\n    g.NextItemData.Width = item_width;\r\n}\r\n\r\n// FIXME: Remove the == 0.0f behavior?\r\nvoid ImGui::PushItemWidth(float item_width)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width\r\n    window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);\r\n    g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;\r\n}\r\n\r\nvoid ImGui::PushMultiItemsWidths(int components, float w_full)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    const ImGuiStyle& style = g.Style;\r\n    const float w_item_one  = ImMax(1.0f, IM_FLOOR((w_full - (style.ItemInnerSpacing.x) * (components - 1)) / (float)components));\r\n    const float w_item_last = ImMax(1.0f, IM_FLOOR(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components - 1)));\r\n    window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width\r\n    window->DC.ItemWidthStack.push_back(w_item_last);\r\n    for (int i = 0; i < components - 2; i++)\r\n        window->DC.ItemWidthStack.push_back(w_item_one);\r\n    window->DC.ItemWidth = (components == 1) ? w_item_last : w_item_one;\r\n    g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;\r\n}\r\n\r\nvoid ImGui::PopItemWidth()\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    window->DC.ItemWidth = window->DC.ItemWidthStack.back();\r\n    window->DC.ItemWidthStack.pop_back();\r\n}\r\n\r\n// Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth().\r\n// The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags()\r\nfloat ImGui::CalcItemWidth()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    float w;\r\n    if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasWidth)\r\n        w = g.NextItemData.Width;\r\n    else\r\n        w = window->DC.ItemWidth;\r\n    if (w < 0.0f)\r\n    {\r\n        float region_max_x = GetContentRegionMaxAbs().x;\r\n        w = ImMax(1.0f, region_max_x - window->DC.CursorPos.x + w);\r\n    }\r\n    w = IM_FLOOR(w);\r\n    return w;\r\n}\r\n\r\n// [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth().\r\n// Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.\r\n// Note that only CalcItemWidth() is publicly exposed.\r\n// The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable)\r\nImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h)\r\n{\r\n    ImGuiWindow* window = GImGui->CurrentWindow;\r\n\r\n    ImVec2 region_max;\r\n    if (size.x < 0.0f || size.y < 0.0f)\r\n        region_max = GetContentRegionMaxAbs();\r\n\r\n    if (size.x == 0.0f)\r\n        size.x = default_w;\r\n    else if (size.x < 0.0f)\r\n        size.x = ImMax(4.0f, region_max.x - window->DC.CursorPos.x + size.x);\r\n\r\n    if (size.y == 0.0f)\r\n        size.y = default_h;\r\n    else if (size.y < 0.0f)\r\n        size.y = ImMax(4.0f, region_max.y - window->DC.CursorPos.y + size.y);\r\n\r\n    return size;\r\n}\r\n\r\nfloat ImGui::GetTextLineHeight()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    return g.FontSize;\r\n}\r\n\r\nfloat ImGui::GetTextLineHeightWithSpacing()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    return g.FontSize + g.Style.ItemSpacing.y;\r\n}\r\n\r\nfloat ImGui::GetFrameHeight()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    return g.FontSize + g.Style.FramePadding.y * 2.0f;\r\n}\r\n\r\nfloat ImGui::GetFrameHeightWithSpacing()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;\r\n}\r\n\r\n// FIXME: All the Contents Region function are messy or misleading. WE WILL AIM TO OBSOLETE ALL OF THEM WITH A NEW \"WORK RECT\" API. Thanks for your patience!\r\n\r\n// FIXME: This is in window space (not screen space!).\r\nImVec2 ImGui::GetContentRegionMax()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    ImVec2 mx = window->ContentRegionRect.Max - window->Pos;\r\n    if (window->DC.CurrentColumns || g.CurrentTable)\r\n        mx.x = window->WorkRect.Max.x - window->Pos.x;\r\n    return mx;\r\n}\r\n\r\n// [Internal] Absolute coordinate. Saner. This is not exposed until we finishing refactoring work rect features.\r\nImVec2 ImGui::GetContentRegionMaxAbs()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    ImVec2 mx = window->ContentRegionRect.Max;\r\n    if (window->DC.CurrentColumns || g.CurrentTable)\r\n        mx.x = window->WorkRect.Max.x;\r\n    return mx;\r\n}\r\n\r\nImVec2 ImGui::GetContentRegionAvail()\r\n{\r\n    ImGuiWindow* window = GImGui->CurrentWindow;\r\n    return GetContentRegionMaxAbs() - window->DC.CursorPos;\r\n}\r\n\r\n// In window space (not screen space!)\r\nImVec2 ImGui::GetWindowContentRegionMin()\r\n{\r\n    ImGuiWindow* window = GImGui->CurrentWindow;\r\n    return window->ContentRegionRect.Min - window->Pos;\r\n}\r\n\r\nImVec2 ImGui::GetWindowContentRegionMax()\r\n{\r\n    ImGuiWindow* window = GImGui->CurrentWindow;\r\n    return window->ContentRegionRect.Max - window->Pos;\r\n}\r\n\r\n// Lock horizontal starting position + capture group bounding box into one \"item\" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.)\r\n// Groups are currently a mishmash of functionalities which should perhaps be clarified and separated.\r\n// FIXME-OPT: Could we safely early out on ->SkipItems?\r\nvoid ImGui::BeginGroup()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n\r\n    g.GroupStack.resize(g.GroupStack.Size + 1);\r\n    ImGuiGroupData& group_data = g.GroupStack.back();\r\n    group_data.WindowID = window->ID;\r\n    group_data.BackupCursorPos = window->DC.CursorPos;\r\n    group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;\r\n    group_data.BackupIndent = window->DC.Indent;\r\n    group_data.BackupGroupOffset = window->DC.GroupOffset;\r\n    group_data.BackupCurrLineSize = window->DC.CurrLineSize;\r\n    group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset;\r\n    group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;\r\n    group_data.BackupHoveredIdIsAlive = g.HoveredId != 0;\r\n    group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive;\r\n    group_data.EmitItem = true;\r\n\r\n    window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;\r\n    window->DC.Indent = window->DC.GroupOffset;\r\n    window->DC.CursorMaxPos = window->DC.CursorPos;\r\n    window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);\r\n    if (g.LogEnabled)\r\n        g.LogLinePosY = -FLT_MAX; // To enforce a carriage return\r\n}\r\n\r\nvoid ImGui::EndGroup()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    IM_ASSERT(g.GroupStack.Size > 0); // Mismatched BeginGroup()/EndGroup() calls\r\n\r\n    ImGuiGroupData& group_data = g.GroupStack.back();\r\n    IM_ASSERT(group_data.WindowID == window->ID); // EndGroup() in wrong window?\r\n\r\n    ImRect group_bb(group_data.BackupCursorPos, ImMax(window->DC.CursorMaxPos, group_data.BackupCursorPos));\r\n\r\n    window->DC.CursorPos = group_data.BackupCursorPos;\r\n    window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos);\r\n    window->DC.Indent = group_data.BackupIndent;\r\n    window->DC.GroupOffset = group_data.BackupGroupOffset;\r\n    window->DC.CurrLineSize = group_data.BackupCurrLineSize;\r\n    window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset;\r\n    if (g.LogEnabled)\r\n        g.LogLinePosY = -FLT_MAX; // To enforce a carriage return\r\n\r\n    if (!group_data.EmitItem)\r\n    {\r\n        g.GroupStack.pop_back();\r\n        return;\r\n    }\r\n\r\n    window->DC.CurrLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset);      // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now.\r\n    ItemSize(group_bb.GetSize());\r\n    ItemAdd(group_bb, 0, NULL, ImGuiItemFlags_NoTabStop);\r\n\r\n    // If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group.\r\n    // It would be be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets.\r\n    // Also if you grep for LastItemId you'll notice it is only used in that context.\r\n    // (The two tests not the same because ActiveIdIsAlive is an ID itself, in order to be able to handle ActiveId being overwritten during the frame.)\r\n    const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId;\r\n    const bool group_contains_prev_active_id = (group_data.BackupActiveIdPreviousFrameIsAlive == false) && (g.ActiveIdPreviousFrameIsAlive == true);\r\n    if (group_contains_curr_active_id)\r\n        g.LastItemData.ID = g.ActiveId;\r\n    else if (group_contains_prev_active_id)\r\n        g.LastItemData.ID = g.ActiveIdPreviousFrame;\r\n    g.LastItemData.Rect = group_bb;\r\n\r\n    // Forward Hovered flag\r\n    const bool group_contains_curr_hovered_id = (group_data.BackupHoveredIdIsAlive == false) && g.HoveredId != 0;\r\n    if (group_contains_curr_hovered_id)\r\n        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;\r\n\r\n    // Forward Edited flag\r\n    if (group_contains_curr_active_id && g.ActiveIdHasBeenEditedThisFrame)\r\n        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;\r\n\r\n    // Forward Deactivated flag\r\n    g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDeactivated;\r\n    if (group_contains_prev_active_id && g.ActiveId != g.ActiveIdPreviousFrame)\r\n        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Deactivated;\r\n\r\n    g.GroupStack.pop_back();\r\n    //window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255));   // [Debug]\r\n}\r\n\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] SCROLLING\r\n//-----------------------------------------------------------------------------\r\n\r\n// Helper to snap on edges when aiming at an item very close to the edge,\r\n// So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling.\r\n// When we refactor the scrolling API this may be configurable with a flag?\r\n// Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default.\r\nstatic float CalcScrollEdgeSnap(float target, float snap_min, float snap_max, float snap_threshold, float center_ratio)\r\n{\r\n    if (target <= snap_min + snap_threshold)\r\n        return ImLerp(snap_min, target, center_ratio);\r\n    if (target >= snap_max - snap_threshold)\r\n        return ImLerp(target, snap_max, center_ratio);\r\n    return target;\r\n}\r\n\r\nstatic ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window)\r\n{\r\n    ImVec2 scroll = window->Scroll;\r\n    if (window->ScrollTarget.x < FLT_MAX)\r\n    {\r\n        float decoration_total_width = window->ScrollbarSizes.x;\r\n        float center_x_ratio = window->ScrollTargetCenterRatio.x;\r\n        float scroll_target_x = window->ScrollTarget.x;\r\n        if (window->ScrollTargetEdgeSnapDist.x > 0.0f)\r\n        {\r\n            float snap_x_min = 0.0f;\r\n            float snap_x_max = window->ScrollMax.x + window->SizeFull.x - decoration_total_width;\r\n            scroll_target_x = CalcScrollEdgeSnap(scroll_target_x, snap_x_min, snap_x_max, window->ScrollTargetEdgeSnapDist.x, center_x_ratio);\r\n        }\r\n        scroll.x = scroll_target_x - center_x_ratio * (window->SizeFull.x - decoration_total_width);\r\n    }\r\n    if (window->ScrollTarget.y < FLT_MAX)\r\n    {\r\n        float decoration_total_height = window->TitleBarHeight() + window->MenuBarHeight() + window->ScrollbarSizes.y;\r\n        float center_y_ratio = window->ScrollTargetCenterRatio.y;\r\n        float scroll_target_y = window->ScrollTarget.y;\r\n        if (window->ScrollTargetEdgeSnapDist.y > 0.0f)\r\n        {\r\n            float snap_y_min = 0.0f;\r\n            float snap_y_max = window->ScrollMax.y + window->SizeFull.y - decoration_total_height;\r\n            scroll_target_y = CalcScrollEdgeSnap(scroll_target_y, snap_y_min, snap_y_max, window->ScrollTargetEdgeSnapDist.y, center_y_ratio);\r\n        }\r\n        scroll.y = scroll_target_y - center_y_ratio * (window->SizeFull.y - decoration_total_height);\r\n    }\r\n    scroll.x = IM_FLOOR(ImMax(scroll.x, 0.0f));\r\n    scroll.y = IM_FLOOR(ImMax(scroll.y, 0.0f));\r\n    if (!window->Collapsed && !window->SkipItems)\r\n    {\r\n        scroll.x = ImMin(scroll.x, window->ScrollMax.x);\r\n        scroll.y = ImMin(scroll.y, window->ScrollMax.y);\r\n    }\r\n    return scroll;\r\n}\r\n\r\nvoid ImGui::ScrollToItem(ImGuiScrollFlags flags)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    ScrollToRectEx(window, g.LastItemData.NavRect, flags);\r\n}\r\n\r\nvoid ImGui::ScrollToRect(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)\r\n{\r\n    ScrollToRectEx(window, item_rect, flags);\r\n}\r\n\r\n// Scroll to keep newly navigated item fully into view\r\nImVec2 ImGui::ScrollToRectEx(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImRect window_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1));\r\n    //GetForegroundDrawList(window)->AddRect(window_rect.Min, window_rect.Max, IM_COL32_WHITE); // [DEBUG]\r\n\r\n    // Check that only one behavior is selected per axis\r\n    IM_ASSERT((flags & ImGuiScrollFlags_MaskX_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskX_));\r\n    IM_ASSERT((flags & ImGuiScrollFlags_MaskY_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskY_));\r\n\r\n    // Defaults\r\n    ImGuiScrollFlags in_flags = flags;\r\n    if ((flags & ImGuiScrollFlags_MaskX_) == 0 && window->ScrollbarX)\r\n        flags |= ImGuiScrollFlags_KeepVisibleEdgeX;\r\n    if ((flags & ImGuiScrollFlags_MaskY_) == 0)\r\n        flags |= window->Appearing ? ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeY;\r\n\r\n    const bool fully_visible_x = item_rect.Min.x >= window_rect.Min.x && item_rect.Max.x <= window_rect.Max.x;\r\n    const bool fully_visible_y = item_rect.Min.y >= window_rect.Min.y && item_rect.Max.y <= window_rect.Max.y;\r\n    const bool can_be_fully_visible_x = (item_rect.GetWidth() + g.Style.ItemSpacing.x * 2.0f) <= window_rect.GetWidth();\r\n    const bool can_be_fully_visible_y = (item_rect.GetHeight() + g.Style.ItemSpacing.y * 2.0f) <= window_rect.GetHeight();\r\n\r\n    if ((flags & ImGuiScrollFlags_KeepVisibleEdgeX) && !fully_visible_x)\r\n    {\r\n        if (item_rect.Min.x < window_rect.Min.x || !can_be_fully_visible_x)\r\n            SetScrollFromPosX(window, item_rect.Min.x - g.Style.ItemSpacing.x - window->Pos.x, 0.0f);\r\n        else if (item_rect.Max.x >= window_rect.Max.x)\r\n            SetScrollFromPosX(window, item_rect.Max.x + g.Style.ItemSpacing.x - window->Pos.x, 1.0f);\r\n    }\r\n    else if (((flags & ImGuiScrollFlags_KeepVisibleCenterX) && !fully_visible_x) || (flags & ImGuiScrollFlags_AlwaysCenterX))\r\n    {\r\n        float target_x = can_be_fully_visible_x ? ImFloor((item_rect.Min.x + item_rect.Max.x - window->InnerRect.GetWidth()) * 0.5f) : item_rect.Min.x;\r\n        SetScrollFromPosX(window, target_x - window->Pos.x, 0.0f);\r\n    }\r\n\r\n    if ((flags & ImGuiScrollFlags_KeepVisibleEdgeY) && !fully_visible_y)\r\n    {\r\n        if (item_rect.Min.y < window_rect.Min.y || !can_be_fully_visible_y)\r\n            SetScrollFromPosY(window, item_rect.Min.y - g.Style.ItemSpacing.y - window->Pos.y, 0.0f);\r\n        else if (item_rect.Max.y >= window_rect.Max.y)\r\n            SetScrollFromPosY(window, item_rect.Max.y + g.Style.ItemSpacing.y - window->Pos.y, 1.0f);\r\n    }\r\n    else if (((flags & ImGuiScrollFlags_KeepVisibleCenterY) && !fully_visible_y) || (flags & ImGuiScrollFlags_AlwaysCenterY))\r\n    {\r\n        float target_y = can_be_fully_visible_y ? ImFloor((item_rect.Min.y + item_rect.Max.y - window->InnerRect.GetHeight()) * 0.5f) : item_rect.Min.y;\r\n        SetScrollFromPosY(window, target_y - window->Pos.y, 0.0f);\r\n    }\r\n\r\n    ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);\r\n    ImVec2 delta_scroll = next_scroll - window->Scroll;\r\n\r\n    // Also scroll parent window to keep us into view if necessary\r\n    if (!(flags & ImGuiScrollFlags_NoScrollParent) && (window->Flags & ImGuiWindowFlags_ChildWindow))\r\n    {\r\n        // FIXME-SCROLL: May be an option?\r\n        if ((in_flags & (ImGuiScrollFlags_AlwaysCenterX | ImGuiScrollFlags_KeepVisibleCenterX)) != 0)\r\n            in_flags = (in_flags & ~ImGuiScrollFlags_MaskX_) | ImGuiScrollFlags_KeepVisibleEdgeX;\r\n        if ((in_flags & (ImGuiScrollFlags_AlwaysCenterY | ImGuiScrollFlags_KeepVisibleCenterY)) != 0)\r\n            in_flags = (in_flags & ~ImGuiScrollFlags_MaskY_) | ImGuiScrollFlags_KeepVisibleEdgeY;\r\n        delta_scroll += ScrollToRectEx(window->ParentWindow, ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll), in_flags);\r\n    }\r\n\r\n    return delta_scroll;\r\n}\r\n\r\nfloat ImGui::GetScrollX()\r\n{\r\n    ImGuiWindow* window = GImGui->CurrentWindow;\r\n    return window->Scroll.x;\r\n}\r\n\r\nfloat ImGui::GetScrollY()\r\n{\r\n    ImGuiWindow* window = GImGui->CurrentWindow;\r\n    return window->Scroll.y;\r\n}\r\n\r\nfloat ImGui::GetScrollMaxX()\r\n{\r\n    ImGuiWindow* window = GImGui->CurrentWindow;\r\n    return window->ScrollMax.x;\r\n}\r\n\r\nfloat ImGui::GetScrollMaxY()\r\n{\r\n    ImGuiWindow* window = GImGui->CurrentWindow;\r\n    return window->ScrollMax.y;\r\n}\r\n\r\nvoid ImGui::SetScrollX(ImGuiWindow* window, float scroll_x)\r\n{\r\n    window->ScrollTarget.x = scroll_x;\r\n    window->ScrollTargetCenterRatio.x = 0.0f;\r\n    window->ScrollTargetEdgeSnapDist.x = 0.0f;\r\n}\r\n\r\nvoid ImGui::SetScrollY(ImGuiWindow* window, float scroll_y)\r\n{\r\n    window->ScrollTarget.y = scroll_y;\r\n    window->ScrollTargetCenterRatio.y = 0.0f;\r\n    window->ScrollTargetEdgeSnapDist.y = 0.0f;\r\n}\r\n\r\nvoid ImGui::SetScrollX(float scroll_x)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    SetScrollX(g.CurrentWindow, scroll_x);\r\n}\r\n\r\nvoid ImGui::SetScrollY(float scroll_y)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    SetScrollY(g.CurrentWindow, scroll_y);\r\n}\r\n\r\n// Note that a local position will vary depending on initial scroll value,\r\n// This is a little bit confusing so bear with us:\r\n//  - local_pos = (absolution_pos - window->Pos)\r\n//  - So local_x/local_y are 0.0f for a position at the upper-left corner of a window,\r\n//    and generally local_x/local_y are >(padding+decoration) && <(size-padding-decoration) when in the visible area.\r\n//  - They mostly exists because of legacy API.\r\n// Following the rules above, when trying to work with scrolling code, consider that:\r\n//  - SetScrollFromPosY(0.0f) == SetScrollY(0.0f + scroll.y) == has no effect!\r\n//  - SetScrollFromPosY(-scroll.y) == SetScrollY(-scroll.y + scroll.y) == SetScrollY(0.0f) == reset scroll. Of course writing SetScrollY(0.0f) directly then makes more sense\r\n// We store a target position so centering and clamping can occur on the next frame when we are guaranteed to have a known window size\r\nvoid ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio)\r\n{\r\n    IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f);\r\n    window->ScrollTarget.x = IM_FLOOR(local_x + window->Scroll.x); // Convert local position to scroll offset\r\n    window->ScrollTargetCenterRatio.x = center_x_ratio;\r\n    window->ScrollTargetEdgeSnapDist.x = 0.0f;\r\n}\r\n\r\nvoid ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio)\r\n{\r\n    IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);\r\n    const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight(); // FIXME: Would be nice to have a more standardized access to our scrollable/client rect;\r\n    local_y -= decoration_up_height;\r\n    window->ScrollTarget.y = IM_FLOOR(local_y + window->Scroll.y); // Convert local position to scroll offset\r\n    window->ScrollTargetCenterRatio.y = center_y_ratio;\r\n    window->ScrollTargetEdgeSnapDist.y = 0.0f;\r\n}\r\n\r\nvoid ImGui::SetScrollFromPosX(float local_x, float center_x_ratio)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    SetScrollFromPosX(g.CurrentWindow, local_x, center_x_ratio);\r\n}\r\n\r\nvoid ImGui::SetScrollFromPosY(float local_y, float center_y_ratio)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    SetScrollFromPosY(g.CurrentWindow, local_y, center_y_ratio);\r\n}\r\n\r\n// center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item.\r\nvoid ImGui::SetScrollHereX(float center_x_ratio)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    float spacing_x = ImMax(window->WindowPadding.x, g.Style.ItemSpacing.x);\r\n    float target_pos_x = ImLerp(g.LastItemData.Rect.Min.x - spacing_x, g.LastItemData.Rect.Max.x + spacing_x, center_x_ratio);\r\n    SetScrollFromPosX(window, target_pos_x - window->Pos.x, center_x_ratio); // Convert from absolute to local pos\r\n\r\n    // Tweak: snap on edges when aiming at an item very close to the edge\r\n    window->ScrollTargetEdgeSnapDist.x = ImMax(0.0f, window->WindowPadding.x - spacing_x);\r\n}\r\n\r\n// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.\r\nvoid ImGui::SetScrollHereY(float center_y_ratio)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    float spacing_y = ImMax(window->WindowPadding.y, g.Style.ItemSpacing.y);\r\n    float target_pos_y = ImLerp(window->DC.CursorPosPrevLine.y - spacing_y, window->DC.CursorPosPrevLine.y + window->DC.PrevLineSize.y + spacing_y, center_y_ratio);\r\n    SetScrollFromPosY(window, target_pos_y - window->Pos.y, center_y_ratio); // Convert from absolute to local pos\r\n\r\n    // Tweak: snap on edges when aiming at an item very close to the edge\r\n    window->ScrollTargetEdgeSnapDist.y = ImMax(0.0f, window->WindowPadding.y - spacing_y);\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] TOOLTIPS\r\n//-----------------------------------------------------------------------------\r\n\r\nvoid ImGui::BeginTooltip()\r\n{\r\n    BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);\r\n}\r\n\r\nvoid ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags extra_window_flags)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n\r\n    if (g.DragDropWithinSource || g.DragDropWithinTarget)\r\n    {\r\n        // The default tooltip position is a little offset to give space to see the context menu (it's also clamped within the current viewport/monitor)\r\n        // In the context of a dragging tooltip we try to reduce that offset and we enforce following the cursor.\r\n        // Whatever we do we want to call SetNextWindowPos() to enforce a tooltip position and disable clipping the tooltip without our display area, like regular tooltip do.\r\n        //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;\r\n        ImVec2 tooltip_pos = g.IO.MousePos + ImVec2(16 * g.Style.MouseCursorScale, 8 * g.Style.MouseCursorScale);\r\n        SetNextWindowPos(tooltip_pos);\r\n        SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);\r\n        //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(\r\n        tooltip_flags |= ImGuiTooltipFlags_OverridePreviousTooltip;\r\n    }\r\n\r\n    char window_name[16];\r\n    ImFormatString(window_name, IM_ARRAYSIZE(window_name), \"##Tooltip_%02d\", g.TooltipOverrideCount);\r\n    if (tooltip_flags & ImGuiTooltipFlags_OverridePreviousTooltip)\r\n        if (ImGuiWindow* window = FindWindowByName(window_name))\r\n            if (window->Active)\r\n            {\r\n                // Hide previous tooltip from being displayed. We can't easily \"reset\" the content of a window so we create a new one.\r\n                window->Hidden = true;\r\n                window->HiddenFramesCanSkipItems = 1; // FIXME: This may not be necessary?\r\n                ImFormatString(window_name, IM_ARRAYSIZE(window_name), \"##Tooltip_%02d\", ++g.TooltipOverrideCount);\r\n            }\r\n    ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize;\r\n    Begin(window_name, NULL, flags | extra_window_flags);\r\n}\r\n\r\nvoid ImGui::EndTooltip()\r\n{\r\n    IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip);   // Mismatched BeginTooltip()/EndTooltip() calls\r\n    End();\r\n}\r\n\r\nvoid ImGui::SetTooltipV(const char* fmt, va_list args)\r\n{\r\n    BeginTooltipEx(ImGuiTooltipFlags_OverridePreviousTooltip, ImGuiWindowFlags_None);\r\n    TextV(fmt, args);\r\n    EndTooltip();\r\n}\r\n\r\nvoid ImGui::SetTooltip(const char* fmt, ...)\r\n{\r\n    va_list args;\r\n    va_start(args, fmt);\r\n    SetTooltipV(fmt, args);\r\n    va_end(args);\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] POPUPS\r\n//-----------------------------------------------------------------------------\r\n\r\n// Supported flags: ImGuiPopupFlags_AnyPopupId, ImGuiPopupFlags_AnyPopupLevel\r\nbool ImGui::IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    if (popup_flags & ImGuiPopupFlags_AnyPopupId)\r\n    {\r\n        // Return true if any popup is open at the current BeginPopup() level of the popup stack\r\n        // This may be used to e.g. test for another popups already opened to handle popups priorities at the same level.\r\n        IM_ASSERT(id == 0);\r\n        if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)\r\n            return g.OpenPopupStack.Size > 0;\r\n        else\r\n            return g.OpenPopupStack.Size > g.BeginPopupStack.Size;\r\n    }\r\n    else\r\n    {\r\n        if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)\r\n        {\r\n            // Return true if the popup is open anywhere in the popup stack\r\n            for (int n = 0; n < g.OpenPopupStack.Size; n++)\r\n                if (g.OpenPopupStack[n].PopupId == id)\r\n                    return true;\r\n            return false;\r\n        }\r\n        else\r\n        {\r\n            // Return true if the popup is open at the current BeginPopup() level of the popup stack (this is the most-common query)\r\n            return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;\r\n        }\r\n    }\r\n}\r\n\r\nbool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiID id = (popup_flags & ImGuiPopupFlags_AnyPopupId) ? 0 : g.CurrentWindow->GetID(str_id);\r\n    if ((popup_flags & ImGuiPopupFlags_AnyPopupLevel) && id != 0)\r\n        IM_ASSERT(0 && \"Cannot use IsPopupOpen() with a string id and ImGuiPopupFlags_AnyPopupLevel.\"); // But non-string version is legal and used internally\r\n    return IsPopupOpen(id, popup_flags);\r\n}\r\n\r\nImGuiWindow* ImGui::GetTopMostPopupModal()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)\r\n        if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)\r\n            if (popup->Flags & ImGuiWindowFlags_Modal)\r\n                return popup;\r\n    return NULL;\r\n}\r\n\r\nImGuiWindow* ImGui::GetTopMostAndVisiblePopupModal()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)\r\n        if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)\r\n            if ((popup->Flags & ImGuiWindowFlags_Modal) && IsWindowActiveAndVisible(popup))\r\n                return popup;\r\n    return NULL;\r\n}\r\n\r\nvoid ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    OpenPopupEx(g.CurrentWindow->GetID(str_id), popup_flags);\r\n}\r\n\r\nvoid ImGui::OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags)\r\n{\r\n    OpenPopupEx(id, popup_flags);\r\n}\r\n\r\n// Mark popup as open (toggle toward open state).\r\n// Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.\r\n// Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).\r\n// One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)\r\nvoid ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* parent_window = g.CurrentWindow;\r\n    const int current_stack_size = g.BeginPopupStack.Size;\r\n\r\n    if (popup_flags & ImGuiPopupFlags_NoOpenOverExistingPopup)\r\n        if (IsPopupOpen(0u, ImGuiPopupFlags_AnyPopupId))\r\n            return;\r\n\r\n    ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.\r\n    popup_ref.PopupId = id;\r\n    popup_ref.Window = NULL;\r\n    popup_ref.SourceWindow = g.NavWindow;\r\n    popup_ref.OpenFrameCount = g.FrameCount;\r\n    popup_ref.OpenParentId = parent_window->IDStack.back();\r\n    popup_ref.OpenPopupPos = NavCalcPreferredRefPos();\r\n    popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;\r\n\r\n    IMGUI_DEBUG_LOG_POPUP(\"OpenPopupEx(0x%08X)\\n\", id);\r\n    if (g.OpenPopupStack.Size < current_stack_size + 1)\r\n    {\r\n        g.OpenPopupStack.push_back(popup_ref);\r\n    }\r\n    else\r\n    {\r\n        // Gently handle the user mistakenly calling OpenPopup() every frame. It is a programming mistake! However, if we were to run the regular code path, the ui\r\n        // would become completely unusable because the popup will always be in hidden-while-calculating-size state _while_ claiming focus. Which would be a very confusing\r\n        // situation for the programmer. Instead, we silently allow the popup to proceed, it will keep reappearing and the programming error will be more obvious to understand.\r\n        if (g.OpenPopupStack[current_stack_size].PopupId == id && g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1)\r\n        {\r\n            g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;\r\n        }\r\n        else\r\n        {\r\n            // Close child popups if any, then flag popup for open/reopen\r\n            ClosePopupToLevel(current_stack_size, false);\r\n            g.OpenPopupStack.push_back(popup_ref);\r\n        }\r\n\r\n        // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().\r\n        // This is equivalent to what ClosePopupToLevel() does.\r\n        //if (g.OpenPopupStack[current_stack_size].PopupId == id)\r\n        //    FocusWindow(parent_window);\r\n    }\r\n}\r\n\r\n// When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.\r\n// This function closes any popups that are over 'ref_window'.\r\nvoid ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    if (g.OpenPopupStack.Size == 0)\r\n        return;\r\n\r\n    // Don't close our own child popup windows.\r\n    int popup_count_to_keep = 0;\r\n    if (ref_window)\r\n    {\r\n        // Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)\r\n        for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++)\r\n        {\r\n            ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep];\r\n            if (!popup.Window)\r\n                continue;\r\n            IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);\r\n            if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow)\r\n                continue;\r\n\r\n            // Trim the stack unless the popup is a direct parent of the reference window (the reference window is often the NavWindow)\r\n            // - With this stack of window, clicking/focusing Popup1 will close Popup2 and Popup3:\r\n            //     Window -> Popup1 -> Popup2 -> Popup3\r\n            // - Each popups may contain child windows, which is why we compare ->RootWindow!\r\n            //     Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child\r\n            bool ref_window_is_descendent_of_popup = false;\r\n            for (int n = popup_count_to_keep; n < g.OpenPopupStack.Size; n++)\r\n                if (ImGuiWindow* popup_window = g.OpenPopupStack[n].Window)\r\n                    if (IsWindowWithinBeginStackOf(ref_window, popup_window))\r\n                    {\r\n                        ref_window_is_descendent_of_popup = true;\r\n                        break;\r\n                    }\r\n            if (!ref_window_is_descendent_of_popup)\r\n                break;\r\n        }\r\n    }\r\n    if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below\r\n    {\r\n        IMGUI_DEBUG_LOG_POPUP(\"ClosePopupsOverWindow(\\\"%s\\\") -> ClosePopupToLevel(%d)\\n\", ref_window->Name, popup_count_to_keep);\r\n        ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup);\r\n    }\r\n}\r\n\r\nvoid ImGui::ClosePopupsExceptModals()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n\r\n    int popup_count_to_keep;\r\n    for (popup_count_to_keep = g.OpenPopupStack.Size; popup_count_to_keep > 0; popup_count_to_keep--)\r\n    {\r\n        ImGuiWindow* window = g.OpenPopupStack[popup_count_to_keep - 1].Window;\r\n        if (!window || window->Flags & ImGuiWindowFlags_Modal)\r\n            break;\r\n    }\r\n    if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below\r\n        ClosePopupToLevel(popup_count_to_keep, true);\r\n}\r\n\r\nvoid ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    IMGUI_DEBUG_LOG_POPUP(\"ClosePopupToLevel(%d), restore_focus_to_window_under_popup=%d\\n\", remaining, restore_focus_to_window_under_popup);\r\n    IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size);\r\n\r\n    // Trim open popup stack\r\n    ImGuiWindow* focus_window = g.OpenPopupStack[remaining].SourceWindow;\r\n    ImGuiWindow* popup_window = g.OpenPopupStack[remaining].Window;\r\n    g.OpenPopupStack.resize(remaining);\r\n\r\n    if (restore_focus_to_window_under_popup)\r\n    {\r\n        if (focus_window && !focus_window->WasActive && popup_window)\r\n        {\r\n            // Fallback\r\n            FocusTopMostWindowUnderOne(popup_window, NULL);\r\n        }\r\n        else\r\n        {\r\n            if (g.NavLayer == ImGuiNavLayer_Main && focus_window)\r\n                focus_window = NavRestoreLastChildNavWindow(focus_window);\r\n            FocusWindow(focus_window);\r\n        }\r\n    }\r\n}\r\n\r\n// Close the popup we have begin-ed into.\r\nvoid ImGui::CloseCurrentPopup()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    int popup_idx = g.BeginPopupStack.Size - 1;\r\n    if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)\r\n        return;\r\n\r\n    // Closing a menu closes its top-most parent popup (unless a modal)\r\n    while (popup_idx > 0)\r\n    {\r\n        ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window;\r\n        ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window;\r\n        bool close_parent = false;\r\n        if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu))\r\n            if (parent_popup_window && !(parent_popup_window->Flags & ImGuiWindowFlags_MenuBar))\r\n                close_parent = true;\r\n        if (!close_parent)\r\n            break;\r\n        popup_idx--;\r\n    }\r\n    IMGUI_DEBUG_LOG_POPUP(\"CloseCurrentPopup %d -> %d\\n\", g.BeginPopupStack.Size - 1, popup_idx);\r\n    ClosePopupToLevel(popup_idx, true);\r\n\r\n    // A common pattern is to close a popup when selecting a menu item/selectable that will open another window.\r\n    // To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.\r\n    // Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.\r\n    if (ImGuiWindow* window = g.NavWindow)\r\n        window->DC.NavHideHighlightOneFrame = true;\r\n}\r\n\r\n// Attention! BeginPopup() adds default flags which BeginPopupEx()!\r\nbool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags flags)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    if (!IsPopupOpen(id, ImGuiPopupFlags_None))\r\n    {\r\n        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values\r\n        return false;\r\n    }\r\n\r\n    char name[20];\r\n    if (flags & ImGuiWindowFlags_ChildMenu)\r\n        ImFormatString(name, IM_ARRAYSIZE(name), \"##Menu_%02d\", g.BeginMenuCount); // Recycle windows based on depth\r\n    else\r\n        ImFormatString(name, IM_ARRAYSIZE(name), \"##Popup_%08x\", id); // Not recycling, so we can close/open during the same frame\r\n\r\n    flags |= ImGuiWindowFlags_Popup;\r\n    bool is_open = Begin(name, NULL, flags);\r\n    if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)\r\n        EndPopup();\r\n\r\n    return is_open;\r\n}\r\n\r\nbool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance\r\n    {\r\n        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values\r\n        return false;\r\n    }\r\n    flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings;\r\n    ImGuiID id = g.CurrentWindow->GetID(str_id);\r\n    return BeginPopupEx(id, flags);\r\n}\r\n\r\n// If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup.\r\n// Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup) so the actual value of *p_open is meaningless here.\r\nbool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    const ImGuiID id = window->GetID(name);\r\n    if (!IsPopupOpen(id, ImGuiPopupFlags_None))\r\n    {\r\n        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values\r\n        return false;\r\n    }\r\n\r\n    // Center modal windows by default for increased visibility\r\n    // (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves)\r\n    // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.\r\n    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0)\r\n    {\r\n        const ImGuiViewport* viewport = GetMainViewport();\r\n        SetNextWindowPos(viewport->GetCenter(), ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f));\r\n    }\r\n\r\n    flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse;\r\n    const bool is_open = Begin(name, p_open, flags);\r\n    if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)\r\n    {\r\n        EndPopup();\r\n        if (is_open)\r\n            ClosePopupToLevel(g.BeginPopupStack.Size, true);\r\n        return false;\r\n    }\r\n    return is_open;\r\n}\r\n\r\nvoid ImGui::EndPopup()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup);  // Mismatched BeginPopup()/EndPopup() calls\r\n    IM_ASSERT(g.BeginPopupStack.Size > 0);\r\n\r\n    // Make all menus and popups wrap around for now, may need to expose that policy (e.g. focus scope could include wrap/loop policy flags used by new move requests)\r\n    if (g.NavWindow == window)\r\n        NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY);\r\n\r\n    // Child-popups don't need to be laid out\r\n    IM_ASSERT(g.WithinEndChild == false);\r\n    if (window->Flags & ImGuiWindowFlags_ChildWindow)\r\n        g.WithinEndChild = true;\r\n    End();\r\n    g.WithinEndChild = false;\r\n}\r\n\r\n// Helper to open a popup if mouse button is released over the item\r\n// - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup()\r\nvoid ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);\r\n    if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))\r\n    {\r\n        ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID;    // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!\r\n        IM_ASSERT(id != 0);                                             // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)\r\n        OpenPopupEx(id, popup_flags);\r\n    }\r\n}\r\n\r\n// This is a helper to handle the simplest case of associating one named popup to one given widget.\r\n// - To create a popup associated to the last item, you generally want to pass a NULL value to str_id.\r\n// - To create a popup with a specific identifier, pass it in str_id.\r\n//    - This is useful when using using BeginPopupContextItem() on an item which doesn't have an identifier, e.g. a Text() call.\r\n//    - This is useful when multiple code locations may want to manipulate/open the same popup, given an explicit id.\r\n// - You may want to handle the whole on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).\r\n//   This is essentially the same as:\r\n//       id = str_id ? GetID(str_id) : GetItemID();\r\n//       OpenPopupOnItemClick(str_id, ImGuiPopupFlags_MouseButtonRight);\r\n//       return BeginPopup(id);\r\n//   Which is essentially the same as:\r\n//       id = str_id ? GetID(str_id) : GetItemID();\r\n//       if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right))\r\n//           OpenPopup(id);\r\n//       return BeginPopup(id);\r\n//   The main difference being that this is tweaked to avoid computing the ID twice.\r\nbool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    if (window->SkipItems)\r\n        return false;\r\n    ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID;    // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!\r\n    IM_ASSERT(id != 0);                                             // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)\r\n    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);\r\n    if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))\r\n        OpenPopupEx(id, popup_flags);\r\n    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);\r\n}\r\n\r\nbool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    if (!str_id)\r\n        str_id = \"window_context\";\r\n    ImGuiID id = window->GetID(str_id);\r\n    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);\r\n    if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))\r\n        if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered())\r\n            OpenPopupEx(id, popup_flags);\r\n    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);\r\n}\r\n\r\nbool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    if (!str_id)\r\n        str_id = \"void_context\";\r\n    ImGuiID id = window->GetID(str_id);\r\n    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);\r\n    if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))\r\n        if (GetTopMostPopupModal() == NULL)\r\n            OpenPopupEx(id, popup_flags);\r\n    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);\r\n}\r\n\r\n// r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.)\r\n// r_outer = the visible area rectangle, minus safe area padding. If our popup size won't fit because of safe area padding we ignore it.\r\n// (r_outer is usually equivalent to the viewport rectangle minus padding, but when multi-viewports are enabled and monitor\r\n//  information are available, it may represent the entire platform monitor from the frame of reference of the current viewport.\r\n//  this allows us to have tooltips/popups displayed out of the parent viewport.)\r\nImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)\r\n{\r\n    ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);\r\n    //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));\r\n    //GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));\r\n\r\n    // Combo Box policy (we want a connecting edge)\r\n    if (policy == ImGuiPopupPositionPolicy_ComboBox)\r\n    {\r\n        const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };\r\n        for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)\r\n        {\r\n            const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];\r\n            if (n != -1 && dir == *last_dir) // Already tried this direction?\r\n                continue;\r\n            ImVec2 pos;\r\n            if (dir == ImGuiDir_Down)  pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y);          // Below, Toward Right (default)\r\n            if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right\r\n            if (dir == ImGuiDir_Left)  pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left\r\n            if (dir == ImGuiDir_Up)    pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left\r\n            if (!r_outer.Contains(ImRect(pos, pos + size)))\r\n                continue;\r\n            *last_dir = dir;\r\n            return pos;\r\n        }\r\n    }\r\n\r\n    // Tooltip and Default popup policy\r\n    // (Always first try the direction we used on the last frame, if any)\r\n    if (policy == ImGuiPopupPositionPolicy_Tooltip || policy == ImGuiPopupPositionPolicy_Default)\r\n    {\r\n        const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };\r\n        for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)\r\n        {\r\n            const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];\r\n            if (n != -1 && dir == *last_dir) // Already tried this direction?\r\n                continue;\r\n\r\n            const float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x);\r\n            const float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y);\r\n\r\n            // If there not enough room on one axis, there's no point in positioning on a side on this axis (e.g. when not enough width, use a top/bottom position to maximize available width)\r\n            if (avail_w < size.x && (dir == ImGuiDir_Left || dir == ImGuiDir_Right))\r\n                continue;\r\n            if (avail_h < size.y && (dir == ImGuiDir_Up || dir == ImGuiDir_Down))\r\n                continue;\r\n\r\n            ImVec2 pos;\r\n            pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;\r\n            pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;\r\n\r\n            // Clamp top-left corner of popup\r\n            pos.x = ImMax(pos.x, r_outer.Min.x);\r\n            pos.y = ImMax(pos.y, r_outer.Min.y);\r\n\r\n            *last_dir = dir;\r\n            return pos;\r\n        }\r\n    }\r\n\r\n    // Fallback when not enough room:\r\n    *last_dir = ImGuiDir_None;\r\n\r\n    // For tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.\r\n    if (policy == ImGuiPopupPositionPolicy_Tooltip)\r\n        return ref_pos + ImVec2(2, 2);\r\n\r\n    // Otherwise try to keep within display\r\n    ImVec2 pos = ref_pos;\r\n    pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);\r\n    pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);\r\n    return pos;\r\n}\r\n\r\n// Note that this is used for popups, which can overlap the non work-area of individual viewports.\r\nImRect ImGui::GetPopupAllowedExtentRect(ImGuiWindow* window)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    IM_UNUSED(window);\r\n    ImRect r_screen = ((ImGuiViewportP*)(void*)GetMainViewport())->GetMainRect();\r\n    ImVec2 padding = g.Style.DisplaySafeAreaPadding;\r\n    r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));\r\n    return r_screen;\r\n}\r\n\r\nImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n\r\n    ImRect r_outer = GetPopupAllowedExtentRect(window);\r\n    if (window->Flags & ImGuiWindowFlags_ChildMenu)\r\n    {\r\n        // Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds.\r\n        // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.\r\n        IM_ASSERT(g.CurrentWindow == window);\r\n        ImGuiWindow* parent_window = g.CurrentWindowStack[g.CurrentWindowStack.Size - 2].Window;\r\n        float horizontal_overlap = g.Style.ItemInnerSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x).\r\n        ImRect r_avoid;\r\n        if (parent_window->DC.MenuBarAppending)\r\n            r_avoid = ImRect(-FLT_MAX, parent_window->ClipRect.Min.y, FLT_MAX, parent_window->ClipRect.Max.y); // Avoid parent menu-bar. If we wanted multi-line menu-bar, we may instead want to have the calling window setup e.g. a NextWindowData.PosConstraintAvoidRect field\r\n        else\r\n            r_avoid = ImRect(parent_window->Pos.x + horizontal_overlap, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - horizontal_overlap - parent_window->ScrollbarSizes.x, FLT_MAX);\r\n        return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Default);\r\n    }\r\n    if (window->Flags & ImGuiWindowFlags_Popup)\r\n    {\r\n        return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, ImRect(window->Pos, window->Pos), ImGuiPopupPositionPolicy_Default); // Ideally we'd disable r_avoid here\r\n    }\r\n    if (window->Flags & ImGuiWindowFlags_Tooltip)\r\n    {\r\n        // Position tooltip (always follows mouse)\r\n        float sc = g.Style.MouseCursorScale;\r\n        ImVec2 ref_pos = NavCalcPreferredRefPos();\r\n        ImRect r_avoid;\r\n        if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos))\r\n            r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);\r\n        else\r\n            r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * sc, ref_pos.y + 24 * sc); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important.\r\n        return FindBestWindowPosForPopupEx(ref_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Tooltip);\r\n    }\r\n    IM_ASSERT(0);\r\n    return window->Pos;\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] KEYBOARD/GAMEPAD NAVIGATION\r\n//-----------------------------------------------------------------------------\r\n\r\n// FIXME-NAV: The existence of SetNavID vs SetFocusID properly needs to be clarified/reworked.\r\n// In our terminology those should be interchangeable. Those two functions are merely a legacy artifact, so at minimum naming should be clarified.\r\nvoid ImGui::SetNavID(ImGuiID id, ImGuiNavLayer nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(g.NavWindow != NULL);\r\n    IM_ASSERT(nav_layer == ImGuiNavLayer_Main || nav_layer == ImGuiNavLayer_Menu);\r\n    g.NavId = id;\r\n    g.NavLayer = nav_layer;\r\n    g.NavFocusScopeId = focus_scope_id;\r\n    g.NavWindow->NavLastIds[nav_layer] = id;\r\n    g.NavWindow->NavRectRel[nav_layer] = rect_rel;\r\n}\r\n\r\nvoid ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(id != 0);\r\n\r\n    // Assume that SetFocusID() is called in the context where its window->DC.NavLayerCurrent and window->DC.NavFocusScopeIdCurrent are valid.\r\n    // Note that window may be != g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text)\r\n    const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;\r\n    if (g.NavWindow != window)\r\n        g.NavInitRequest = false;\r\n    g.NavWindow = window;\r\n    g.NavId = id;\r\n    g.NavLayer = nav_layer;\r\n    g.NavFocusScopeId = window->DC.NavFocusScopeIdCurrent;\r\n    window->NavLastIds[nav_layer] = id;\r\n    if (g.LastItemData.ID == id)\r\n        window->NavRectRel[nav_layer] = WindowRectAbsToRel(window, g.LastItemData.NavRect);\r\n\r\n    if (g.ActiveIdSource == ImGuiInputSource_Nav)\r\n        g.NavDisableMouseHover = true;\r\n    else\r\n        g.NavDisableHighlight = true;\r\n}\r\n\r\nImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)\r\n{\r\n    if (ImFabs(dx) > ImFabs(dy))\r\n        return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;\r\n    return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;\r\n}\r\n\r\nstatic float inline NavScoreItemDistInterval(float a0, float a1, float b0, float b1)\r\n{\r\n    if (a1 < b0)\r\n        return a1 - b0;\r\n    if (b1 < a0)\r\n        return a0 - b1;\r\n    return 0.0f;\r\n}\r\n\r\nstatic void inline NavClampRectToVisibleAreaForMoveDir(ImGuiDir move_dir, ImRect& r, const ImRect& clip_rect)\r\n{\r\n    if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)\r\n    {\r\n        r.Min.y = ImClamp(r.Min.y, clip_rect.Min.y, clip_rect.Max.y);\r\n        r.Max.y = ImClamp(r.Max.y, clip_rect.Min.y, clip_rect.Max.y);\r\n    }\r\n    else // FIXME: PageUp/PageDown are leaving move_dir == None\r\n    {\r\n        r.Min.x = ImClamp(r.Min.x, clip_rect.Min.x, clip_rect.Max.x);\r\n        r.Max.x = ImClamp(r.Max.x, clip_rect.Min.x, clip_rect.Max.x);\r\n    }\r\n}\r\n\r\n// Scoring function for gamepad/keyboard directional navigation. Based on https://gist.github.com/rygorous/6981057\r\nstatic bool ImGui::NavScoreItem(ImGuiNavItemData* result)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    if (g.NavLayer != window->DC.NavLayerCurrent)\r\n        return false;\r\n\r\n    // FIXME: Those are not good variables names\r\n    ImRect cand = g.LastItemData.NavRect;   // Current item nav rectangle\r\n    const ImRect curr = g.NavScoringRect;   // Current modified source rect (NB: we've applied Max.x = Min.x in NavUpdate() to inhibit the effect of having varied item width)\r\n    g.NavScoringDebugCount++;\r\n\r\n    // When entering through a NavFlattened border, we consider child window items as fully clipped for scoring\r\n    if (window->ParentWindow == g.NavWindow)\r\n    {\r\n        IM_ASSERT((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened);\r\n        if (!window->ClipRect.Overlaps(cand))\r\n            return false;\r\n        cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window\r\n    }\r\n\r\n    // We perform scoring on items bounding box clipped by the current clipping rectangle on the other axis (clipping on our movement axis would give us equal scores for all clipped items)\r\n    // For example, this ensure that items in one column are not reached when moving vertically from items in another column.\r\n    NavClampRectToVisibleAreaForMoveDir(g.NavMoveClipDir, cand, window->ClipRect);\r\n\r\n    // Compute distance between boxes\r\n    // FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.\r\n    float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x);\r\n    float dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2f), ImLerp(cand.Min.y, cand.Max.y, 0.8f), ImLerp(curr.Min.y, curr.Max.y, 0.2f), ImLerp(curr.Min.y, curr.Max.y, 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items\r\n    if (dby != 0.0f && dbx != 0.0f)\r\n        dbx = (dbx / 1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);\r\n    float dist_box = ImFabs(dbx) + ImFabs(dby);\r\n\r\n    // Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter)\r\n    float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);\r\n    float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);\r\n    float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee)\r\n\r\n    // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance\r\n    ImGuiDir quadrant;\r\n    float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;\r\n    if (dbx != 0.0f || dby != 0.0f)\r\n    {\r\n        // For non-overlapping boxes, use distance between boxes\r\n        dax = dbx;\r\n        day = dby;\r\n        dist_axial = dist_box;\r\n        quadrant = ImGetDirQuadrantFromDelta(dbx, dby);\r\n    }\r\n    else if (dcx != 0.0f || dcy != 0.0f)\r\n    {\r\n        // For overlapping boxes with different centers, use distance between centers\r\n        dax = dcx;\r\n        day = dcy;\r\n        dist_axial = dist_center;\r\n        quadrant = ImGetDirQuadrantFromDelta(dcx, dcy);\r\n    }\r\n    else\r\n    {\r\n        // Degenerate case: two overlapping buttons with same center, break ties arbitrarily (note that LastItemId here is really the _previous_ item order, but it doesn't matter)\r\n        quadrant = (g.LastItemData.ID < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;\r\n    }\r\n\r\n#if IMGUI_DEBUG_NAV_SCORING\r\n    char buf[128];\r\n    if (IsMouseHoveringRect(cand.Min, cand.Max))\r\n    {\r\n        ImFormatString(buf, IM_ARRAYSIZE(buf), \"dbox (%.2f,%.2f->%.4f)\\ndcen (%.2f,%.2f->%.4f)\\nd (%.2f,%.2f->%.4f)\\nnav %c, quadrant %c\", dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, \"WENS\"[g.NavMoveDir], \"WENS\"[quadrant]);\r\n        ImDrawList* draw_list = GetForegroundDrawList(window);\r\n        draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255,200,0,100));\r\n        draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255,255,0,200));\r\n        draw_list->AddRectFilled(cand.Max - ImVec2(4, 4), cand.Max + CalcTextSize(buf) + ImVec2(4, 4), IM_COL32(40,0,0,150));\r\n        draw_list->AddText(cand.Max, ~0U, buf);\r\n    }\r\n    else if (g.IO.KeyCtrl) // Hold to preview score in matching quadrant. Press C to rotate.\r\n    {\r\n        if (quadrant == g.NavMoveDir)\r\n        {\r\n            ImFormatString(buf, IM_ARRAYSIZE(buf), \"%.0f/%.0f\", dist_box, dist_center);\r\n            ImDrawList* draw_list = GetForegroundDrawList(window);\r\n            draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 200));\r\n            draw_list->AddText(cand.Min, IM_COL32(255, 255, 255, 255), buf);\r\n        }\r\n    }\r\n#endif\r\n\r\n    // Is it in the quadrant we're interesting in moving to?\r\n    bool new_best = false;\r\n    const ImGuiDir move_dir = g.NavMoveDir;\r\n    if (quadrant == move_dir)\r\n    {\r\n        // Does it beat the current best candidate?\r\n        if (dist_box < result->DistBox)\r\n        {\r\n            result->DistBox = dist_box;\r\n            result->DistCenter = dist_center;\r\n            return true;\r\n        }\r\n        if (dist_box == result->DistBox)\r\n        {\r\n            // Try using distance between center points to break ties\r\n            if (dist_center < result->DistCenter)\r\n            {\r\n                result->DistCenter = dist_center;\r\n                new_best = true;\r\n            }\r\n            else if (dist_center == result->DistCenter)\r\n            {\r\n                // Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving \"later\" items\r\n                // (with higher index) to the right/downwards by an infinitesimal amount since we the current \"best\" button already (so it must have a lower index),\r\n                // this is fairly easy. This rule ensures that all buttons with dx==dy==0 will end up being linked in order of appearance along the x axis.\r\n                if (((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance\r\n                    new_best = true;\r\n            }\r\n        }\r\n    }\r\n\r\n    // Axial check: if 'curr' has no link at all in some direction and 'cand' lies roughly in that direction, add a tentative link. This will only be kept if no \"real\" matches\r\n    // are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)\r\n    // This is just to avoid buttons having no links in a particular direction when there's a suitable neighbor. you get good graphs without this too.\r\n    // 2017/09/29: FIXME: This now currently only enabled inside menu bars, ideally we'd disable it everywhere. Menus in particular need to catch failure. For general navigation it feels awkward.\r\n    // Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?\r\n    if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial)  // Check axial match\r\n        if (g.NavLayer == ImGuiNavLayer_Menu && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))\r\n            if ((move_dir == ImGuiDir_Left && dax < 0.0f) || (move_dir == ImGuiDir_Right && dax > 0.0f) || (move_dir == ImGuiDir_Up && day < 0.0f) || (move_dir == ImGuiDir_Down && day > 0.0f))\r\n            {\r\n                result->DistAxial = dist_axial;\r\n                new_best = true;\r\n            }\r\n\r\n    return new_best;\r\n}\r\n\r\nstatic void ImGui::NavApplyItemToResult(ImGuiNavItemData* result)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    result->Window = window;\r\n    result->ID = g.LastItemData.ID;\r\n    result->FocusScopeId = window->DC.NavFocusScopeIdCurrent;\r\n    result->InFlags = g.LastItemData.InFlags;\r\n    result->RectRel = WindowRectAbsToRel(window, g.LastItemData.NavRect);\r\n}\r\n\r\n// We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)\r\n// This is called after LastItemData is set.\r\nstatic void ImGui::NavProcessItem()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    const ImGuiID id = g.LastItemData.ID;\r\n    const ImRect nav_bb = g.LastItemData.NavRect;\r\n    const ImGuiItemFlags item_flags = g.LastItemData.InFlags;\r\n\r\n    // Process Init Request\r\n    if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent)\r\n    {\r\n        // Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback\r\n        const bool candidate_for_nav_default_focus = (item_flags & (ImGuiItemFlags_NoNavDefaultFocus | ImGuiItemFlags_Disabled)) == 0;\r\n        if (candidate_for_nav_default_focus || g.NavInitResultId == 0)\r\n        {\r\n            g.NavInitResultId = id;\r\n            g.NavInitResultRectRel = WindowRectAbsToRel(window, nav_bb);\r\n        }\r\n        if (candidate_for_nav_default_focus)\r\n        {\r\n            g.NavInitRequest = false; // Found a match, clear request\r\n            NavUpdateAnyRequestFlag();\r\n        }\r\n    }\r\n\r\n    // Process Move Request (scoring for navigation)\r\n    // FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRect + scoring from a rect wrapped according to current wrapping policy)\r\n    if (g.NavMoveScoringItems)\r\n    {\r\n        const bool is_tab_stop = (item_flags & ImGuiItemFlags_Inputable) && (item_flags & (ImGuiItemFlags_NoTabStop | ImGuiItemFlags_Disabled)) == 0;\r\n        const bool is_tabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) != 0;\r\n        if (is_tabbing)\r\n        {\r\n            if (is_tab_stop || (g.NavMoveFlags & ImGuiNavMoveFlags_FocusApi))\r\n                NavProcessItemForTabbingRequest(id);\r\n        }\r\n        else if ((g.NavId != id || (g.NavMoveFlags & ImGuiNavMoveFlags_AllowCurrentNavId)) && !(item_flags & (ImGuiItemFlags_Disabled | ImGuiItemFlags_NoNav)))\r\n        {\r\n            ImGuiNavItemData* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;\r\n            if (!is_tabbing)\r\n            {\r\n                if (NavScoreItem(result))\r\n                    NavApplyItemToResult(result);\r\n\r\n                // Features like PageUp/PageDown need to maintain a separate score for the visible set of items.\r\n                const float VISIBLE_RATIO = 0.70f;\r\n                if ((g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb))\r\n                    if (ImClamp(nav_bb.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y) - ImClamp(nav_bb.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO)\r\n                        if (NavScoreItem(&g.NavMoveResultLocalVisible))\r\n                            NavApplyItemToResult(&g.NavMoveResultLocalVisible);\r\n            }\r\n        }\r\n    }\r\n\r\n    // Update window-relative bounding box of navigated item\r\n    if (g.NavId == id)\r\n    {\r\n        g.NavWindow = window;                                           // Always refresh g.NavWindow, because some operations such as FocusItem() don't have a window.\r\n        g.NavLayer = window->DC.NavLayerCurrent;\r\n        g.NavFocusScopeId = window->DC.NavFocusScopeIdCurrent;\r\n        g.NavIdIsAlive = true;\r\n        window->NavRectRel[window->DC.NavLayerCurrent] = WindowRectAbsToRel(window, nav_bb);    // Store item bounding box (relative to window position)\r\n    }\r\n}\r\n\r\n// Handle \"scoring\" of an item for a tabbing/focusing request initiated by NavUpdateCreateTabbingRequest().\r\n// Note that SetKeyboardFocusHere() API calls are considered tabbing requests!\r\n// - Case 1: no nav/active id:    set result to first eligible item, stop storing.\r\n// - Case 2: tab forward:         on ref id set counter, on counter elapse store result\r\n// - Case 3: tab forward wrap:    set result to first eligible item (preemptively), on ref id set counter, on next frame if counter hasn't elapsed store result. // FIXME-TABBING: Could be done as a next-frame forwarded request\r\n// - Case 4: tab backward:        store all results, on ref id pick prev, stop storing\r\n// - Case 5: tab backward wrap:   store all results, on ref id if no result keep storing until last // FIXME-TABBING: Could be done as next-frame forwarded requested\r\nvoid ImGui::NavProcessItemForTabbingRequest(ImGuiID id)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n\r\n    // Always store in NavMoveResultLocal (unlike directional request which uses NavMoveResultOther on sibling/flattened windows)\r\n    ImGuiNavItemData* result = &g.NavMoveResultLocal;\r\n    if (g.NavTabbingDir == +1)\r\n    {\r\n        // Tab Forward or SetKeyboardFocusHere() with >= 0\r\n        if (g.NavTabbingResultFirst.ID == 0)\r\n            NavApplyItemToResult(&g.NavTabbingResultFirst);\r\n        if (--g.NavTabbingCounter == 0)\r\n            NavMoveRequestResolveWithLastItem(result);\r\n        else if (g.NavId == id)\r\n            g.NavTabbingCounter = 1;\r\n    }\r\n    else if (g.NavTabbingDir == -1)\r\n    {\r\n        // Tab Backward\r\n        if (g.NavId == id)\r\n        {\r\n            if (result->ID)\r\n            {\r\n                g.NavMoveScoringItems = false;\r\n                NavUpdateAnyRequestFlag();\r\n            }\r\n        }\r\n        else\r\n        {\r\n            NavApplyItemToResult(result);\r\n        }\r\n    }\r\n    else if (g.NavTabbingDir == 0)\r\n    {\r\n        // Tab Init\r\n        if (g.NavTabbingResultFirst.ID == 0)\r\n            NavMoveRequestResolveWithLastItem(&g.NavTabbingResultFirst);\r\n    }\r\n}\r\n\r\nbool ImGui::NavMoveRequestButNoResultYet()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    return g.NavMoveScoringItems && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;\r\n}\r\n\r\n// FIXME: ScoringRect is not set\r\nvoid ImGui::NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(g.NavWindow != NULL);\r\n\r\n    if (move_flags & ImGuiNavMoveFlags_Tabbing)\r\n        move_flags |= ImGuiNavMoveFlags_AllowCurrentNavId;\r\n\r\n    g.NavMoveSubmitted = g.NavMoveScoringItems = true;\r\n    g.NavMoveDir = move_dir;\r\n    g.NavMoveDirForDebug = move_dir;\r\n    g.NavMoveClipDir = clip_dir;\r\n    g.NavMoveFlags = move_flags;\r\n    g.NavMoveScrollFlags = scroll_flags;\r\n    g.NavMoveForwardToNextFrame = false;\r\n    g.NavMoveKeyMods = g.IO.KeyMods;\r\n    g.NavTabbingCounter = 0;\r\n    g.NavMoveResultLocal.Clear();\r\n    g.NavMoveResultLocalVisible.Clear();\r\n    g.NavMoveResultOther.Clear();\r\n    NavUpdateAnyRequestFlag();\r\n}\r\n\r\nvoid ImGui::NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    g.NavMoveScoringItems = false; // Ensure request doesn't need more processing\r\n    NavApplyItemToResult(result);\r\n    NavUpdateAnyRequestFlag();\r\n}\r\n\r\nvoid ImGui::NavMoveRequestCancel()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    g.NavMoveSubmitted = g.NavMoveScoringItems = false;\r\n    NavUpdateAnyRequestFlag();\r\n}\r\n\r\n// Forward will reuse the move request again on the next frame (generally with modifications done to it)\r\nvoid ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(g.NavMoveForwardToNextFrame == false);\r\n    NavMoveRequestCancel();\r\n    g.NavMoveForwardToNextFrame = true;\r\n    g.NavMoveDir = move_dir;\r\n    g.NavMoveClipDir = clip_dir;\r\n    g.NavMoveFlags = move_flags | ImGuiNavMoveFlags_Forwarded;\r\n    g.NavMoveScrollFlags = scroll_flags;\r\n}\r\n\r\n// Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire\r\n// popup is assembled and in case of appended popups it is not clear which EndPopup() call is final.\r\nvoid ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags wrap_flags)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(wrap_flags != 0); // Call with _WrapX, _WrapY, _LoopX, _LoopY\r\n    // In theory we should test for NavMoveRequestButNoResultYet() but there's no point doing it, NavEndFrame() will do the same test\r\n    if (g.NavWindow == window && g.NavMoveScoringItems && g.NavLayer == ImGuiNavLayer_Main)\r\n        g.NavMoveFlags |= wrap_flags;\r\n}\r\n\r\n// FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0).\r\n// This way we could find the last focused window among our children. It would be much less confusing this way?\r\nstatic void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window)\r\n{\r\n    ImGuiWindow* parent = nav_window;\r\n    while (parent && parent->RootWindow != parent && (parent->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)\r\n        parent = parent->ParentWindow;\r\n    if (parent && parent != nav_window)\r\n        parent->NavLastChildNavWindow = nav_window;\r\n}\r\n\r\n// Restore the last focused child.\r\n// Call when we are expected to land on the Main Layer (0) after FocusWindow()\r\nstatic ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)\r\n{\r\n    if (window->NavLastChildNavWindow && window->NavLastChildNavWindow->WasActive)\r\n        return window->NavLastChildNavWindow;\r\n    return window;\r\n}\r\n\r\nvoid ImGui::NavRestoreLayer(ImGuiNavLayer layer)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    if (layer == ImGuiNavLayer_Main)\r\n        g.NavWindow = NavRestoreLastChildNavWindow(g.NavWindow);\r\n    ImGuiWindow* window = g.NavWindow;\r\n    if (window->NavLastIds[layer] != 0)\r\n    {\r\n        SetNavID(window->NavLastIds[layer], layer, 0, window->NavRectRel[layer]);\r\n    }\r\n    else\r\n    {\r\n        g.NavLayer = layer;\r\n        NavInitWindow(window, true);\r\n    }\r\n}\r\n\r\nvoid ImGui::NavRestoreHighlightAfterMove()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    g.NavDisableHighlight = false;\r\n    g.NavDisableMouseHover = g.NavMousePosDirty = true;\r\n}\r\n\r\nstatic inline void ImGui::NavUpdateAnyRequestFlag()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    g.NavAnyRequest = g.NavMoveScoringItems || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL);\r\n    if (g.NavAnyRequest)\r\n        IM_ASSERT(g.NavWindow != NULL);\r\n}\r\n\r\n// This needs to be called before we submit any widget (aka in or before Begin)\r\nvoid ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(window == g.NavWindow);\r\n\r\n    if (window->Flags & ImGuiWindowFlags_NoNavInputs)\r\n    {\r\n        g.NavId = g.NavFocusScopeId = 0;\r\n        return;\r\n    }\r\n\r\n    bool init_for_nav = false;\r\n    if (window == window->RootWindow || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)\r\n        init_for_nav = true;\r\n    IMGUI_DEBUG_LOG_NAV(\"[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\\\"%s\\\", layer=%d\\n\", init_for_nav, window->Name, g.NavLayer);\r\n    if (init_for_nav)\r\n    {\r\n        SetNavID(0, g.NavLayer, 0, ImRect());\r\n        g.NavInitRequest = true;\r\n        g.NavInitRequestFromMove = false;\r\n        g.NavInitResultId = 0;\r\n        g.NavInitResultRectRel = ImRect();\r\n        NavUpdateAnyRequestFlag();\r\n    }\r\n    else\r\n    {\r\n        g.NavId = window->NavLastIds[0];\r\n        g.NavFocusScopeId = 0;\r\n    }\r\n}\r\n\r\nstatic ImVec2 ImGui::NavCalcPreferredRefPos()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.NavWindow;\r\n    if (g.NavDisableHighlight || !g.NavDisableMouseHover || !window)\r\n    {\r\n        // Mouse (we need a fallback in case the mouse becomes invalid after being used)\r\n        // The +1.0f offset when stored by OpenPopupEx() allows reopening this or another popup (same or another mouse button) while not moving the mouse, it is pretty standard.\r\n        // In theory we could move that +1.0f offset in OpenPopupEx()\r\n        ImVec2 p = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : g.MouseLastValidPos;\r\n        return ImVec2(p.x + 1.0f, p.y);\r\n    }\r\n    else\r\n    {\r\n        // When navigation is active and mouse is disabled, pick a position around the bottom left of the currently navigated item\r\n        // Take account of upcoming scrolling (maybe set mouse pos should be done in EndFrame?)\r\n        ImRect rect_rel = WindowRectRelToAbs(window, window->NavRectRel[g.NavLayer]);\r\n        if (window->LastFrameActive != g.FrameCount && (window->ScrollTarget.x != FLT_MAX || window->ScrollTarget.y != FLT_MAX))\r\n        {\r\n            ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);\r\n            rect_rel.Translate(window->Scroll - next_scroll);\r\n        }\r\n        ImVec2 pos = ImVec2(rect_rel.Min.x + ImMin(g.Style.FramePadding.x * 4, rect_rel.GetWidth()), rect_rel.Max.y - ImMin(g.Style.FramePadding.y, rect_rel.GetHeight()));\r\n        ImGuiViewport* viewport = GetMainViewport();\r\n        return ImFloor(ImClamp(pos, viewport->Pos, viewport->Pos + viewport->Size)); // ImFloor() is important because non-integer mouse position application in backend might be lossy and result in undesirable non-zero delta.\r\n    }\r\n}\r\n\r\nconst char* ImGui::GetNavInputName(ImGuiNavInput n)\r\n{\r\n    static const char* names[] =\r\n    {\r\n        \"Activate\", \"Cancel\", \"Input\", \"Menu\", \"DpadLeft\", \"DpadRight\", \"DpadUp\", \"DpadDown\", \"LStickLeft\", \"LStickRight\", \"LStickUp\", \"LStickDown\",\r\n        \"FocusPrev\", \"FocusNext\", \"TweakSlow\", \"TweakFast\", \"KeyLeft\", \"KeyRight\", \"KeyUp\", \"KeyDown\"\r\n    };\r\n    IM_ASSERT(IM_ARRAYSIZE(names) == ImGuiNavInput_COUNT);\r\n    IM_ASSERT(n >= 0 && n < ImGuiNavInput_COUNT);\r\n    return names[n];\r\n}\r\n\r\nfloat ImGui::GetNavInputAmount(ImGuiNavInput n, ImGuiInputReadMode mode)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    if (mode == ImGuiInputReadMode_Down)\r\n        return g.IO.NavInputs[n];                         // Instant, read analog input (0.0f..1.0f, as provided by user)\r\n\r\n    const float t = g.IO.NavInputsDownDuration[n];\r\n    if (t < 0.0f && mode == ImGuiInputReadMode_Released)  // Return 1.0f when just released, no repeat, ignore analog input.\r\n        return (g.IO.NavInputsDownDurationPrev[n] >= 0.0f ? 1.0f : 0.0f);\r\n    if (t < 0.0f)\r\n        return 0.0f;\r\n    if (mode == ImGuiInputReadMode_Pressed)               // Return 1.0f when just pressed, no repeat, ignore analog input.\r\n        return (t == 0.0f) ? 1.0f : 0.0f;\r\n    if (mode == ImGuiInputReadMode_Repeat)\r\n        return (float)CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay * 0.72f, g.IO.KeyRepeatRate * 0.80f);\r\n    if (mode == ImGuiInputReadMode_RepeatSlow)\r\n        return (float)CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay * 1.25f, g.IO.KeyRepeatRate * 2.00f);\r\n    if (mode == ImGuiInputReadMode_RepeatFast)\r\n        return (float)CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay * 0.72f, g.IO.KeyRepeatRate * 0.30f);\r\n    return 0.0f;\r\n}\r\n\r\nImVec2 ImGui::GetNavInputAmount2d(ImGuiNavDirSourceFlags dir_sources, ImGuiInputReadMode mode, float slow_factor, float fast_factor)\r\n{\r\n    ImVec2 delta(0.0f, 0.0f);\r\n    if (dir_sources & ImGuiNavDirSourceFlags_RawKeyboard)\r\n        delta += ImVec2((float)IsKeyDown(ImGuiKey_RightArrow) - (float)IsKeyDown(ImGuiKey_LeftArrow), (float)IsKeyDown(ImGuiKey_DownArrow) - (float)IsKeyDown(ImGuiKey_UpArrow));\r\n    if (dir_sources & ImGuiNavDirSourceFlags_Keyboard)\r\n        delta += ImVec2(GetNavInputAmount(ImGuiNavInput_KeyRight_, mode)   - GetNavInputAmount(ImGuiNavInput_KeyLeft_,   mode), GetNavInputAmount(ImGuiNavInput_KeyDown_,   mode) - GetNavInputAmount(ImGuiNavInput_KeyUp_,   mode));\r\n    if (dir_sources & ImGuiNavDirSourceFlags_PadDPad)\r\n        delta += ImVec2(GetNavInputAmount(ImGuiNavInput_DpadRight, mode)   - GetNavInputAmount(ImGuiNavInput_DpadLeft,   mode), GetNavInputAmount(ImGuiNavInput_DpadDown,   mode) - GetNavInputAmount(ImGuiNavInput_DpadUp,   mode));\r\n    if (dir_sources & ImGuiNavDirSourceFlags_PadLStick)\r\n        delta += ImVec2(GetNavInputAmount(ImGuiNavInput_LStickRight, mode) - GetNavInputAmount(ImGuiNavInput_LStickLeft, mode), GetNavInputAmount(ImGuiNavInput_LStickDown, mode) - GetNavInputAmount(ImGuiNavInput_LStickUp, mode));\r\n    if (slow_factor != 0.0f && IsNavInputDown(ImGuiNavInput_TweakSlow))\r\n        delta *= slow_factor;\r\n    if (fast_factor != 0.0f && IsNavInputDown(ImGuiNavInput_TweakFast))\r\n        delta *= fast_factor;\r\n    return delta;\r\n}\r\n\r\nstatic void ImGui::NavUpdate()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiIO& io = g.IO;\r\n\r\n    io.WantSetMousePos = false;\r\n    //if (g.NavScoringDebugCount > 0) IMGUI_DEBUG_LOG(\"NavScoringDebugCount %d for '%s' layer %d (Init:%d, Move:%d)\\n\", g.NavScoringDebugCount, g.NavWindow ? g.NavWindow->Name : \"NULL\", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest);\r\n\r\n    // Update Gamepad->Nav inputs mapping\r\n    // Set input source as Gamepad when buttons are pressed (as some features differs when used with Gamepad vs Keyboard)\r\n    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;\r\n    if (nav_gamepad_active && g.IO.BackendUsingLegacyNavInputArray == false)\r\n    {\r\n        for (int n = 0; n < ImGuiNavInput_COUNT; n++)\r\n            IM_ASSERT(io.NavInputs[n] == 0.0f && \"Backend needs to either only use io.AddKeyEvent()/io.AddKeyAnalogEvent(), either only fill legacy io.NavInputs[]. Not both!\");\r\n        #define NAV_MAP_KEY(_KEY, _NAV_INPUT, _ACTIVATE_NAV)  do { io.NavInputs[_NAV_INPUT] = io.KeysData[_KEY - ImGuiKey_KeysData_OFFSET].AnalogValue; if (_ACTIVATE_NAV && io.NavInputs[_NAV_INPUT] > 0.0f) { g.NavInputSource = ImGuiInputSource_Gamepad; } } while (0)\r\n        NAV_MAP_KEY(ImGuiKey_GamepadFaceDown, ImGuiNavInput_Activate, true);\r\n        NAV_MAP_KEY(ImGuiKey_GamepadFaceRight, ImGuiNavInput_Cancel, true);\r\n        NAV_MAP_KEY(ImGuiKey_GamepadFaceLeft, ImGuiNavInput_Menu, true);\r\n        NAV_MAP_KEY(ImGuiKey_GamepadFaceUp, ImGuiNavInput_Input, true);\r\n        NAV_MAP_KEY(ImGuiKey_GamepadDpadLeft, ImGuiNavInput_DpadLeft, true);\r\n        NAV_MAP_KEY(ImGuiKey_GamepadDpadRight, ImGuiNavInput_DpadRight, true);\r\n        NAV_MAP_KEY(ImGuiKey_GamepadDpadUp, ImGuiNavInput_DpadUp, true);\r\n        NAV_MAP_KEY(ImGuiKey_GamepadDpadDown, ImGuiNavInput_DpadDown, true);\r\n        NAV_MAP_KEY(ImGuiKey_GamepadL1, ImGuiNavInput_FocusPrev, false);\r\n        NAV_MAP_KEY(ImGuiKey_GamepadR1, ImGuiNavInput_FocusNext, false);\r\n        NAV_MAP_KEY(ImGuiKey_GamepadL1, ImGuiNavInput_TweakSlow, false);\r\n        NAV_MAP_KEY(ImGuiKey_GamepadR1, ImGuiNavInput_TweakFast, false);\r\n        NAV_MAP_KEY(ImGuiKey_GamepadLStickLeft, ImGuiNavInput_LStickLeft, false);\r\n        NAV_MAP_KEY(ImGuiKey_GamepadLStickRight, ImGuiNavInput_LStickRight, false);\r\n        NAV_MAP_KEY(ImGuiKey_GamepadLStickUp, ImGuiNavInput_LStickUp, false);\r\n        NAV_MAP_KEY(ImGuiKey_GamepadLStickDown, ImGuiNavInput_LStickDown, false);\r\n        #undef NAV_MAP_KEY\r\n    }\r\n\r\n    // Update Keyboard->Nav inputs mapping\r\n    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;\r\n    if (nav_keyboard_active)\r\n    {\r\n        #define NAV_MAP_KEY(_KEY, _NAV_INPUT)  do { if (IsKeyDown(_KEY)) { io.NavInputs[_NAV_INPUT] = 1.0f; g.NavInputSource = ImGuiInputSource_Keyboard; } } while (0)\r\n        NAV_MAP_KEY(ImGuiKey_Space,     ImGuiNavInput_Activate );\r\n        NAV_MAP_KEY(ImGuiKey_Enter,     ImGuiNavInput_Input    );\r\n        NAV_MAP_KEY(ImGuiKey_Escape,    ImGuiNavInput_Cancel   );\r\n        NAV_MAP_KEY(ImGuiKey_LeftArrow, ImGuiNavInput_KeyLeft_ );\r\n        NAV_MAP_KEY(ImGuiKey_RightArrow,ImGuiNavInput_KeyRight_);\r\n        NAV_MAP_KEY(ImGuiKey_UpArrow,   ImGuiNavInput_KeyUp_   );\r\n        NAV_MAP_KEY(ImGuiKey_DownArrow, ImGuiNavInput_KeyDown_ );\r\n        if (io.KeyCtrl)\r\n            io.NavInputs[ImGuiNavInput_TweakSlow] = 1.0f;\r\n        if (io.KeyShift)\r\n            io.NavInputs[ImGuiNavInput_TweakFast] = 1.0f;\r\n        #undef NAV_MAP_KEY\r\n    }\r\n    memcpy(io.NavInputsDownDurationPrev, io.NavInputsDownDuration, sizeof(io.NavInputsDownDuration));\r\n    for (int i = 0; i < IM_ARRAYSIZE(io.NavInputs); i++)\r\n        io.NavInputsDownDuration[i] = (io.NavInputs[i] > 0.0f) ? (io.NavInputsDownDuration[i] < 0.0f ? 0.0f : io.NavInputsDownDuration[i] + io.DeltaTime) : -1.0f;\r\n\r\n    // Process navigation init request (select first/default focus)\r\n    if (g.NavInitResultId != 0)\r\n        NavInitRequestApplyResult();\r\n    g.NavInitRequest = false;\r\n    g.NavInitRequestFromMove = false;\r\n    g.NavInitResultId = 0;\r\n    g.NavJustMovedToId = 0;\r\n\r\n    // Process navigation move request\r\n    if (g.NavMoveSubmitted)\r\n        NavMoveRequestApplyResult();\r\n    g.NavTabbingCounter = 0;\r\n    g.NavMoveSubmitted = g.NavMoveScoringItems = false;\r\n\r\n    // Schedule mouse position update (will be done at the bottom of this function, after 1) processing all move requests and 2) updating scrolling)\r\n    bool set_mouse_pos = false;\r\n    if (g.NavMousePosDirty && g.NavIdIsAlive)\r\n        if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow)\r\n            set_mouse_pos = true;\r\n    g.NavMousePosDirty = false;\r\n    IM_ASSERT(g.NavLayer == ImGuiNavLayer_Main || g.NavLayer == ImGuiNavLayer_Menu);\r\n\r\n    // Store our return window (for returning from Menu Layer to Main Layer) and clear it as soon as we step back in our own Layer 0\r\n    if (g.NavWindow)\r\n        NavSaveLastChildNavWindowIntoParent(g.NavWindow);\r\n    if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == ImGuiNavLayer_Main)\r\n        g.NavWindow->NavLastChildNavWindow = NULL;\r\n\r\n    // Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.)\r\n    NavUpdateWindowing();\r\n\r\n    // Set output flags for user application\r\n    io.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);\r\n    io.NavVisible = (io.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL);\r\n\r\n    // Process NavCancel input (to close a popup, get back to parent, clear focus)\r\n    NavUpdateCancelRequest();\r\n\r\n    // Process manual activation request\r\n    g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavActivateInputId = 0;\r\n    g.NavActivateFlags = ImGuiActivateFlags_None;\r\n    if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))\r\n    {\r\n        bool activate_down = IsNavInputDown(ImGuiNavInput_Activate);\r\n        bool input_down = IsNavInputDown(ImGuiNavInput_Input);\r\n        bool activate_pressed = activate_down && IsNavInputTest(ImGuiNavInput_Activate, ImGuiInputReadMode_Pressed);\r\n        bool input_pressed = input_down && IsNavInputTest(ImGuiNavInput_Input, ImGuiInputReadMode_Pressed);\r\n        if (g.ActiveId == 0 && activate_pressed)\r\n        {\r\n            g.NavActivateId = g.NavId;\r\n            g.NavActivateFlags = ImGuiActivateFlags_PreferTweak;\r\n        }\r\n        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && input_pressed)\r\n        {\r\n            g.NavActivateInputId = g.NavId;\r\n            g.NavActivateFlags = ImGuiActivateFlags_PreferInput;\r\n        }\r\n        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_down)\r\n            g.NavActivateDownId = g.NavId;\r\n        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_pressed)\r\n            g.NavActivatePressedId = g.NavId;\r\n    }\r\n    if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))\r\n        g.NavDisableHighlight = true;\r\n    if (g.NavActivateId != 0)\r\n        IM_ASSERT(g.NavActivateDownId == g.NavActivateId);\r\n\r\n    // Process programmatic activation request\r\n    // FIXME-NAV: Those should eventually be queued (unlike focus they don't cancel each others)\r\n    if (g.NavNextActivateId != 0)\r\n    {\r\n        if (g.NavNextActivateFlags & ImGuiActivateFlags_PreferInput)\r\n            g.NavActivateInputId = g.NavNextActivateId;\r\n        else\r\n            g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavNextActivateId;\r\n        g.NavActivateFlags = g.NavNextActivateFlags;\r\n    }\r\n    g.NavNextActivateId = 0;\r\n\r\n    // Process move requests\r\n    NavUpdateCreateMoveRequest();\r\n    if (g.NavMoveDir == ImGuiDir_None)\r\n        NavUpdateCreateTabbingRequest();\r\n    NavUpdateAnyRequestFlag();\r\n    g.NavIdIsAlive = false;\r\n\r\n    // Scrolling\r\n    if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)\r\n    {\r\n        // *Fallback* manual-scroll with Nav directional keys when window has no navigable item\r\n        ImGuiWindow* window = g.NavWindow;\r\n        const float scroll_speed = IM_ROUND(window->CalcFontSize() * 100 * io.DeltaTime); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.\r\n        const ImGuiDir move_dir = g.NavMoveDir;\r\n        if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavHasScroll && move_dir != ImGuiDir_None)\r\n        {\r\n            if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)\r\n                SetScrollX(window, ImFloor(window->Scroll.x + ((move_dir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));\r\n            if (move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down)\r\n                SetScrollY(window, ImFloor(window->Scroll.y + ((move_dir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));\r\n        }\r\n\r\n        // *Normal* Manual scroll with NavScrollXXX keys\r\n        // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.\r\n        ImVec2 scroll_dir = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down, 1.0f / 10.0f, 10.0f);\r\n        if (scroll_dir.x != 0.0f && window->ScrollbarX)\r\n            SetScrollX(window, ImFloor(window->Scroll.x + scroll_dir.x * scroll_speed));\r\n        if (scroll_dir.y != 0.0f)\r\n            SetScrollY(window, ImFloor(window->Scroll.y + scroll_dir.y * scroll_speed));\r\n    }\r\n\r\n    // Always prioritize mouse highlight if navigation is disabled\r\n    if (!nav_keyboard_active && !nav_gamepad_active)\r\n    {\r\n        g.NavDisableHighlight = true;\r\n        g.NavDisableMouseHover = set_mouse_pos = false;\r\n    }\r\n\r\n    // Update mouse position if requested\r\n    // (This will take into account the possibility that a Scroll was queued in the window to offset our absolute mouse position before scroll has been applied)\r\n    if (set_mouse_pos && (io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos))\r\n    {\r\n        io.MousePos = io.MousePosPrev = NavCalcPreferredRefPos();\r\n        io.WantSetMousePos = true;\r\n        //IMGUI_DEBUG_LOG(\"SetMousePos: (%.1f,%.1f)\\n\", io.MousePos.x, io.MousePos.y);\r\n    }\r\n\r\n    // [DEBUG]\r\n    g.NavScoringDebugCount = 0;\r\n#if IMGUI_DEBUG_NAV_RECTS\r\n    if (g.NavWindow)\r\n    {\r\n        ImDrawList* draw_list = GetForegroundDrawList(g.NavWindow);\r\n        if (1) { for (int layer = 0; layer < 2; layer++) { ImRect r = WindowRectRelToAbs(g.NavWindow, g.NavWindow->NavRectRel[layer]); draw_list->AddRect(r.Min, r.Max, IM_COL32(255,200,0,255)); } } // [DEBUG]\r\n        if (1) { ImU32 col = (!g.NavWindow->Hidden) ? IM_COL32(255,0,255,255) : IM_COL32(255,0,0,255); ImVec2 p = NavCalcPreferredRefPos(); char buf[32]; ImFormatString(buf, 32, \"%d\", g.NavLayer); draw_list->AddCircleFilled(p, 3.0f, col); draw_list->AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); }\r\n    }\r\n#endif\r\n}\r\n\r\nvoid ImGui::NavInitRequestApplyResult()\r\n{\r\n    // In very rare cases g.NavWindow may be null (e.g. clearing focus after requesting an init request, which does happen when releasing Alt while clicking on void)\r\n    ImGuiContext& g = *GImGui;\r\n    if (!g.NavWindow)\r\n        return;\r\n\r\n    // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)\r\n    // FIXME-NAV: On _NavFlattened windows, g.NavWindow will only be updated during subsequent frame. Not a problem currently.\r\n    IMGUI_DEBUG_LOG_NAV(\"[nav] NavInitRequest: result NavID 0x%08X in Layer %d Window \\\"%s\\\"\\n\", g.NavInitResultId, g.NavLayer, g.NavWindow->Name);\r\n    SetNavID(g.NavInitResultId, g.NavLayer, 0, g.NavInitResultRectRel);\r\n    g.NavIdIsAlive = true; // Mark as alive from previous frame as we got a result\r\n    if (g.NavInitRequestFromMove)\r\n        NavRestoreHighlightAfterMove();\r\n}\r\n\r\nvoid ImGui::NavUpdateCreateMoveRequest()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiIO& io = g.IO;\r\n    ImGuiWindow* window = g.NavWindow;\r\n\r\n    if (g.NavMoveForwardToNextFrame && window != NULL)\r\n    {\r\n        // Forwarding previous request (which has been modified, e.g. wrap around menus rewrite the requests with a starting rectangle at the other side of the window)\r\n        // (preserve most state, which were already set by the NavMoveRequestForward() function)\r\n        IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);\r\n        IM_ASSERT(g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded);\r\n        IMGUI_DEBUG_LOG_NAV(\"[nav] NavMoveRequestForward %d\\n\", g.NavMoveDir);\r\n    }\r\n    else\r\n    {\r\n        // Initiate directional inputs request\r\n        g.NavMoveDir = ImGuiDir_None;\r\n        g.NavMoveFlags = ImGuiNavMoveFlags_None;\r\n        g.NavMoveScrollFlags = ImGuiScrollFlags_None;\r\n        if (window && !g.NavWindowingTarget && !(window->Flags & ImGuiWindowFlags_NoNavInputs))\r\n        {\r\n            const ImGuiInputReadMode read_mode = ImGuiInputReadMode_Repeat;\r\n            if (!IsActiveIdUsingNavDir(ImGuiDir_Left)  && (IsNavInputTest(ImGuiNavInput_DpadLeft,  read_mode) || IsNavInputTest(ImGuiNavInput_KeyLeft_,  read_mode))) { g.NavMoveDir = ImGuiDir_Left; }\r\n            if (!IsActiveIdUsingNavDir(ImGuiDir_Right) && (IsNavInputTest(ImGuiNavInput_DpadRight, read_mode) || IsNavInputTest(ImGuiNavInput_KeyRight_, read_mode))) { g.NavMoveDir = ImGuiDir_Right; }\r\n            if (!IsActiveIdUsingNavDir(ImGuiDir_Up)    && (IsNavInputTest(ImGuiNavInput_DpadUp,    read_mode) || IsNavInputTest(ImGuiNavInput_KeyUp_,    read_mode))) { g.NavMoveDir = ImGuiDir_Up; }\r\n            if (!IsActiveIdUsingNavDir(ImGuiDir_Down)  && (IsNavInputTest(ImGuiNavInput_DpadDown,  read_mode) || IsNavInputTest(ImGuiNavInput_KeyDown_,  read_mode))) { g.NavMoveDir = ImGuiDir_Down; }\r\n        }\r\n        g.NavMoveClipDir = g.NavMoveDir;\r\n        g.NavScoringNoClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);\r\n    }\r\n\r\n    // Update PageUp/PageDown/Home/End scroll\r\n    // FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag?\r\n    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;\r\n    float scoring_rect_offset_y = 0.0f;\r\n    if (window && g.NavMoveDir == ImGuiDir_None && nav_keyboard_active)\r\n        scoring_rect_offset_y = NavUpdatePageUpPageDown();\r\n    if (scoring_rect_offset_y != 0.0f)\r\n    {\r\n        g.NavScoringNoClipRect = window->InnerRect;\r\n        g.NavScoringNoClipRect.TranslateY(scoring_rect_offset_y);\r\n    }\r\n\r\n    // [DEBUG] Always send a request\r\n#if IMGUI_DEBUG_NAV_SCORING\r\n    if (io.KeyCtrl && IsKeyPressed(ImGuiKey_C))\r\n        g.NavMoveDirForDebug = (ImGuiDir)((g.NavMoveDirForDebug + 1) & 3);\r\n    if (io.KeyCtrl && g.NavMoveDir == ImGuiDir_None)\r\n    {\r\n        g.NavMoveDir = g.NavMoveDirForDebug;\r\n        g.NavMoveFlags |= ImGuiNavMoveFlags_DebugNoResult;\r\n    }\r\n#endif\r\n\r\n    // Submit\r\n    g.NavMoveForwardToNextFrame = false;\r\n    if (g.NavMoveDir != ImGuiDir_None)\r\n        NavMoveRequestSubmit(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags);\r\n\r\n    // Moving with no reference triggers a init request (will be used as a fallback if the direction fails to find a match)\r\n    if (g.NavMoveSubmitted && g.NavId == 0)\r\n    {\r\n        IMGUI_DEBUG_LOG_NAV(\"[nav] NavInitRequest: from move, window \\\"%s\\\", layer=%d\\n\", g.NavWindow->Name, g.NavLayer);\r\n        g.NavInitRequest = g.NavInitRequestFromMove = true;\r\n        g.NavInitResultId = 0;\r\n        g.NavDisableHighlight = false;\r\n    }\r\n\r\n    // When using gamepad, we project the reference nav bounding box into window visible area.\r\n    // This is to allow resuming navigation inside the visible area after doing a large amount of scrolling, since with gamepad every movements are relative\r\n    // (can't focus a visible object like we can with the mouse).\r\n    if (g.NavMoveSubmitted && g.NavInputSource == ImGuiInputSource_Gamepad && g.NavLayer == ImGuiNavLayer_Main && window != NULL)// && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded))\r\n    {\r\n        bool clamp_x = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_WrapX)) == 0;\r\n        bool clamp_y = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopY | ImGuiNavMoveFlags_WrapY)) == 0;\r\n        ImRect inner_rect_rel = WindowRectAbsToRel(window, ImRect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1)));\r\n        if ((clamp_x || clamp_y) && !inner_rect_rel.Contains(window->NavRectRel[g.NavLayer]))\r\n        {\r\n            IMGUI_DEBUG_LOG_NAV(\"[nav] NavMoveRequest: clamp NavRectRel for gamepad move\\n\");\r\n            float pad_x = ImMin(inner_rect_rel.GetWidth(), window->CalcFontSize() * 0.5f);\r\n            float pad_y = ImMin(inner_rect_rel.GetHeight(), window->CalcFontSize() * 0.5f); // Terrible approximation for the intent of starting navigation from first fully visible item\r\n            inner_rect_rel.Min.x = clamp_x ? (inner_rect_rel.Min.x + pad_x) : -FLT_MAX;\r\n            inner_rect_rel.Max.x = clamp_x ? (inner_rect_rel.Max.x - pad_x) : +FLT_MAX;\r\n            inner_rect_rel.Min.y = clamp_y ? (inner_rect_rel.Min.y + pad_y) : -FLT_MAX;\r\n            inner_rect_rel.Max.y = clamp_y ? (inner_rect_rel.Max.y - pad_y) : +FLT_MAX;\r\n            window->NavRectRel[g.NavLayer].ClipWithFull(inner_rect_rel);\r\n            g.NavId = g.NavFocusScopeId = 0;\r\n        }\r\n    }\r\n\r\n    // For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items)\r\n    ImRect scoring_rect;\r\n    if (window != NULL)\r\n    {\r\n        ImRect nav_rect_rel = !window->NavRectRel[g.NavLayer].IsInverted() ? window->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0);\r\n        scoring_rect = WindowRectRelToAbs(window, nav_rect_rel);\r\n        scoring_rect.TranslateY(scoring_rect_offset_y);\r\n        scoring_rect.Min.x = ImMin(scoring_rect.Min.x + 1.0f, scoring_rect.Max.x);\r\n        scoring_rect.Max.x = scoring_rect.Min.x;\r\n        IM_ASSERT(!scoring_rect.IsInverted()); // Ensure if we have a finite, non-inverted bounding box here will allows us to remove extraneous ImFabs() calls in NavScoreItem().\r\n        //GetForegroundDrawList()->AddRect(scoring_rect.Min, scoring_rect.Max, IM_COL32(255,200,0,255)); // [DEBUG]\r\n        //if (!g.NavScoringNoClipRect.IsInverted()) { GetForegroundDrawList()->AddRect(g.NavScoringNoClipRect.Min, g.NavScoringNoClipRect.Max, IM_COL32(255, 200, 0, 255)); } // [DEBUG]\r\n    }\r\n    g.NavScoringRect = scoring_rect;\r\n    g.NavScoringNoClipRect.Add(scoring_rect);\r\n}\r\n\r\nvoid ImGui::NavUpdateCreateTabbingRequest()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.NavWindow;\r\n    IM_ASSERT(g.NavMoveDir == ImGuiDir_None);\r\n    if (window == NULL || g.NavWindowingTarget != NULL || (window->Flags & ImGuiWindowFlags_NoNavInputs))\r\n        return;\r\n\r\n    const bool tab_pressed = IsKeyPressed(ImGuiKey_Tab, true) && !IsActiveIdUsingKey(ImGuiKey_Tab) && !g.IO.KeyCtrl && !g.IO.KeyAlt;\r\n    if (!tab_pressed)\r\n        return;\r\n\r\n    // Initiate tabbing request\r\n    // (this is ALWAYS ENABLED, regardless of ImGuiConfigFlags_NavEnableKeyboard flag!)\r\n    // Initially this was designed to use counters and modulo arithmetic, but that could not work with unsubmitted items (list clipper). Instead we use a strategy close to other move requests.\r\n    // See NavProcessItemForTabbingRequest() for a description of the various forward/backward tabbing cases with and without wrapping.\r\n    //// FIXME: We use (g.ActiveId == 0) but (g.NavDisableHighlight == false) might be righter once we can tab through anything\r\n    g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.ActiveId == 0) ? 0 : +1;\r\n    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;\r\n    ImGuiDir clip_dir = (g.NavTabbingDir < 0) ? ImGuiDir_Up : ImGuiDir_Down;\r\n    NavMoveRequestSubmit(ImGuiDir_None, clip_dir, ImGuiNavMoveFlags_Tabbing, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.\r\n    g.NavTabbingResultFirst.Clear();\r\n    g.NavTabbingCounter = -1;\r\n}\r\n\r\n// Apply result from previous frame navigation directional move request. Always called from NavUpdate()\r\nvoid ImGui::NavMoveRequestApplyResult()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n#if IMGUI_DEBUG_NAV_SCORING\r\n    if (g.NavMoveFlags & ImGuiNavMoveFlags_DebugNoResult) // [DEBUG] Scoring all items in NavWindow at all times\r\n        return;\r\n#endif\r\n\r\n    // Select which result to use\r\n    ImGuiNavItemData* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : (g.NavMoveResultOther.ID != 0) ? &g.NavMoveResultOther : NULL;\r\n\r\n    // Tabbing forward wrap\r\n    if (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing)\r\n        if ((g.NavTabbingCounter == 1 || g.NavTabbingDir == 0) && g.NavTabbingResultFirst.ID)\r\n            result = &g.NavTabbingResultFirst;\r\n\r\n    // In a situation when there is no results but NavId != 0, re-enable the Navigation highlight (because g.NavId is not considered as a possible result)\r\n    if (result == NULL)\r\n    {\r\n        if (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing)\r\n            g.NavMoveFlags |= ImGuiNavMoveFlags_DontSetNavHighlight;\r\n        if (g.NavId != 0 && (g.NavMoveFlags & ImGuiNavMoveFlags_DontSetNavHighlight) == 0)\r\n            NavRestoreHighlightAfterMove();\r\n        return;\r\n    }\r\n\r\n    // PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.\r\n    if (g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet)\r\n        if (g.NavMoveResultLocalVisible.ID != 0 && g.NavMoveResultLocalVisible.ID != g.NavId)\r\n            result = &g.NavMoveResultLocalVisible;\r\n\r\n    // Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules.\r\n    if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow)\r\n        if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter))\r\n            result = &g.NavMoveResultOther;\r\n    IM_ASSERT(g.NavWindow && result->Window);\r\n\r\n    // Scroll to keep newly navigated item fully into view.\r\n    if (g.NavLayer == ImGuiNavLayer_Main)\r\n    {\r\n        if (g.NavMoveFlags & ImGuiNavMoveFlags_ScrollToEdgeY)\r\n        {\r\n            // FIXME: Should remove this\r\n            float scroll_target = (g.NavMoveDir == ImGuiDir_Up) ? result->Window->ScrollMax.y : 0.0f;\r\n            SetScrollY(result->Window, scroll_target);\r\n        }\r\n        else\r\n        {\r\n            ImRect rect_abs = WindowRectRelToAbs(result->Window, result->RectRel);\r\n            ScrollToRectEx(result->Window, rect_abs, g.NavMoveScrollFlags);\r\n        }\r\n    }\r\n\r\n    g.NavWindow = result->Window;\r\n    if (g.ActiveId != result->ID)\r\n        ClearActiveID();\r\n    if (g.NavId != result->ID)\r\n    {\r\n        // Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)\r\n        g.NavJustMovedToId = result->ID;\r\n        g.NavJustMovedToFocusScopeId = result->FocusScopeId;\r\n        g.NavJustMovedToKeyMods = g.NavMoveKeyMods;\r\n    }\r\n\r\n    // Focus\r\n    IMGUI_DEBUG_LOG_NAV(\"[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \\\"%s\\\"\\n\", result->ID, g.NavLayer, g.NavWindow->Name);\r\n    SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);\r\n\r\n    // Tabbing: Activates Inputable or Focus non-Inputable\r\n    if ((g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) && (result->InFlags & ImGuiItemFlags_Inputable))\r\n    {\r\n        g.NavNextActivateId = result->ID;\r\n        g.NavNextActivateFlags = ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_TryToPreserveState;\r\n        g.NavMoveFlags |= ImGuiNavMoveFlags_DontSetNavHighlight;\r\n    }\r\n\r\n    // Activate\r\n    if (g.NavMoveFlags & ImGuiNavMoveFlags_Activate)\r\n    {\r\n        g.NavNextActivateId = result->ID;\r\n        g.NavNextActivateFlags = ImGuiActivateFlags_None;\r\n    }\r\n\r\n    // Enable nav highlight\r\n    if ((g.NavMoveFlags & ImGuiNavMoveFlags_DontSetNavHighlight) == 0)\r\n        NavRestoreHighlightAfterMove();\r\n}\r\n\r\n// Process NavCancel input (to close a popup, get back to parent, clear focus)\r\n// FIXME: In order to support e.g. Escape to clear a selection we'll need:\r\n// - either to store the equivalent of ActiveIdUsingKeyInputMask for a FocusScope and test for it.\r\n// - either to move most/all of those tests to the epilogue/end functions of the scope they are dealing with (e.g. exit child window in EndChild()) or in EndFrame(), to allow an earlier intercept\r\nstatic void ImGui::NavUpdateCancelRequest()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    if (!IsNavInputTest(ImGuiNavInput_Cancel, ImGuiInputReadMode_Pressed))\r\n        return;\r\n\r\n    IMGUI_DEBUG_LOG_NAV(\"[nav] ImGuiNavInput_Cancel\\n\");\r\n    if (g.ActiveId != 0)\r\n    {\r\n        if (!IsActiveIdUsingNavInput(ImGuiNavInput_Cancel))\r\n            ClearActiveID();\r\n    }\r\n    else if (g.NavLayer != ImGuiNavLayer_Main)\r\n    {\r\n        // Leave the \"menu\" layer\r\n        NavRestoreLayer(ImGuiNavLayer_Main);\r\n        NavRestoreHighlightAfterMove();\r\n    }\r\n    else if (g.NavWindow && g.NavWindow != g.NavWindow->RootWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->ParentWindow)\r\n    {\r\n        // Exit child window\r\n        ImGuiWindow* child_window = g.NavWindow;\r\n        ImGuiWindow* parent_window = g.NavWindow->ParentWindow;\r\n        IM_ASSERT(child_window->ChildId != 0);\r\n        ImRect child_rect = child_window->Rect();\r\n        FocusWindow(parent_window);\r\n        SetNavID(child_window->ChildId, ImGuiNavLayer_Main, 0, WindowRectAbsToRel(parent_window, child_rect));\r\n        NavRestoreHighlightAfterMove();\r\n    }\r\n    else if (g.OpenPopupStack.Size > 0)\r\n    {\r\n        // Close open popup/menu\r\n        if (!(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))\r\n            ClosePopupToLevel(g.OpenPopupStack.Size - 1, true);\r\n    }\r\n    else\r\n    {\r\n        // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were\r\n        if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))\r\n            g.NavWindow->NavLastIds[0] = 0;\r\n        g.NavId = g.NavFocusScopeId = 0;\r\n    }\r\n}\r\n\r\n// Handle PageUp/PageDown/Home/End keys\r\n// Called from NavUpdateCreateMoveRequest() which will use our output to create a move request\r\n// FIXME-NAV: This doesn't work properly with NavFlattened siblings as we use NavWindow rectangle for reference\r\n// FIXME-NAV: how to get Home/End to aim at the beginning/end of a 2D grid?\r\nstatic float ImGui::NavUpdatePageUpPageDown()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.NavWindow;\r\n    if ((window->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL)\r\n        return 0.0f;\r\n\r\n    const bool page_up_held = IsKeyDown(ImGuiKey_PageUp) && !IsActiveIdUsingKey(ImGuiKey_PageUp);\r\n    const bool page_down_held = IsKeyDown(ImGuiKey_PageDown) && !IsActiveIdUsingKey(ImGuiKey_PageDown);\r\n    const bool home_pressed = IsKeyPressed(ImGuiKey_Home) && !IsActiveIdUsingKey(ImGuiKey_Home);\r\n    const bool end_pressed = IsKeyPressed(ImGuiKey_End) && !IsActiveIdUsingKey(ImGuiKey_End);\r\n    if (page_up_held == page_down_held && home_pressed == end_pressed) // Proceed if either (not both) are pressed, otherwise early out\r\n        return 0.0f;\r\n\r\n    if (g.NavLayer != ImGuiNavLayer_Main)\r\n        NavRestoreLayer(ImGuiNavLayer_Main);\r\n\r\n    if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavHasScroll)\r\n    {\r\n        // Fallback manual-scroll when window has no navigable item\r\n        if (IsKeyPressed(ImGuiKey_PageUp, true))\r\n            SetScrollY(window, window->Scroll.y - window->InnerRect.GetHeight());\r\n        else if (IsKeyPressed(ImGuiKey_PageDown, true))\r\n            SetScrollY(window, window->Scroll.y + window->InnerRect.GetHeight());\r\n        else if (home_pressed)\r\n            SetScrollY(window, 0.0f);\r\n        else if (end_pressed)\r\n            SetScrollY(window, window->ScrollMax.y);\r\n    }\r\n    else\r\n    {\r\n        ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];\r\n        const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight());\r\n        float nav_scoring_rect_offset_y = 0.0f;\r\n        if (IsKeyPressed(ImGuiKey_PageUp, true))\r\n        {\r\n            nav_scoring_rect_offset_y = -page_offset_y;\r\n            g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset up, we request the down direction (so we can always land on the last item)\r\n            g.NavMoveClipDir = ImGuiDir_Up;\r\n            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;\r\n        }\r\n        else if (IsKeyPressed(ImGuiKey_PageDown, true))\r\n        {\r\n            nav_scoring_rect_offset_y = +page_offset_y;\r\n            g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset down, we request the up direction (so we can always land on the last item)\r\n            g.NavMoveClipDir = ImGuiDir_Down;\r\n            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;\r\n        }\r\n        else if (home_pressed)\r\n        {\r\n            // FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y\r\n            // Scrolling will be handled via the ImGuiNavMoveFlags_ScrollToEdgeY flag, we don't scroll immediately to avoid scrolling happening before nav result.\r\n            // Preserve current horizontal position if we have any.\r\n            nav_rect_rel.Min.y = nav_rect_rel.Max.y = 0.0f;\r\n            if (nav_rect_rel.IsInverted())\r\n                nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;\r\n            g.NavMoveDir = ImGuiDir_Down;\r\n            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;\r\n            // FIXME-NAV: MoveClipDir left to _None, intentional?\r\n        }\r\n        else if (end_pressed)\r\n        {\r\n            nav_rect_rel.Min.y = nav_rect_rel.Max.y = window->ContentSize.y;\r\n            if (nav_rect_rel.IsInverted())\r\n                nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;\r\n            g.NavMoveDir = ImGuiDir_Up;\r\n            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;\r\n            // FIXME-NAV: MoveClipDir left to _None, intentional?\r\n        }\r\n        return nav_scoring_rect_offset_y;\r\n    }\r\n    return 0.0f;\r\n}\r\n\r\nstatic void ImGui::NavEndFrame()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n\r\n    // Show CTRL+TAB list window\r\n    if (g.NavWindowingTarget != NULL)\r\n        NavUpdateWindowingOverlay();\r\n\r\n    // Perform wrap-around in menus\r\n    // FIXME-NAV: Wrap may need to apply a weight bias on the other axis. e.g. 4x4 grid with 2 last items missing on last item won't handle LoopY/WrapY correctly.\r\n    // FIXME-NAV: Wrap (not Loop) support could be handled by the scoring function and then WrapX would function without an extra frame.\r\n    const ImGuiNavMoveFlags wanted_flags = ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY;\r\n    if (g.NavWindow && NavMoveRequestButNoResultYet() && (g.NavMoveFlags & wanted_flags) && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded) == 0)\r\n        NavUpdateCreateWrappingRequest();\r\n}\r\n\r\nstatic void ImGui::NavUpdateCreateWrappingRequest()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.NavWindow;\r\n\r\n    bool do_forward = false;\r\n    ImRect bb_rel = window->NavRectRel[g.NavLayer];\r\n    ImGuiDir clip_dir = g.NavMoveDir;\r\n    const ImGuiNavMoveFlags move_flags = g.NavMoveFlags;\r\n    if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))\r\n    {\r\n        bb_rel.Min.x = bb_rel.Max.x = window->ContentSize.x + window->WindowPadding.x;\r\n        if (move_flags & ImGuiNavMoveFlags_WrapX)\r\n        {\r\n            bb_rel.TranslateY(-bb_rel.GetHeight()); // Previous row\r\n            clip_dir = ImGuiDir_Up;\r\n        }\r\n        do_forward = true;\r\n    }\r\n    if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))\r\n    {\r\n        bb_rel.Min.x = bb_rel.Max.x = -window->WindowPadding.x;\r\n        if (move_flags & ImGuiNavMoveFlags_WrapX)\r\n        {\r\n            bb_rel.TranslateY(+bb_rel.GetHeight()); // Next row\r\n            clip_dir = ImGuiDir_Down;\r\n        }\r\n        do_forward = true;\r\n    }\r\n    if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))\r\n    {\r\n        bb_rel.Min.y = bb_rel.Max.y = window->ContentSize.y + window->WindowPadding.y;\r\n        if (move_flags & ImGuiNavMoveFlags_WrapY)\r\n        {\r\n            bb_rel.TranslateX(-bb_rel.GetWidth()); // Previous column\r\n            clip_dir = ImGuiDir_Left;\r\n        }\r\n        do_forward = true;\r\n    }\r\n    if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))\r\n    {\r\n        bb_rel.Min.y = bb_rel.Max.y = -window->WindowPadding.y;\r\n        if (move_flags & ImGuiNavMoveFlags_WrapY)\r\n        {\r\n            bb_rel.TranslateX(+bb_rel.GetWidth()); // Next column\r\n            clip_dir = ImGuiDir_Right;\r\n        }\r\n        do_forward = true;\r\n    }\r\n    if (!do_forward)\r\n        return;\r\n    window->NavRectRel[g.NavLayer] = bb_rel;\r\n    NavMoveRequestForward(g.NavMoveDir, clip_dir, move_flags, g.NavMoveScrollFlags);\r\n}\r\n\r\nstatic int ImGui::FindWindowFocusIndex(ImGuiWindow* window)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    IM_UNUSED(g);\r\n    int order = window->FocusOrder;\r\n    IM_ASSERT(window->RootWindow == window); // No child window (not testing _ChildWindow because of docking)\r\n    IM_ASSERT(g.WindowsFocusOrder[order] == window);\r\n    return order;\r\n}\r\n\r\nstatic ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir)\r\n        if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i]))\r\n            return g.WindowsFocusOrder[i];\r\n    return NULL;\r\n}\r\n\r\nstatic void NavUpdateWindowingHighlightWindow(int focus_change_dir)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(g.NavWindowingTarget);\r\n    if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)\r\n        return;\r\n\r\n    const int i_current = ImGui::FindWindowFocusIndex(g.NavWindowingTarget);\r\n    ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir);\r\n    if (!window_target)\r\n        window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir);\r\n    if (window_target) // Don't reset windowing target if there's a single window in the list\r\n        g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target;\r\n    g.NavWindowingToggleLayer = false;\r\n}\r\n\r\n// Windowing management mode\r\n// Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer)\r\n// Gamepad:  Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer)\r\nstatic void ImGui::NavUpdateWindowing()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiIO& io = g.IO;\r\n\r\n    ImGuiWindow* apply_focus_window = NULL;\r\n    bool apply_toggle_layer = false;\r\n\r\n    ImGuiWindow* modal_window = GetTopMostPopupModal();\r\n    bool allow_windowing = (modal_window == NULL);\r\n    if (!allow_windowing)\r\n        g.NavWindowingTarget = NULL;\r\n\r\n    // Fade out\r\n    if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL)\r\n    {\r\n        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - io.DeltaTime * 10.0f, 0.0f);\r\n        if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)\r\n            g.NavWindowingTargetAnim = NULL;\r\n    }\r\n\r\n    // Start CTRL+Tab or Square+L/R window selection\r\n    const bool start_windowing_with_gamepad = allow_windowing && !g.NavWindowingTarget && IsNavInputTest(ImGuiNavInput_Menu, ImGuiInputReadMode_Pressed);\r\n    const bool start_windowing_with_keyboard = allow_windowing && !g.NavWindowingTarget && io.KeyCtrl && IsKeyPressed(ImGuiKey_Tab);\r\n    if (start_windowing_with_gamepad || start_windowing_with_keyboard)\r\n        if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))\r\n        {\r\n            g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow;\r\n            g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;\r\n            g.NavWindowingToggleLayer = start_windowing_with_gamepad ? true : false; // Gamepad starts toggling layer\r\n            g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad;\r\n        }\r\n\r\n    // Gamepad update\r\n    g.NavWindowingTimer += io.DeltaTime;\r\n    if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Gamepad)\r\n    {\r\n        // Highlight only appears after a brief time holding the button, so that a fast tap on PadMenu (to toggle NavLayer) doesn't add visual noise\r\n        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));\r\n\r\n        // Select window to focus\r\n        const int focus_change_dir = (int)IsNavInputTest(ImGuiNavInput_FocusPrev, ImGuiInputReadMode_RepeatSlow) - (int)IsNavInputTest(ImGuiNavInput_FocusNext, ImGuiInputReadMode_RepeatSlow);\r\n        if (focus_change_dir != 0)\r\n        {\r\n            NavUpdateWindowingHighlightWindow(focus_change_dir);\r\n            g.NavWindowingHighlightAlpha = 1.0f;\r\n        }\r\n\r\n        // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most)\r\n        if (!IsNavInputDown(ImGuiNavInput_Menu))\r\n        {\r\n            g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.\r\n            if (g.NavWindowingToggleLayer && g.NavWindow)\r\n                apply_toggle_layer = true;\r\n            else if (!g.NavWindowingToggleLayer)\r\n                apply_focus_window = g.NavWindowingTarget;\r\n            g.NavWindowingTarget = NULL;\r\n        }\r\n    }\r\n\r\n    // Keyboard: Focus\r\n    if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Keyboard)\r\n    {\r\n        // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise\r\n        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f\r\n        if (IsKeyPressed(ImGuiKey_Tab, true))\r\n            NavUpdateWindowingHighlightWindow(io.KeyShift ? +1 : -1);\r\n        if (!io.KeyCtrl)\r\n            apply_focus_window = g.NavWindowingTarget;\r\n    }\r\n\r\n    // Keyboard: Press and Release ALT to toggle menu layer\r\n    // - Testing that only Alt is tested prevents Alt+Shift or AltGR from toggling menu layer.\r\n    // - AltGR is normally Alt+Ctrl but we can't reliably detect it (not all backends/systems/layout emit it as Alt+Ctrl). But even on keyboards without AltGR we don't want Alt+Ctrl to open menu anyway.\r\n\tconst bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;\r\n    if (nav_keyboard_active && io.KeyMods == ImGuiKeyModFlags_Alt && (io.KeyModsPrev & ImGuiKeyModFlags_Alt) == 0)\r\n    {\r\n        g.NavWindowingToggleLayer = true;\r\n        g.NavInputSource = ImGuiInputSource_Keyboard;\r\n    }\r\n    if (g.NavWindowingToggleLayer && g.NavInputSource == ImGuiInputSource_Keyboard)\r\n    {\r\n        // We cancel toggling nav layer when any text has been typed (generally while holding Alt). (See #370)\r\n        // We cancel toggling nav layer when other modifiers are pressed. (See #4439)\r\n        if (io.InputQueueCharacters.Size > 0 || io.KeyCtrl || io.KeyShift || io.KeySuper)\r\n            g.NavWindowingToggleLayer = false;\r\n\r\n        // Apply layer toggle on release\r\n        // Important: we don't assume that Alt was previously held in order to handle loss of focus when backend calls io.AddFocusEvent(false)\r\n        // Important: as before version <18314 we lacked an explicit IO event for focus gain/loss, we also compare mouse validity to detect old backends clearing mouse pos on focus loss.\r\n        if (!(io.KeyMods & ImGuiKeyModFlags_Alt) && (io.KeyModsPrev & ImGuiKeyModFlags_Alt) && g.NavWindowingToggleLayer)\r\n            if (g.ActiveId == 0 || g.ActiveIdAllowOverlap)\r\n                if (IsMousePosValid(&io.MousePos) == IsMousePosValid(&io.MousePosPrev))\r\n                    apply_toggle_layer = true;\r\n        if (!io.KeyAlt)\r\n            g.NavWindowingToggleLayer = false;\r\n    }\r\n\r\n    // Move window\r\n    if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove))\r\n    {\r\n        ImVec2 move_delta;\r\n        if (g.NavInputSource == ImGuiInputSource_Keyboard && !io.KeyShift)\r\n            move_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_RawKeyboard, ImGuiInputReadMode_Down);\r\n        if (g.NavInputSource == ImGuiInputSource_Gamepad)\r\n            move_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down);\r\n        if (move_delta.x != 0.0f || move_delta.y != 0.0f)\r\n        {\r\n            const float NAV_MOVE_SPEED = 800.0f;\r\n            const float move_speed = ImFloor(NAV_MOVE_SPEED * io.DeltaTime * ImMin(io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y)); // FIXME: Doesn't handle variable framerate very well\r\n            ImGuiWindow* moving_window = g.NavWindowingTarget->RootWindow;\r\n            SetWindowPos(moving_window, moving_window->Pos + move_delta * move_speed, ImGuiCond_Always);\r\n            MarkIniSettingsDirty(moving_window);\r\n            g.NavDisableMouseHover = true;\r\n        }\r\n    }\r\n\r\n    // Apply final focus\r\n    if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow))\r\n    {\r\n        ClearActiveID();\r\n        NavRestoreHighlightAfterMove();\r\n        apply_focus_window = NavRestoreLastChildNavWindow(apply_focus_window);\r\n        ClosePopupsOverWindow(apply_focus_window, false);\r\n        FocusWindow(apply_focus_window);\r\n        if (apply_focus_window->NavLastIds[0] == 0)\r\n            NavInitWindow(apply_focus_window, false);\r\n\r\n        // If the window has ONLY a menu layer (no main layer), select it directly\r\n        // Use NavLayersActiveMaskNext since windows didn't have a chance to be Begin()-ed on this frame,\r\n        // so CTRL+Tab where the keys are only held for 1 frame will be able to use correct layers mask since\r\n        // the target window as already been previewed once.\r\n        // FIXME-NAV: This should be done in NavInit.. or in FocusWindow... However in both of those cases,\r\n        // we won't have a guarantee that windows has been visible before and therefore NavLayersActiveMask*\r\n        // won't be valid.\r\n        if (apply_focus_window->DC.NavLayersActiveMaskNext == (1 << ImGuiNavLayer_Menu))\r\n            g.NavLayer = ImGuiNavLayer_Menu;\r\n    }\r\n    if (apply_focus_window)\r\n        g.NavWindowingTarget = NULL;\r\n\r\n    // Apply menu/layer toggle\r\n    if (apply_toggle_layer && g.NavWindow)\r\n    {\r\n        ClearActiveID();\r\n\r\n        // Move to parent menu if necessary\r\n        ImGuiWindow* new_nav_window = g.NavWindow;\r\n        while (new_nav_window->ParentWindow\r\n            && (new_nav_window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0\r\n            && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0\r\n            && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)\r\n            new_nav_window = new_nav_window->ParentWindow;\r\n        if (new_nav_window != g.NavWindow)\r\n        {\r\n            ImGuiWindow* old_nav_window = g.NavWindow;\r\n            FocusWindow(new_nav_window);\r\n            new_nav_window->NavLastChildNavWindow = old_nav_window;\r\n        }\r\n\r\n        // Toggle layer\r\n        const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main;\r\n        if (new_nav_layer != g.NavLayer)\r\n        {\r\n            // Reinitialize navigation when entering menu bar with the Alt key (FIXME: could be a properly of the layer?)\r\n            if (new_nav_layer == ImGuiNavLayer_Menu)\r\n                g.NavWindow->NavLastIds[new_nav_layer] = 0;\r\n            NavRestoreLayer(new_nav_layer);\r\n            NavRestoreHighlightAfterMove();\r\n        }\r\n    }\r\n}\r\n\r\n// Window has already passed the IsWindowNavFocusable()\r\nstatic const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window)\r\n{\r\n    if (window->Flags & ImGuiWindowFlags_Popup)\r\n        return \"(Popup)\";\r\n    if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, \"##MainMenuBar\") == 0)\r\n        return \"(Main menu bar)\";\r\n    return \"(Untitled)\";\r\n}\r\n\r\n// Overlay displayed when using CTRL+TAB. Called by EndFrame().\r\nvoid ImGui::NavUpdateWindowingOverlay()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(g.NavWindowingTarget != NULL);\r\n\r\n    if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY)\r\n        return;\r\n\r\n    if (g.NavWindowingListWindow == NULL)\r\n        g.NavWindowingListWindow = FindWindowByName(\"###NavWindowingList\");\r\n    const ImGuiViewport* viewport = GetMainViewport();\r\n    SetNextWindowSizeConstraints(ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX));\r\n    SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f));\r\n    PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f);\r\n    Begin(\"###NavWindowingList\", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);\r\n    for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)\r\n    {\r\n        ImGuiWindow* window = g.WindowsFocusOrder[n];\r\n        IM_ASSERT(window != NULL); // Fix static analyzers\r\n        if (!IsWindowNavFocusable(window))\r\n            continue;\r\n        const char* label = window->Name;\r\n        if (label == FindRenderedTextEnd(label))\r\n            label = GetFallbackWindowNameForWindowingList(window);\r\n        Selectable(label, g.NavWindowingTarget == window);\r\n    }\r\n    End();\r\n    PopStyleVar();\r\n}\r\n\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] DRAG AND DROP\r\n//-----------------------------------------------------------------------------\r\n\r\nvoid ImGui::ClearDragDrop()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    g.DragDropActive = false;\r\n    g.DragDropPayload.Clear();\r\n    g.DragDropAcceptFlags = ImGuiDragDropFlags_None;\r\n    g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;\r\n    g.DragDropAcceptIdCurrRectSurface = FLT_MAX;\r\n    g.DragDropAcceptFrameCount = -1;\r\n\r\n    g.DragDropPayloadBufHeap.clear();\r\n    memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));\r\n}\r\n\r\n// When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()\r\n// If the item has an identifier:\r\n// - This assume/require the item to be activated (typically via ButtonBehavior).\r\n// - Therefore if you want to use this with a mouse button other than left mouse button, it is up to the item itself to activate with another button.\r\n// - We then pull and use the mouse button that was used to activate the item and use it to carry on the drag.\r\n// If the item has no identifier:\r\n// - Currently always assume left mouse button.\r\nbool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n\r\n    // FIXME-DRAGDROP: While in the common-most \"drag from non-zero active id\" case we can tell the mouse button,\r\n    // in both SourceExtern and id==0 cases we may requires something else (explicit flags or some heuristic).\r\n    ImGuiMouseButton mouse_button = ImGuiMouseButton_Left;\r\n\r\n    bool source_drag_active = false;\r\n    ImGuiID source_id = 0;\r\n    ImGuiID source_parent_id = 0;\r\n    if (!(flags & ImGuiDragDropFlags_SourceExtern))\r\n    {\r\n        source_id = g.LastItemData.ID;\r\n        if (source_id != 0)\r\n        {\r\n            // Common path: items with ID\r\n            if (g.ActiveId != source_id)\r\n                return false;\r\n            if (g.ActiveIdMouseButton != -1)\r\n                mouse_button = g.ActiveIdMouseButton;\r\n            if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)\r\n                return false;\r\n            g.ActiveIdAllowOverlap = false;\r\n        }\r\n        else\r\n        {\r\n            // Uncommon path: items without ID\r\n            if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)\r\n                return false;\r\n            if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window))\r\n                return false;\r\n\r\n            // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:\r\n            // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag.\r\n            if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))\r\n            {\r\n                IM_ASSERT(0);\r\n                return false;\r\n            }\r\n\r\n            // Magic fallback to handle items with no assigned ID, e.g. Text(), Image()\r\n            // We build a throwaway ID based on current ID stack + relative AABB of items in window.\r\n            // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING/RESIZINGG OF THE WIDGET, so if your widget moves your dragging operation will be canceled.\r\n            // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.\r\n            // Rely on keeping other window->LastItemXXX fields intact.\r\n            source_id = g.LastItemData.ID = window->GetIDFromRectangle(g.LastItemData.Rect);\r\n            bool is_hovered = ItemHoverable(g.LastItemData.Rect, source_id);\r\n            if (is_hovered && g.IO.MouseClicked[mouse_button])\r\n            {\r\n                SetActiveID(source_id, window);\r\n                FocusWindow(window);\r\n            }\r\n            if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.\r\n                g.ActiveIdAllowOverlap = is_hovered;\r\n        }\r\n        if (g.ActiveId != source_id)\r\n            return false;\r\n        source_parent_id = window->IDStack.back();\r\n        source_drag_active = IsMouseDragging(mouse_button);\r\n\r\n        // Disable navigation and key inputs while dragging + cancel existing request if any\r\n        SetActiveIdUsingNavAndKeys();\r\n    }\r\n    else\r\n    {\r\n        window = NULL;\r\n        source_id = ImHashStr(\"#SourceExtern\");\r\n        source_drag_active = true;\r\n    }\r\n\r\n    if (source_drag_active)\r\n    {\r\n        if (!g.DragDropActive)\r\n        {\r\n            IM_ASSERT(source_id != 0);\r\n            ClearDragDrop();\r\n            ImGuiPayload& payload = g.DragDropPayload;\r\n            payload.SourceId = source_id;\r\n            payload.SourceParentId = source_parent_id;\r\n            g.DragDropActive = true;\r\n            g.DragDropSourceFlags = flags;\r\n            g.DragDropMouseButton = mouse_button;\r\n            if (payload.SourceId == g.ActiveId)\r\n                g.ActiveIdNoClearOnFocusLoss = true;\r\n        }\r\n        g.DragDropSourceFrameCount = g.FrameCount;\r\n        g.DragDropWithinSource = true;\r\n\r\n        if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))\r\n        {\r\n            // Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit)\r\n            // We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents.\r\n            BeginTooltip();\r\n            if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip))\r\n            {\r\n                ImGuiWindow* tooltip_window = g.CurrentWindow;\r\n                tooltip_window->Hidden = tooltip_window->SkipItems = true;\r\n                tooltip_window->HiddenFramesCanSkipItems = 1;\r\n            }\r\n        }\r\n\r\n        if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))\r\n            g.LastItemData.StatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;\r\n\r\n        return true;\r\n    }\r\n    return false;\r\n}\r\n\r\nvoid ImGui::EndDragDropSource()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(g.DragDropActive);\r\n    IM_ASSERT(g.DragDropWithinSource && \"Not after a BeginDragDropSource()?\");\r\n\r\n    if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))\r\n        EndTooltip();\r\n\r\n    // Discard the drag if have not called SetDragDropPayload()\r\n    if (g.DragDropPayload.DataFrameCount == -1)\r\n        ClearDragDrop();\r\n    g.DragDropWithinSource = false;\r\n}\r\n\r\n// Use 'cond' to choose to submit payload on drag start or every frame\r\nbool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiPayload& payload = g.DragDropPayload;\r\n    if (cond == 0)\r\n        cond = ImGuiCond_Always;\r\n\r\n    IM_ASSERT(type != NULL);\r\n    IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && \"Payload type can be at most 32 characters long\");\r\n    IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));\r\n    IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);\r\n    IM_ASSERT(payload.SourceId != 0);                               // Not called between BeginDragDropSource() and EndDragDropSource()\r\n\r\n    if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)\r\n    {\r\n        // Copy payload\r\n        ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType));\r\n        g.DragDropPayloadBufHeap.resize(0);\r\n        if (data_size > sizeof(g.DragDropPayloadBufLocal))\r\n        {\r\n            // Store in heap\r\n            g.DragDropPayloadBufHeap.resize((int)data_size);\r\n            payload.Data = g.DragDropPayloadBufHeap.Data;\r\n            memcpy(payload.Data, data, data_size);\r\n        }\r\n        else if (data_size > 0)\r\n        {\r\n            // Store locally\r\n            memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));\r\n            payload.Data = g.DragDropPayloadBufLocal;\r\n            memcpy(payload.Data, data, data_size);\r\n        }\r\n        else\r\n        {\r\n            payload.Data = NULL;\r\n        }\r\n        payload.DataSize = (int)data_size;\r\n    }\r\n    payload.DataFrameCount = g.FrameCount;\r\n\r\n    // Return whether the payload has been accepted\r\n    return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);\r\n}\r\n\r\nbool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    if (!g.DragDropActive)\r\n        return false;\r\n\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;\r\n    if (hovered_window == NULL || window->RootWindow != hovered_window->RootWindow)\r\n        return false;\r\n    IM_ASSERT(id != 0);\r\n    if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId))\r\n        return false;\r\n    if (window->SkipItems)\r\n        return false;\r\n\r\n    IM_ASSERT(g.DragDropWithinTarget == false);\r\n    g.DragDropTargetRect = bb;\r\n    g.DragDropTargetId = id;\r\n    g.DragDropWithinTarget = true;\r\n    return true;\r\n}\r\n\r\n// We don't use BeginDragDropTargetCustom() and duplicate its code because:\r\n// 1) we use LastItemRectHoveredRect which handles items that pushes a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them.\r\n// 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.\r\n// Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)\r\nbool ImGui::BeginDragDropTarget()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    if (!g.DragDropActive)\r\n        return false;\r\n\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    if (!(g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect))\r\n        return false;\r\n    ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;\r\n    if (hovered_window == NULL || window->RootWindow != hovered_window->RootWindow || window->SkipItems)\r\n        return false;\r\n\r\n    const ImRect& display_rect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? g.LastItemData.DisplayRect : g.LastItemData.Rect;\r\n    ImGuiID id = g.LastItemData.ID;\r\n    if (id == 0)\r\n        id = window->GetIDFromRectangle(display_rect);\r\n    if (g.DragDropPayload.SourceId == id)\r\n        return false;\r\n\r\n    IM_ASSERT(g.DragDropWithinTarget == false);\r\n    g.DragDropTargetRect = display_rect;\r\n    g.DragDropTargetId = id;\r\n    g.DragDropWithinTarget = true;\r\n    return true;\r\n}\r\n\r\nbool ImGui::IsDragDropPayloadBeingAccepted()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    return g.DragDropActive && g.DragDropAcceptIdPrev != 0;\r\n}\r\n\r\nconst ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    ImGuiPayload& payload = g.DragDropPayload;\r\n    IM_ASSERT(g.DragDropActive);                        // Not called between BeginDragDropTarget() and EndDragDropTarget() ?\r\n    IM_ASSERT(payload.DataFrameCount != -1);            // Forgot to call EndDragDropTarget() ?\r\n    if (type != NULL && !payload.IsDataType(type))\r\n        return NULL;\r\n\r\n    // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.\r\n    // NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!\r\n    const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);\r\n    ImRect r = g.DragDropTargetRect;\r\n    float r_surface = r.GetWidth() * r.GetHeight();\r\n    if (r_surface <= g.DragDropAcceptIdCurrRectSurface)\r\n    {\r\n        g.DragDropAcceptFlags = flags;\r\n        g.DragDropAcceptIdCurr = g.DragDropTargetId;\r\n        g.DragDropAcceptIdCurrRectSurface = r_surface;\r\n    }\r\n\r\n    // Render default drop visuals\r\n    // FIXME-DRAGDROP: Settle on a proper default visuals for drop target.\r\n    payload.Preview = was_accepted_previously;\r\n    flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that lives for 1 frame)\r\n    if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview)\r\n        window->DrawList->AddRect(r.Min - ImVec2(3.5f,3.5f), r.Max + ImVec2(3.5f, 3.5f), GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f);\r\n\r\n    g.DragDropAcceptFrameCount = g.FrameCount;\r\n    payload.Delivery = was_accepted_previously && !IsMouseDown(g.DragDropMouseButton); // For extern drag sources affecting os window focus, it's easier to just test !IsMouseDown() instead of IsMouseReleased()\r\n    if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))\r\n        return NULL;\r\n\r\n    return &payload;\r\n}\r\n\r\nconst ImGuiPayload* ImGui::GetDragDropPayload()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    return g.DragDropActive ? &g.DragDropPayload : NULL;\r\n}\r\n\r\n// We don't really use/need this now, but added it for the sake of consistency and because we might need it later.\r\nvoid ImGui::EndDragDropTarget()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(g.DragDropActive);\r\n    IM_ASSERT(g.DragDropWithinTarget);\r\n    g.DragDropWithinTarget = false;\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] LOGGING/CAPTURING\r\n//-----------------------------------------------------------------------------\r\n// All text output from the interface can be captured into tty/file/clipboard.\r\n// By default, tree nodes are automatically opened during logging.\r\n//-----------------------------------------------------------------------------\r\n\r\n// Pass text data straight to log (without being displayed)\r\nstatic inline void LogTextV(ImGuiContext& g, const char* fmt, va_list args)\r\n{\r\n    if (g.LogFile)\r\n    {\r\n        g.LogBuffer.Buf.resize(0);\r\n        g.LogBuffer.appendfv(fmt, args);\r\n        ImFileWrite(g.LogBuffer.c_str(), sizeof(char), (ImU64)g.LogBuffer.size(), g.LogFile);\r\n    }\r\n    else\r\n    {\r\n        g.LogBuffer.appendfv(fmt, args);\r\n    }\r\n}\r\n\r\nvoid ImGui::LogText(const char* fmt, ...)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    if (!g.LogEnabled)\r\n        return;\r\n\r\n    va_list args;\r\n    va_start(args, fmt);\r\n    LogTextV(g, fmt, args);\r\n    va_end(args);\r\n}\r\n\r\nvoid ImGui::LogTextV(const char* fmt, va_list args)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    if (!g.LogEnabled)\r\n        return;\r\n\r\n    LogTextV(g, fmt, args);\r\n}\r\n\r\n// Internal version that takes a position to decide on newline placement and pad items according to their depth.\r\n// We split text into individual lines to add current tree level padding\r\n// FIXME: This code is a little complicated perhaps, considering simplifying the whole system.\r\nvoid ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n\r\n    const char* prefix = g.LogNextPrefix;\r\n    const char* suffix = g.LogNextSuffix;\r\n    g.LogNextPrefix = g.LogNextSuffix = NULL;\r\n\r\n    if (!text_end)\r\n        text_end = FindRenderedTextEnd(text, text_end);\r\n\r\n    const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + g.Style.FramePadding.y + 1);\r\n    if (ref_pos)\r\n        g.LogLinePosY = ref_pos->y;\r\n    if (log_new_line)\r\n    {\r\n        LogText(IM_NEWLINE);\r\n        g.LogLineFirstItem = true;\r\n    }\r\n\r\n    if (prefix)\r\n        LogRenderedText(ref_pos, prefix, prefix + strlen(prefix)); // Calculate end ourself to ensure \"##\" are included here.\r\n\r\n    // Re-adjust padding if we have popped out of our starting depth\r\n    if (g.LogDepthRef > window->DC.TreeDepth)\r\n        g.LogDepthRef = window->DC.TreeDepth;\r\n    const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef);\r\n\r\n    const char* text_remaining = text;\r\n    for (;;)\r\n    {\r\n        // Split the string. Each new line (after a '\\n') is followed by indentation corresponding to the current depth of our log entry.\r\n        // We don't add a trailing \\n yet to allow a subsequent item on the same line to be captured.\r\n        const char* line_start = text_remaining;\r\n        const char* line_end = ImStreolRange(line_start, text_end);\r\n        const bool is_last_line = (line_end == text_end);\r\n        if (line_start != line_end || !is_last_line)\r\n        {\r\n            const int line_length = (int)(line_end - line_start);\r\n            const int indentation = g.LogLineFirstItem ? tree_depth * 4 : 1;\r\n            LogText(\"%*s%.*s\", indentation, \"\", line_length, line_start);\r\n            g.LogLineFirstItem = false;\r\n            if (*line_end == '\\n')\r\n            {\r\n                LogText(IM_NEWLINE);\r\n                g.LogLineFirstItem = true;\r\n            }\r\n        }\r\n        if (is_last_line)\r\n            break;\r\n        text_remaining = line_end + 1;\r\n    }\r\n\r\n    if (suffix)\r\n        LogRenderedText(ref_pos, suffix, suffix + strlen(suffix));\r\n}\r\n\r\n// Start logging/capturing text output\r\nvoid ImGui::LogBegin(ImGuiLogType type, int auto_open_depth)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    IM_ASSERT(g.LogEnabled == false);\r\n    IM_ASSERT(g.LogFile == NULL);\r\n    IM_ASSERT(g.LogBuffer.empty());\r\n    g.LogEnabled = true;\r\n    g.LogType = type;\r\n    g.LogNextPrefix = g.LogNextSuffix = NULL;\r\n    g.LogDepthRef = window->DC.TreeDepth;\r\n    g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault);\r\n    g.LogLinePosY = FLT_MAX;\r\n    g.LogLineFirstItem = true;\r\n}\r\n\r\n// Important: doesn't copy underlying data, use carefully (prefix/suffix must be in scope at the time of the next LogRenderedText)\r\nvoid ImGui::LogSetNextTextDecoration(const char* prefix, const char* suffix)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    g.LogNextPrefix = prefix;\r\n    g.LogNextSuffix = suffix;\r\n}\r\n\r\nvoid ImGui::LogToTTY(int auto_open_depth)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    if (g.LogEnabled)\r\n        return;\r\n    IM_UNUSED(auto_open_depth);\r\n#ifndef IMGUI_DISABLE_TTY_FUNCTIONS\r\n    LogBegin(ImGuiLogType_TTY, auto_open_depth);\r\n    g.LogFile = stdout;\r\n#endif\r\n}\r\n\r\n// Start logging/capturing text output to given file\r\nvoid ImGui::LogToFile(int auto_open_depth, const char* filename)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    if (g.LogEnabled)\r\n        return;\r\n\r\n    // FIXME: We could probably open the file in text mode \"at\", however note that clipboard/buffer logging will still\r\n    // be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE.\r\n    // By opening the file in binary mode \"ab\" we have consistent output everywhere.\r\n    if (!filename)\r\n        filename = g.IO.LogFilename;\r\n    if (!filename || !filename[0])\r\n        return;\r\n    ImFileHandle f = ImFileOpen(filename, \"ab\");\r\n    if (!f)\r\n    {\r\n        IM_ASSERT(0);\r\n        return;\r\n    }\r\n\r\n    LogBegin(ImGuiLogType_File, auto_open_depth);\r\n    g.LogFile = f;\r\n}\r\n\r\n// Start logging/capturing text output to clipboard\r\nvoid ImGui::LogToClipboard(int auto_open_depth)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    if (g.LogEnabled)\r\n        return;\r\n    LogBegin(ImGuiLogType_Clipboard, auto_open_depth);\r\n}\r\n\r\nvoid ImGui::LogToBuffer(int auto_open_depth)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    if (g.LogEnabled)\r\n        return;\r\n    LogBegin(ImGuiLogType_Buffer, auto_open_depth);\r\n}\r\n\r\nvoid ImGui::LogFinish()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    if (!g.LogEnabled)\r\n        return;\r\n\r\n    LogText(IM_NEWLINE);\r\n    switch (g.LogType)\r\n    {\r\n    case ImGuiLogType_TTY:\r\n#ifndef IMGUI_DISABLE_TTY_FUNCTIONS\r\n        fflush(g.LogFile);\r\n#endif\r\n        break;\r\n    case ImGuiLogType_File:\r\n        ImFileClose(g.LogFile);\r\n        break;\r\n    case ImGuiLogType_Buffer:\r\n        break;\r\n    case ImGuiLogType_Clipboard:\r\n        if (!g.LogBuffer.empty())\r\n            SetClipboardText(g.LogBuffer.begin());\r\n        break;\r\n    case ImGuiLogType_None:\r\n        IM_ASSERT(0);\r\n        break;\r\n    }\r\n\r\n    g.LogEnabled = false;\r\n    g.LogType = ImGuiLogType_None;\r\n    g.LogFile = NULL;\r\n    g.LogBuffer.clear();\r\n}\r\n\r\n// Helper to display logging buttons\r\n// FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!)\r\nvoid ImGui::LogButtons()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n\r\n    PushID(\"LogButtons\");\r\n#ifndef IMGUI_DISABLE_TTY_FUNCTIONS\r\n    const bool log_to_tty = Button(\"Log To TTY\"); SameLine();\r\n#else\r\n    const bool log_to_tty = false;\r\n#endif\r\n    const bool log_to_file = Button(\"Log To File\"); SameLine();\r\n    const bool log_to_clipboard = Button(\"Log To Clipboard\"); SameLine();\r\n    PushAllowKeyboardFocus(false);\r\n    SetNextItemWidth(80.0f);\r\n    SliderInt(\"Default Depth\", &g.LogDepthToExpandDefault, 0, 9, NULL);\r\n    PopAllowKeyboardFocus();\r\n    PopID();\r\n\r\n    // Start logging at the end of the function so that the buttons don't appear in the log\r\n    if (log_to_tty)\r\n        LogToTTY();\r\n    if (log_to_file)\r\n        LogToFile();\r\n    if (log_to_clipboard)\r\n        LogToClipboard();\r\n}\r\n\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] SETTINGS\r\n//-----------------------------------------------------------------------------\r\n// - UpdateSettings() [Internal]\r\n// - MarkIniSettingsDirty() [Internal]\r\n// - CreateNewWindowSettings() [Internal]\r\n// - FindWindowSettings() [Internal]\r\n// - FindOrCreateWindowSettings() [Internal]\r\n// - FindSettingsHandler() [Internal]\r\n// - ClearIniSettings() [Internal]\r\n// - LoadIniSettingsFromDisk()\r\n// - LoadIniSettingsFromMemory()\r\n// - SaveIniSettingsToDisk()\r\n// - SaveIniSettingsToMemory()\r\n// - WindowSettingsHandler_***() [Internal]\r\n//-----------------------------------------------------------------------------\r\n\r\n// Called by NewFrame()\r\nvoid ImGui::UpdateSettings()\r\n{\r\n    // Load settings on first frame (if not explicitly loaded manually before)\r\n    ImGuiContext& g = *GImGui;\r\n    if (!g.SettingsLoaded)\r\n    {\r\n        IM_ASSERT(g.SettingsWindows.empty());\r\n        if (g.IO.IniFilename)\r\n            LoadIniSettingsFromDisk(g.IO.IniFilename);\r\n        g.SettingsLoaded = true;\r\n    }\r\n\r\n    // Save settings (with a delay after the last modification, so we don't spam disk too much)\r\n    if (g.SettingsDirtyTimer > 0.0f)\r\n    {\r\n        g.SettingsDirtyTimer -= g.IO.DeltaTime;\r\n        if (g.SettingsDirtyTimer <= 0.0f)\r\n        {\r\n            if (g.IO.IniFilename != NULL)\r\n                SaveIniSettingsToDisk(g.IO.IniFilename);\r\n            else\r\n                g.IO.WantSaveIniSettings = true;  // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.\r\n            g.SettingsDirtyTimer = 0.0f;\r\n        }\r\n    }\r\n}\r\n\r\nvoid ImGui::MarkIniSettingsDirty()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    if (g.SettingsDirtyTimer <= 0.0f)\r\n        g.SettingsDirtyTimer = g.IO.IniSavingRate;\r\n}\r\n\r\nvoid ImGui::MarkIniSettingsDirty(ImGuiWindow* window)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))\r\n        if (g.SettingsDirtyTimer <= 0.0f)\r\n            g.SettingsDirtyTimer = g.IO.IniSavingRate;\r\n}\r\n\r\nImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n\r\n#if !IMGUI_DEBUG_INI_SETTINGS\r\n    // Skip to the \"###\" marker if any. We don't skip past to match the behavior of GetID()\r\n    // Preserve the full string when IMGUI_DEBUG_INI_SETTINGS is set to make .ini inspection easier.\r\n    if (const char* p = strstr(name, \"###\"))\r\n        name = p;\r\n#endif\r\n    const size_t name_len = strlen(name);\r\n\r\n    // Allocate chunk\r\n    const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1;\r\n    ImGuiWindowSettings* settings = g.SettingsWindows.alloc_chunk(chunk_size);\r\n    IM_PLACEMENT_NEW(settings) ImGuiWindowSettings();\r\n    settings->ID = ImHashStr(name, name_len);\r\n    memcpy(settings->GetName(), name, name_len + 1);   // Store with zero terminator\r\n\r\n    return settings;\r\n}\r\n\r\nImGuiWindowSettings* ImGui::FindWindowSettings(ImGuiID id)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))\r\n        if (settings->ID == id)\r\n            return settings;\r\n    return NULL;\r\n}\r\n\r\nImGuiWindowSettings* ImGui::FindOrCreateWindowSettings(const char* name)\r\n{\r\n    if (ImGuiWindowSettings* settings = FindWindowSettings(ImHashStr(name)))\r\n        return settings;\r\n    return CreateNewWindowSettings(name);\r\n}\r\n\r\nImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    const ImGuiID type_hash = ImHashStr(type_name);\r\n    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)\r\n        if (g.SettingsHandlers[handler_n].TypeHash == type_hash)\r\n            return &g.SettingsHandlers[handler_n];\r\n    return NULL;\r\n}\r\n\r\nvoid ImGui::ClearIniSettings()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    g.SettingsIniData.clear();\r\n    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)\r\n        if (g.SettingsHandlers[handler_n].ClearAllFn)\r\n            g.SettingsHandlers[handler_n].ClearAllFn(&g, &g.SettingsHandlers[handler_n]);\r\n}\r\n\r\nvoid ImGui::LoadIniSettingsFromDisk(const char* ini_filename)\r\n{\r\n    size_t file_data_size = 0;\r\n    char* file_data = (char*)ImFileLoadToMemory(ini_filename, \"rb\", &file_data_size);\r\n    if (!file_data)\r\n        return;\r\n    LoadIniSettingsFromMemory(file_data, (size_t)file_data_size);\r\n    IM_FREE(file_data);\r\n}\r\n\r\n// Zero-tolerance, no error reporting, cheap .ini parsing\r\nvoid ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(g.Initialized);\r\n    //IM_ASSERT(!g.WithinFrameScope && \"Cannot be called between NewFrame() and EndFrame()\");\r\n    //IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0);\r\n\r\n    // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter).\r\n    // For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy..\r\n    if (ini_size == 0)\r\n        ini_size = strlen(ini_data);\r\n    g.SettingsIniData.Buf.resize((int)ini_size + 1);\r\n    char* const buf = g.SettingsIniData.Buf.Data;\r\n    char* const buf_end = buf + ini_size;\r\n    memcpy(buf, ini_data, ini_size);\r\n    buf_end[0] = 0;\r\n\r\n    // Call pre-read handlers\r\n    // Some types will clear their data (e.g. dock information) some types will allow merge/override (window)\r\n    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)\r\n        if (g.SettingsHandlers[handler_n].ReadInitFn)\r\n            g.SettingsHandlers[handler_n].ReadInitFn(&g, &g.SettingsHandlers[handler_n]);\r\n\r\n    void* entry_data = NULL;\r\n    ImGuiSettingsHandler* entry_handler = NULL;\r\n\r\n    char* line_end = NULL;\r\n    for (char* line = buf; line < buf_end; line = line_end + 1)\r\n    {\r\n        // Skip new lines markers, then find end of the line\r\n        while (*line == '\\n' || *line == '\\r')\r\n            line++;\r\n        line_end = line;\r\n        while (line_end < buf_end && *line_end != '\\n' && *line_end != '\\r')\r\n            line_end++;\r\n        line_end[0] = 0;\r\n        if (line[0] == ';')\r\n            continue;\r\n        if (line[0] == '[' && line_end > line && line_end[-1] == ']')\r\n        {\r\n            // Parse \"[Type][Name]\". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.\r\n            line_end[-1] = 0;\r\n            const char* name_end = line_end - 1;\r\n            const char* type_start = line + 1;\r\n            char* type_end = (char*)(void*)ImStrchrRange(type_start, name_end, ']');\r\n            const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;\r\n            if (!type_end || !name_start)\r\n                continue;\r\n            *type_end = 0; // Overwrite first ']'\r\n            name_start++;  // Skip second '['\r\n            entry_handler = FindSettingsHandler(type_start);\r\n            entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;\r\n        }\r\n        else if (entry_handler != NULL && entry_data != NULL)\r\n        {\r\n            // Let type handler parse the line\r\n            entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);\r\n        }\r\n    }\r\n    g.SettingsLoaded = true;\r\n\r\n    // [DEBUG] Restore untouched copy so it can be browsed in Metrics (not strictly necessary)\r\n    memcpy(buf, ini_data, ini_size);\r\n\r\n    // Call post-read handlers\r\n    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)\r\n        if (g.SettingsHandlers[handler_n].ApplyAllFn)\r\n            g.SettingsHandlers[handler_n].ApplyAllFn(&g, &g.SettingsHandlers[handler_n]);\r\n}\r\n\r\nvoid ImGui::SaveIniSettingsToDisk(const char* ini_filename)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    g.SettingsDirtyTimer = 0.0f;\r\n    if (!ini_filename)\r\n        return;\r\n\r\n    size_t ini_data_size = 0;\r\n    const char* ini_data = SaveIniSettingsToMemory(&ini_data_size);\r\n    ImFileHandle f = ImFileOpen(ini_filename, \"wt\");\r\n    if (!f)\r\n        return;\r\n    ImFileWrite(ini_data, sizeof(char), ini_data_size, f);\r\n    ImFileClose(f);\r\n}\r\n\r\n// Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer\r\nconst char* ImGui::SaveIniSettingsToMemory(size_t* out_size)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    g.SettingsDirtyTimer = 0.0f;\r\n    g.SettingsIniData.Buf.resize(0);\r\n    g.SettingsIniData.Buf.push_back(0);\r\n    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)\r\n    {\r\n        ImGuiSettingsHandler* handler = &g.SettingsHandlers[handler_n];\r\n        handler->WriteAllFn(&g, handler, &g.SettingsIniData);\r\n    }\r\n    if (out_size)\r\n        *out_size = (size_t)g.SettingsIniData.size();\r\n    return g.SettingsIniData.c_str();\r\n}\r\n\r\nstatic void WindowSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)\r\n{\r\n    ImGuiContext& g = *ctx;\r\n    for (int i = 0; i != g.Windows.Size; i++)\r\n        g.Windows[i]->SettingsOffset = -1;\r\n    g.SettingsWindows.clear();\r\n}\r\n\r\nstatic void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)\r\n{\r\n    ImGuiWindowSettings* settings = ImGui::FindOrCreateWindowSettings(name);\r\n    ImGuiID id = settings->ID;\r\n    *settings = ImGuiWindowSettings(); // Clear existing if recycling previous entry\r\n    settings->ID = id;\r\n    settings->WantApply = true;\r\n    return (void*)settings;\r\n}\r\n\r\nstatic void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)\r\n{\r\n    ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;\r\n    int x, y;\r\n    int i;\r\n    if (sscanf(line, \"Pos=%i,%i\", &x, &y) == 2)         { settings->Pos = ImVec2ih((short)x, (short)y); }\r\n    else if (sscanf(line, \"Size=%i,%i\", &x, &y) == 2)   { settings->Size = ImVec2ih((short)x, (short)y); }\r\n    else if (sscanf(line, \"Collapsed=%d\", &i) == 1)     { settings->Collapsed = (i != 0); }\r\n}\r\n\r\n// Apply to existing windows (if any)\r\nstatic void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)\r\n{\r\n    ImGuiContext& g = *ctx;\r\n    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))\r\n        if (settings->WantApply)\r\n        {\r\n            if (ImGuiWindow* window = ImGui::FindWindowByID(settings->ID))\r\n                ApplyWindowSettings(window, settings);\r\n            settings->WantApply = false;\r\n        }\r\n}\r\n\r\nstatic void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)\r\n{\r\n    // Gather data from windows that were active during this session\r\n    // (if a window wasn't opened in this session we preserve its settings)\r\n    ImGuiContext& g = *ctx;\r\n    for (int i = 0; i != g.Windows.Size; i++)\r\n    {\r\n        ImGuiWindow* window = g.Windows[i];\r\n        if (window->Flags & ImGuiWindowFlags_NoSavedSettings)\r\n            continue;\r\n\r\n        ImGuiWindowSettings* settings = (window->SettingsOffset != -1) ? g.SettingsWindows.ptr_from_offset(window->SettingsOffset) : ImGui::FindWindowSettings(window->ID);\r\n        if (!settings)\r\n        {\r\n            settings = ImGui::CreateNewWindowSettings(window->Name);\r\n            window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);\r\n        }\r\n        IM_ASSERT(settings->ID == window->ID);\r\n        settings->Pos = ImVec2ih(window->Pos);\r\n        settings->Size = ImVec2ih(window->SizeFull);\r\n\r\n        settings->Collapsed = window->Collapsed;\r\n    }\r\n\r\n    // Write to text buffer\r\n    buf->reserve(buf->size() + g.SettingsWindows.size() * 6); // ballpark reserve\r\n    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))\r\n    {\r\n        const char* settings_name = settings->GetName();\r\n        buf->appendf(\"[%s][%s]\\n\", handler->TypeName, settings_name);\r\n        buf->appendf(\"Pos=%d,%d\\n\", settings->Pos.x, settings->Pos.y);\r\n        buf->appendf(\"Size=%d,%d\\n\", settings->Size.x, settings->Size.y);\r\n        buf->appendf(\"Collapsed=%d\\n\", settings->Collapsed);\r\n        buf->append(\"\\n\");\r\n    }\r\n}\r\n\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] VIEWPORTS, PLATFORM WINDOWS\r\n//-----------------------------------------------------------------------------\r\n// - GetMainViewport()\r\n// - UpdateViewportsNewFrame() [Internal]\r\n// (this section is more complete in the 'docking' branch)\r\n//-----------------------------------------------------------------------------\r\n\r\nImGuiViewport* ImGui::GetMainViewport()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    return g.Viewports[0];\r\n}\r\n\r\n// Update viewports and monitor infos\r\nstatic void ImGui::UpdateViewportsNewFrame()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(g.Viewports.Size == 1);\r\n\r\n    // Update main viewport with current platform position.\r\n    // FIXME-VIEWPORT: Size is driven by backend/user code for backward-compatibility but we should aim to make this more consistent.\r\n    ImGuiViewportP* main_viewport = g.Viewports[0];\r\n    main_viewport->Flags = ImGuiViewportFlags_IsPlatformWindow | ImGuiViewportFlags_OwnedByApp;\r\n    main_viewport->Pos = ImVec2(0.0f, 0.0f);\r\n    main_viewport->Size = g.IO.DisplaySize;\r\n\r\n    for (int n = 0; n < g.Viewports.Size; n++)\r\n    {\r\n        ImGuiViewportP* viewport = g.Viewports[n];\r\n\r\n        // Lock down space taken by menu bars and status bars, reset the offset for fucntions like BeginMainMenuBar() to alter them again.\r\n        viewport->WorkOffsetMin = viewport->BuildWorkOffsetMin;\r\n        viewport->WorkOffsetMax = viewport->BuildWorkOffsetMax;\r\n        viewport->BuildWorkOffsetMin = viewport->BuildWorkOffsetMax = ImVec2(0.0f, 0.0f);\r\n        viewport->UpdateWorkRect();\r\n    }\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] DOCKING\r\n//-----------------------------------------------------------------------------\r\n\r\n// (this section is filled in the 'docking' branch)\r\n\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] PLATFORM DEPENDENT HELPERS\r\n//-----------------------------------------------------------------------------\r\n\r\n#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)\r\n\r\n#ifdef _MSC_VER\r\n#pragma comment(lib, \"user32\")\r\n#pragma comment(lib, \"kernel32\")\r\n#endif\r\n\r\n// Win32 clipboard implementation\r\n// We use g.ClipboardHandlerData for temporary storage to ensure it is freed on Shutdown()\r\nstatic const char* GetClipboardTextFn_DefaultImpl(void*)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    g.ClipboardHandlerData.clear();\r\n    if (!::OpenClipboard(NULL))\r\n        return NULL;\r\n    HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT);\r\n    if (wbuf_handle == NULL)\r\n    {\r\n        ::CloseClipboard();\r\n        return NULL;\r\n    }\r\n    if (const WCHAR* wbuf_global = (const WCHAR*)::GlobalLock(wbuf_handle))\r\n    {\r\n        int buf_len = ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, NULL, 0, NULL, NULL);\r\n        g.ClipboardHandlerData.resize(buf_len);\r\n        ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, g.ClipboardHandlerData.Data, buf_len, NULL, NULL);\r\n    }\r\n    ::GlobalUnlock(wbuf_handle);\r\n    ::CloseClipboard();\r\n    return g.ClipboardHandlerData.Data;\r\n}\r\n\r\nstatic void SetClipboardTextFn_DefaultImpl(void*, const char* text)\r\n{\r\n    if (!::OpenClipboard(NULL))\r\n        return;\r\n    const int wbuf_length = ::MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0);\r\n    HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(WCHAR));\r\n    if (wbuf_handle == NULL)\r\n    {\r\n        ::CloseClipboard();\r\n        return;\r\n    }\r\n    WCHAR* wbuf_global = (WCHAR*)::GlobalLock(wbuf_handle);\r\n    ::MultiByteToWideChar(CP_UTF8, 0, text, -1, wbuf_global, wbuf_length);\r\n    ::GlobalUnlock(wbuf_handle);\r\n    ::EmptyClipboard();\r\n    if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL)\r\n        ::GlobalFree(wbuf_handle);\r\n    ::CloseClipboard();\r\n}\r\n\r\n#elif defined(__APPLE__) && TARGET_OS_OSX && defined(IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS)\r\n\r\n#include <Carbon/Carbon.h>  // Use old API to avoid need for separate .mm file\r\nstatic PasteboardRef main_clipboard = 0;\r\n\r\n// OSX clipboard implementation\r\n// If you enable this you will need to add '-framework ApplicationServices' to your linker command-line!\r\nstatic void SetClipboardTextFn_DefaultImpl(void*, const char* text)\r\n{\r\n    if (!main_clipboard)\r\n        PasteboardCreate(kPasteboardClipboard, &main_clipboard);\r\n    PasteboardClear(main_clipboard);\r\n    CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, strlen(text));\r\n    if (cf_data)\r\n    {\r\n        PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR(\"public.utf8-plain-text\"), cf_data, 0);\r\n        CFRelease(cf_data);\r\n    }\r\n}\r\n\r\nstatic const char* GetClipboardTextFn_DefaultImpl(void*)\r\n{\r\n    if (!main_clipboard)\r\n        PasteboardCreate(kPasteboardClipboard, &main_clipboard);\r\n    PasteboardSynchronize(main_clipboard);\r\n\r\n    ItemCount item_count = 0;\r\n    PasteboardGetItemCount(main_clipboard, &item_count);\r\n    for (ItemCount i = 0; i < item_count; i++)\r\n    {\r\n        PasteboardItemID item_id = 0;\r\n        PasteboardGetItemIdentifier(main_clipboard, i + 1, &item_id);\r\n        CFArrayRef flavor_type_array = 0;\r\n        PasteboardCopyItemFlavors(main_clipboard, item_id, &flavor_type_array);\r\n        for (CFIndex j = 0, nj = CFArrayGetCount(flavor_type_array); j < nj; j++)\r\n        {\r\n            CFDataRef cf_data;\r\n            if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR(\"public.utf8-plain-text\"), &cf_data) == noErr)\r\n            {\r\n                ImGuiContext& g = *GImGui;\r\n                g.ClipboardHandlerData.clear();\r\n                int length = (int)CFDataGetLength(cf_data);\r\n                g.ClipboardHandlerData.resize(length + 1);\r\n                CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)g.ClipboardHandlerData.Data);\r\n                g.ClipboardHandlerData[length] = 0;\r\n                CFRelease(cf_data);\r\n                return g.ClipboardHandlerData.Data;\r\n            }\r\n        }\r\n    }\r\n    return NULL;\r\n}\r\n\r\n#else\r\n\r\n// Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers.\r\nstatic const char* GetClipboardTextFn_DefaultImpl(void*)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    return g.ClipboardHandlerData.empty() ? NULL : g.ClipboardHandlerData.begin();\r\n}\r\n\r\nstatic void SetClipboardTextFn_DefaultImpl(void*, const char* text)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    g.ClipboardHandlerData.clear();\r\n    const char* text_end = text + strlen(text);\r\n    g.ClipboardHandlerData.resize((int)(text_end - text) + 1);\r\n    memcpy(&g.ClipboardHandlerData[0], text, (size_t)(text_end - text));\r\n    g.ClipboardHandlerData[(int)(text_end - text)] = 0;\r\n}\r\n\r\n#endif\r\n\r\n// Win32 API IME support (for Asian languages, etc.)\r\n#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)\r\n\r\n#include <imm.h>\r\n#ifdef _MSC_VER\r\n#pragma comment(lib, \"imm32\")\r\n#endif\r\n\r\nstatic void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data)\r\n{\r\n    // Notify OS Input Method Editor of text input position\r\n    HWND hwnd = (HWND)viewport->PlatformHandleRaw;\r\n#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS\r\n    if (hwnd == 0)\r\n        hwnd = (HWND)ImGui::GetIO().ImeWindowHandle;\r\n#endif\r\n    if (hwnd == 0)\r\n        return;\r\n\r\n    ::ImmAssociateContextEx(hwnd, NULL, data->WantVisible ? IACE_DEFAULT : 0);\r\n\r\n    if (HIMC himc = ::ImmGetContext(hwnd))\r\n    {\r\n        COMPOSITIONFORM composition_form = {};\r\n        composition_form.ptCurrentPos.x = (LONG)data->InputPos.x;\r\n        composition_form.ptCurrentPos.y = (LONG)data->InputPos.y;\r\n        composition_form.dwStyle = CFS_FORCE_POSITION;\r\n        ::ImmSetCompositionWindow(himc, &composition_form);\r\n        CANDIDATEFORM candidate_form = {};\r\n        candidate_form.dwStyle = CFS_CANDIDATEPOS;\r\n        candidate_form.ptCurrentPos.x = (LONG)data->InputPos.x;\r\n        candidate_form.ptCurrentPos.y = (LONG)data->InputPos.y;\r\n        ::ImmSetCandidateWindow(himc, &candidate_form);\r\n        ::ImmReleaseContext(hwnd, himc);\r\n    }\r\n}\r\n\r\n#else\r\n\r\nstatic void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport*, ImGuiPlatformImeData*) {}\r\n\r\n#endif\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] METRICS/DEBUGGER WINDOW\r\n//-----------------------------------------------------------------------------\r\n// - RenderViewportThumbnail() [Internal]\r\n// - RenderViewportsThumbnails() [Internal]\r\n// - MetricsHelpMarker() [Internal]\r\n// - ShowMetricsWindow()\r\n// - DebugNodeColumns() [Internal]\r\n// - DebugNodeDrawList() [Internal]\r\n// - DebugNodeDrawCmdShowMeshAndBoundingBox() [Internal]\r\n// - DebugNodeStorage() [Internal]\r\n// - DebugNodeTabBar() [Internal]\r\n// - DebugNodeViewport() [Internal]\r\n// - DebugNodeWindow() [Internal]\r\n// - DebugNodeWindowSettings() [Internal]\r\n// - DebugNodeWindowsList() [Internal]\r\n// - DebugNodeWindowsListByBeginStackParent() [Internal]\r\n//-----------------------------------------------------------------------------\r\n\r\n#ifndef IMGUI_DISABLE_METRICS_WINDOW\r\n\r\nvoid ImGui::DebugRenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n\r\n    ImVec2 scale = bb.GetSize() / viewport->Size;\r\n    ImVec2 off = bb.Min - viewport->Pos * scale;\r\n    float alpha_mul = 1.0f;\r\n    window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul * 0.40f));\r\n    for (int i = 0; i != g.Windows.Size; i++)\r\n    {\r\n        ImGuiWindow* thumb_window = g.Windows[i];\r\n        if (!thumb_window->WasActive || (thumb_window->Flags & ImGuiWindowFlags_ChildWindow))\r\n            continue;\r\n\r\n        ImRect thumb_r = thumb_window->Rect();\r\n        ImRect title_r = thumb_window->TitleBarRect();\r\n        thumb_r = ImRect(ImFloor(off + thumb_r.Min * scale), ImFloor(off +  thumb_r.Max * scale));\r\n        title_r = ImRect(ImFloor(off + title_r.Min * scale), ImFloor(off +  ImVec2(title_r.Max.x, title_r.Min.y) * scale) + ImVec2(0,5)); // Exaggerate title bar height\r\n        thumb_r.ClipWithFull(bb);\r\n        title_r.ClipWithFull(bb);\r\n        const bool window_is_focused = (g.NavWindow && thumb_window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight);\r\n        window->DrawList->AddRectFilled(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_WindowBg, alpha_mul));\r\n        window->DrawList->AddRectFilled(title_r.Min, title_r.Max, GetColorU32(window_is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg, alpha_mul));\r\n        window->DrawList->AddRect(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_Border, alpha_mul));\r\n        window->DrawList->AddText(g.Font, g.FontSize * 1.0f, title_r.Min, GetColorU32(ImGuiCol_Text, alpha_mul), thumb_window->Name, FindRenderedTextEnd(thumb_window->Name));\r\n    }\r\n    draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul));\r\n}\r\n\r\nstatic void RenderViewportsThumbnails()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n\r\n    // We don't display full monitor bounds (we could, but it often looks awkward), instead we display just enough to cover all of our viewports.\r\n    float SCALE = 1.0f / 8.0f;\r\n    ImRect bb_full(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);\r\n    for (int n = 0; n < g.Viewports.Size; n++)\r\n        bb_full.Add(g.Viewports[n]->GetMainRect());\r\n    ImVec2 p = window->DC.CursorPos;\r\n    ImVec2 off = p - bb_full.Min * SCALE;\r\n    for (int n = 0; n < g.Viewports.Size; n++)\r\n    {\r\n        ImGuiViewportP* viewport = g.Viewports[n];\r\n        ImRect viewport_draw_bb(off + (viewport->Pos) * SCALE, off + (viewport->Pos + viewport->Size) * SCALE);\r\n        ImGui::DebugRenderViewportThumbnail(window->DrawList, viewport, viewport_draw_bb);\r\n    }\r\n    ImGui::Dummy(bb_full.GetSize() * SCALE);\r\n}\r\n\r\n// Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds.\r\nstatic void MetricsHelpMarker(const char* desc)\r\n{\r\n    ImGui::TextDisabled(\"(?)\");\r\n    if (ImGui::IsItemHovered())\r\n    {\r\n        ImGui::BeginTooltip();\r\n        ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);\r\n        ImGui::TextUnformatted(desc);\r\n        ImGui::PopTextWrapPos();\r\n        ImGui::EndTooltip();\r\n    }\r\n}\r\n\r\n#ifndef IMGUI_DISABLE_DEMO_WINDOWS\r\nnamespace ImGui { void ShowFontAtlas(ImFontAtlas* atlas); }\r\n#endif\r\n\r\nvoid ImGui::ShowMetricsWindow(bool* p_open)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiIO& io = g.IO;\r\n    ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;\r\n    if (cfg->ShowStackTool)\r\n        ShowStackToolWindow(&cfg->ShowStackTool);\r\n\r\n    if (!Begin(\"Dear ImGui Metrics/Debugger\", p_open) || GetCurrentWindow()->BeginCount > 1)\r\n    {\r\n        End();\r\n        return;\r\n    }\r\n\r\n    // Basic info\r\n    Text(\"Dear ImGui %s\", GetVersion());\r\n    Text(\"Application average %.3f ms/frame (%.1f FPS)\", 1000.0f / io.Framerate, io.Framerate);\r\n    Text(\"%d vertices, %d indices (%d triangles)\", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);\r\n    Text(\"%d visible windows, %d active allocations\", io.MetricsRenderWindows, io.MetricsActiveAllocations);\r\n    //SameLine(); if (SmallButton(\"GC\")) { g.GcCompactAll = true; }\r\n\r\n    Separator();\r\n\r\n    // Debugging enums\r\n    enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentIdeal, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type\r\n    const char* wrt_rects_names[WRT_Count] = { \"OuterRect\", \"OuterRectClipped\", \"InnerRect\", \"InnerClipRect\", \"WorkRect\", \"Content\", \"ContentIdeal\", \"ContentRegionRect\" };\r\n    enum { TRT_OuterRect, TRT_InnerRect, TRT_WorkRect, TRT_HostClipRect, TRT_InnerClipRect, TRT_BackgroundClipRect, TRT_ColumnsRect, TRT_ColumnsWorkRect, TRT_ColumnsClipRect, TRT_ColumnsContentHeadersUsed, TRT_ColumnsContentHeadersIdeal, TRT_ColumnsContentFrozen, TRT_ColumnsContentUnfrozen, TRT_Count }; // Tables Rect Type\r\n    const char* trt_rects_names[TRT_Count] = { \"OuterRect\", \"InnerRect\", \"WorkRect\", \"HostClipRect\", \"InnerClipRect\", \"BackgroundClipRect\", \"ColumnsRect\", \"ColumnsWorkRect\", \"ColumnsClipRect\", \"ColumnsContentHeadersUsed\", \"ColumnsContentHeadersIdeal\", \"ColumnsContentFrozen\", \"ColumnsContentUnfrozen\" };\r\n    if (cfg->ShowWindowsRectsType < 0)\r\n        cfg->ShowWindowsRectsType = WRT_WorkRect;\r\n    if (cfg->ShowTablesRectsType < 0)\r\n        cfg->ShowTablesRectsType = TRT_WorkRect;\r\n\r\n    struct Funcs\r\n    {\r\n        static ImRect GetTableRect(ImGuiTable* table, int rect_type, int n)\r\n        {\r\n            if (rect_type == TRT_OuterRect)                     { return table->OuterRect; }\r\n            else if (rect_type == TRT_InnerRect)                { return table->InnerRect; }\r\n            else if (rect_type == TRT_WorkRect)                 { return table->WorkRect; }\r\n            else if (rect_type == TRT_HostClipRect)             { return table->HostClipRect; }\r\n            else if (rect_type == TRT_InnerClipRect)            { return table->InnerClipRect; }\r\n            else if (rect_type == TRT_BackgroundClipRect)       { return table->BgClipRect; }\r\n            else if (rect_type == TRT_ColumnsRect)              { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MaxX, table->InnerClipRect.Min.y + table->LastOuterHeight); }\r\n            else if (rect_type == TRT_ColumnsWorkRect)          { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->WorkRect.Min.y, c->WorkMaxX, table->WorkRect.Max.y); }\r\n            else if (rect_type == TRT_ColumnsClipRect)          { ImGuiTableColumn* c = &table->Columns[n]; return c->ClipRect; }\r\n            else if (rect_type == TRT_ColumnsContentHeadersUsed){ ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersUsed, table->InnerClipRect.Min.y + table->LastFirstRowHeight); } // Note: y1/y2 not always accurate\r\n            else if (rect_type == TRT_ColumnsContentHeadersIdeal){ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersIdeal, table->InnerClipRect.Min.y + table->LastFirstRowHeight); }\r\n            else if (rect_type == TRT_ColumnsContentFrozen)     { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXFrozen, table->InnerClipRect.Min.y + table->LastFirstRowHeight); }\r\n            else if (rect_type == TRT_ColumnsContentUnfrozen)   { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y + table->LastFirstRowHeight, c->ContentMaxXUnfrozen, table->InnerClipRect.Max.y); }\r\n            IM_ASSERT(0);\r\n            return ImRect();\r\n        }\r\n\r\n        static ImRect GetWindowRect(ImGuiWindow* window, int rect_type)\r\n        {\r\n            if (rect_type == WRT_OuterRect)                 { return window->Rect(); }\r\n            else if (rect_type == WRT_OuterRectClipped)     { return window->OuterRectClipped; }\r\n            else if (rect_type == WRT_InnerRect)            { return window->InnerRect; }\r\n            else if (rect_type == WRT_InnerClipRect)        { return window->InnerClipRect; }\r\n            else if (rect_type == WRT_WorkRect)             { return window->WorkRect; }\r\n            else if (rect_type == WRT_Content)       { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); }\r\n            else if (rect_type == WRT_ContentIdeal)         { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSizeIdeal); }\r\n            else if (rect_type == WRT_ContentRegionRect)    { return window->ContentRegionRect; }\r\n            IM_ASSERT(0);\r\n            return ImRect();\r\n        }\r\n    };\r\n\r\n    // Tools\r\n    if (TreeNode(\"Tools\"))\r\n    {\r\n        // Stack Tool is your best friend!\r\n        Checkbox(\"Show stack tool\", &cfg->ShowStackTool);\r\n        SameLine();\r\n        MetricsHelpMarker(\"You can also call ImGui::ShowStackToolWindow() from your code.\");\r\n\r\n        Checkbox(\"Show windows begin order\", &cfg->ShowWindowsBeginOrder);\r\n        Checkbox(\"Show windows rectangles\", &cfg->ShowWindowsRects);\r\n        SameLine();\r\n        SetNextItemWidth(GetFontSize() * 12);\r\n        cfg->ShowWindowsRects |= Combo(\"##show_windows_rect_type\", &cfg->ShowWindowsRectsType, wrt_rects_names, WRT_Count, WRT_Count);\r\n        if (cfg->ShowWindowsRects && g.NavWindow != NULL)\r\n        {\r\n            BulletText(\"'%s':\", g.NavWindow->Name);\r\n            Indent();\r\n            for (int rect_n = 0; rect_n < WRT_Count; rect_n++)\r\n            {\r\n                ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n);\r\n                Text(\"(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s\", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), wrt_rects_names[rect_n]);\r\n            }\r\n            Unindent();\r\n        }\r\n\r\n        Checkbox(\"Show tables rectangles\", &cfg->ShowTablesRects);\r\n        SameLine();\r\n        SetNextItemWidth(GetFontSize() * 12);\r\n        cfg->ShowTablesRects |= Combo(\"##show_table_rects_type\", &cfg->ShowTablesRectsType, trt_rects_names, TRT_Count, TRT_Count);\r\n        if (cfg->ShowTablesRects && g.NavWindow != NULL)\r\n        {\r\n            for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)\r\n            {\r\n                ImGuiTable* table = g.Tables.TryGetMapData(table_n);\r\n                if (table == NULL || table->LastFrameActive < g.FrameCount - 1 || (table->OuterWindow != g.NavWindow && table->InnerWindow != g.NavWindow))\r\n                    continue;\r\n\r\n                BulletText(\"Table 0x%08X (%d columns, in '%s')\", table->ID, table->ColumnsCount, table->OuterWindow->Name);\r\n                if (IsItemHovered())\r\n                    GetForegroundDrawList()->AddRect(table->OuterRect.Min - ImVec2(1, 1), table->OuterRect.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);\r\n                Indent();\r\n                char buf[128];\r\n                for (int rect_n = 0; rect_n < TRT_Count; rect_n++)\r\n                {\r\n                    if (rect_n >= TRT_ColumnsRect)\r\n                    {\r\n                        if (rect_n != TRT_ColumnsRect && rect_n != TRT_ColumnsClipRect)\r\n                            continue;\r\n                        for (int column_n = 0; column_n < table->ColumnsCount; column_n++)\r\n                        {\r\n                            ImRect r = Funcs::GetTableRect(table, rect_n, column_n);\r\n                            ImFormatString(buf, IM_ARRAYSIZE(buf), \"(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) Col %d %s\", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), column_n, trt_rects_names[rect_n]);\r\n                            Selectable(buf);\r\n                            if (IsItemHovered())\r\n                                GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);\r\n                        }\r\n                    }\r\n                    else\r\n                    {\r\n                        ImRect r = Funcs::GetTableRect(table, rect_n, -1);\r\n                        ImFormatString(buf, IM_ARRAYSIZE(buf), \"(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s\", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), trt_rects_names[rect_n]);\r\n                        Selectable(buf);\r\n                        if (IsItemHovered())\r\n                            GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);\r\n                    }\r\n                }\r\n                Unindent();\r\n            }\r\n        }\r\n\r\n        // The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted.\r\n        if (Button(\"Item Picker..\"))\r\n            DebugStartItemPicker();\r\n        SameLine();\r\n        MetricsHelpMarker(\"Will call the IM_DEBUG_BREAK() macro to break in debugger.\\nWarning: If you don't have a debugger attached, this will probably crash.\");\r\n\r\n        TreePop();\r\n    }\r\n\r\n    // Windows\r\n    if (TreeNode(\"Windows\", \"Windows (%d)\", g.Windows.Size))\r\n    {\r\n        //SetNextItemOpen(true, ImGuiCond_Once);\r\n        DebugNodeWindowsList(&g.Windows, \"By display order\");\r\n        DebugNodeWindowsList(&g.WindowsFocusOrder, \"By focus order (root windows)\");\r\n        if (TreeNode(\"By submission order (begin stack)\"))\r\n        {\r\n            // Here we display windows in their submitted order/hierarchy, however note that the Begin stack doesn't constitute a Parent<>Child relationship!\r\n            ImVector<ImGuiWindow*>& temp_buffer = g.WindowsTempSortBuffer;\r\n            temp_buffer.resize(0);\r\n            for (int i = 0; i < g.Windows.Size; i++)\r\n                if (g.Windows[i]->LastFrameActive + 1 >= g.FrameCount)\r\n                    temp_buffer.push_back(g.Windows[i]);\r\n            struct Func { static int IMGUI_CDECL WindowComparerByBeginOrder(const void* lhs, const void* rhs) { return ((int)(*(const ImGuiWindow* const *)lhs)->BeginOrderWithinContext - (*(const ImGuiWindow* const*)rhs)->BeginOrderWithinContext); } };\r\n            ImQsort(temp_buffer.Data, (size_t)temp_buffer.Size, sizeof(ImGuiWindow*), Func::WindowComparerByBeginOrder);\r\n            DebugNodeWindowsListByBeginStackParent(temp_buffer.Data, temp_buffer.Size, NULL);\r\n            TreePop();\r\n        }\r\n\r\n        TreePop();\r\n    }\r\n\r\n    // DrawLists\r\n    int drawlist_count = 0;\r\n    for (int viewport_i = 0; viewport_i < g.Viewports.Size; viewport_i++)\r\n        drawlist_count += g.Viewports[viewport_i]->DrawDataBuilder.GetDrawListCount();\r\n    if (TreeNode(\"DrawLists\", \"DrawLists (%d)\", drawlist_count))\r\n    {\r\n        Checkbox(\"Show ImDrawCmd mesh when hovering\", &cfg->ShowDrawCmdMesh);\r\n        Checkbox(\"Show ImDrawCmd bounding boxes when hovering\", &cfg->ShowDrawCmdBoundingBoxes);\r\n        for (int viewport_i = 0; viewport_i < g.Viewports.Size; viewport_i++)\r\n        {\r\n            ImGuiViewportP* viewport = g.Viewports[viewport_i];\r\n            for (int layer_i = 0; layer_i < IM_ARRAYSIZE(viewport->DrawDataBuilder.Layers); layer_i++)\r\n                for (int draw_list_i = 0; draw_list_i < viewport->DrawDataBuilder.Layers[layer_i].Size; draw_list_i++)\r\n                    DebugNodeDrawList(NULL, viewport->DrawDataBuilder.Layers[layer_i][draw_list_i], \"DrawList\");\r\n        }\r\n        TreePop();\r\n    }\r\n\r\n    // Viewports\r\n    if (TreeNode(\"Viewports\", \"Viewports (%d)\", g.Viewports.Size))\r\n    {\r\n        Indent(GetTreeNodeToLabelSpacing());\r\n        RenderViewportsThumbnails();\r\n        Unindent(GetTreeNodeToLabelSpacing());\r\n        for (int i = 0; i < g.Viewports.Size; i++)\r\n            DebugNodeViewport(g.Viewports[i]);\r\n        TreePop();\r\n    }\r\n\r\n    // Details for Popups\r\n    if (TreeNode(\"Popups\", \"Popups (%d)\", g.OpenPopupStack.Size))\r\n    {\r\n        for (int i = 0; i < g.OpenPopupStack.Size; i++)\r\n        {\r\n            ImGuiWindow* window = g.OpenPopupStack[i].Window;\r\n            BulletText(\"PopupID: %08x, Window: '%s'%s%s\", g.OpenPopupStack[i].PopupId, window ? window->Name : \"NULL\", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? \" ChildWindow\" : \"\", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? \" ChildMenu\" : \"\");\r\n        }\r\n        TreePop();\r\n    }\r\n\r\n    // Details for TabBars\r\n    if (TreeNode(\"TabBars\", \"Tab Bars (%d)\", g.TabBars.GetAliveCount()))\r\n    {\r\n        for (int n = 0; n < g.TabBars.GetMapSize(); n++)\r\n            if (ImGuiTabBar* tab_bar = g.TabBars.TryGetMapData(n))\r\n            {\r\n                PushID(tab_bar);\r\n                DebugNodeTabBar(tab_bar, \"TabBar\");\r\n                PopID();\r\n            }\r\n        TreePop();\r\n    }\r\n\r\n    // Details for Tables\r\n    if (TreeNode(\"Tables\", \"Tables (%d)\", g.Tables.GetAliveCount()))\r\n    {\r\n        for (int n = 0; n < g.Tables.GetMapSize(); n++)\r\n            if (ImGuiTable* table = g.Tables.TryGetMapData(n))\r\n                DebugNodeTable(table);\r\n        TreePop();\r\n    }\r\n\r\n    // Details for Fonts\r\n#ifndef IMGUI_DISABLE_DEMO_WINDOWS\r\n    ImFontAtlas* atlas = g.IO.Fonts;\r\n    if (TreeNode(\"Fonts\", \"Fonts (%d)\", atlas->Fonts.Size))\r\n    {\r\n        ShowFontAtlas(atlas);\r\n        TreePop();\r\n    }\r\n#endif\r\n\r\n    // Details for Docking\r\n#ifdef IMGUI_HAS_DOCK\r\n    if (TreeNode(\"Docking\"))\r\n    {\r\n        TreePop();\r\n    }\r\n#endif // #ifdef IMGUI_HAS_DOCK\r\n\r\n    // Settings\r\n    if (TreeNode(\"Settings\"))\r\n    {\r\n        if (SmallButton(\"Clear\"))\r\n            ClearIniSettings();\r\n        SameLine();\r\n        if (SmallButton(\"Save to memory\"))\r\n            SaveIniSettingsToMemory();\r\n        SameLine();\r\n        if (SmallButton(\"Save to disk\"))\r\n            SaveIniSettingsToDisk(g.IO.IniFilename);\r\n        SameLine();\r\n        if (g.IO.IniFilename)\r\n            Text(\"\\\"%s\\\"\", g.IO.IniFilename);\r\n        else\r\n            TextUnformatted(\"<NULL>\");\r\n        Text(\"SettingsDirtyTimer %.2f\", g.SettingsDirtyTimer);\r\n        if (TreeNode(\"SettingsHandlers\", \"Settings handlers: (%d)\", g.SettingsHandlers.Size))\r\n        {\r\n            for (int n = 0; n < g.SettingsHandlers.Size; n++)\r\n                BulletText(\"%s\", g.SettingsHandlers[n].TypeName);\r\n            TreePop();\r\n        }\r\n        if (TreeNode(\"SettingsWindows\", \"Settings packed data: Windows: %d bytes\", g.SettingsWindows.size()))\r\n        {\r\n            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))\r\n                DebugNodeWindowSettings(settings);\r\n            TreePop();\r\n        }\r\n\r\n        if (TreeNode(\"SettingsTables\", \"Settings packed data: Tables: %d bytes\", g.SettingsTables.size()))\r\n        {\r\n            for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))\r\n                DebugNodeTableSettings(settings);\r\n            TreePop();\r\n        }\r\n\r\n#ifdef IMGUI_HAS_DOCK\r\n#endif // #ifdef IMGUI_HAS_DOCK\r\n\r\n        if (TreeNode(\"SettingsIniData\", \"Settings unpacked data (.ini): %d bytes\", g.SettingsIniData.size()))\r\n        {\r\n            InputTextMultiline(\"##Ini\", (char*)(void*)g.SettingsIniData.c_str(), g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, GetTextLineHeight() * 20), ImGuiInputTextFlags_ReadOnly);\r\n            TreePop();\r\n        }\r\n        TreePop();\r\n    }\r\n\r\n    // Misc Details\r\n    if (TreeNode(\"Internal state\"))\r\n    {\r\n        Text(\"WINDOWING\");\r\n        Indent();\r\n        Text(\"HoveredWindow: '%s'\", g.HoveredWindow ? g.HoveredWindow->Name : \"NULL\");\r\n        Text(\"HoveredWindow->Root: '%s'\", g.HoveredWindow ? g.HoveredWindow->RootWindow->Name : \"NULL\");\r\n        Text(\"HoveredWindowUnderMovingWindow: '%s'\", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : \"NULL\");\r\n        Text(\"MovingWindow: '%s'\", g.MovingWindow ? g.MovingWindow->Name : \"NULL\");\r\n        Unindent();\r\n\r\n        Text(\"ITEMS\");\r\n        Indent();\r\n        Text(\"ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s\", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, GetInputSourceName(g.ActiveIdSource));\r\n        Text(\"ActiveIdWindow: '%s'\", g.ActiveIdWindow ? g.ActiveIdWindow->Name : \"NULL\");\r\n\r\n        int active_id_using_key_input_count = 0;\r\n        for (int n = 0; n < ImGuiKey_NamedKey_COUNT; n++)\r\n            active_id_using_key_input_count += g.ActiveIdUsingKeyInputMask[n] ? 1 : 0;\r\n        Text(\"ActiveIdUsing: Wheel: %d, NavDirMask: %X, NavInputMask: %X, KeyInputMask: %d key(s)\", g.ActiveIdUsingMouseWheel, g.ActiveIdUsingNavDirMask, g.ActiveIdUsingNavInputMask, active_id_using_key_input_count);\r\n        Text(\"HoveredId: 0x%08X (%.2f sec), AllowOverlap: %d\", g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Not displaying g.HoveredId as it is update mid-frame\r\n        Text(\"DragDrop: %d, SourceId = 0x%08X, Payload \\\"%s\\\" (%d bytes)\", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);\r\n        Unindent();\r\n\r\n        Text(\"NAV,FOCUS\");\r\n        Indent();\r\n        Text(\"NavWindow: '%s'\", g.NavWindow ? g.NavWindow->Name : \"NULL\");\r\n        Text(\"NavId: 0x%08X, NavLayer: %d\", g.NavId, g.NavLayer);\r\n        Text(\"NavInputSource: %s\", GetInputSourceName(g.NavInputSource));\r\n        Text(\"NavActive: %d, NavVisible: %d\", g.IO.NavActive, g.IO.NavVisible);\r\n        Text(\"NavActivateId/DownId/PressedId/InputId: %08X/%08X/%08X/%08X\", g.NavActivateId, g.NavActivateDownId, g.NavActivatePressedId, g.NavActivateInputId);\r\n        Text(\"NavActivateFlags: %04X\", g.NavActivateFlags);\r\n        Text(\"NavDisableHighlight: %d, NavDisableMouseHover: %d\", g.NavDisableHighlight, g.NavDisableMouseHover);\r\n        Text(\"NavFocusScopeId = 0x%08X\", g.NavFocusScopeId);\r\n        Text(\"NavWindowingTarget: '%s'\", g.NavWindowingTarget ? g.NavWindowingTarget->Name : \"NULL\");\r\n        Unindent();\r\n\r\n        TreePop();\r\n    }\r\n\r\n    // Overlay: Display windows Rectangles and Begin Order\r\n    if (cfg->ShowWindowsRects || cfg->ShowWindowsBeginOrder)\r\n    {\r\n        for (int n = 0; n < g.Windows.Size; n++)\r\n        {\r\n            ImGuiWindow* window = g.Windows[n];\r\n            if (!window->WasActive)\r\n                continue;\r\n            ImDrawList* draw_list = GetForegroundDrawList(window);\r\n            if (cfg->ShowWindowsRects)\r\n            {\r\n                ImRect r = Funcs::GetWindowRect(window, cfg->ShowWindowsRectsType);\r\n                draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));\r\n            }\r\n            if (cfg->ShowWindowsBeginOrder && !(window->Flags & ImGuiWindowFlags_ChildWindow))\r\n            {\r\n                char buf[32];\r\n                ImFormatString(buf, IM_ARRAYSIZE(buf), \"%d\", window->BeginOrderWithinContext);\r\n                float font_size = GetFontSize();\r\n                draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));\r\n                draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf);\r\n            }\r\n        }\r\n    }\r\n\r\n    // Overlay: Display Tables Rectangles\r\n    if (cfg->ShowTablesRects)\r\n    {\r\n        for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)\r\n        {\r\n            ImGuiTable* table = g.Tables.TryGetMapData(table_n);\r\n            if (table == NULL || table->LastFrameActive < g.FrameCount - 1)\r\n                continue;\r\n            ImDrawList* draw_list = GetForegroundDrawList(table->OuterWindow);\r\n            if (cfg->ShowTablesRectsType >= TRT_ColumnsRect)\r\n            {\r\n                for (int column_n = 0; column_n < table->ColumnsCount; column_n++)\r\n                {\r\n                    ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, column_n);\r\n                    ImU32 col = (table->HoveredColumnBody == column_n) ? IM_COL32(255, 255, 128, 255) : IM_COL32(255, 0, 128, 255);\r\n                    float thickness = (table->HoveredColumnBody == column_n) ? 3.0f : 1.0f;\r\n                    draw_list->AddRect(r.Min, r.Max, col, 0.0f, 0, thickness);\r\n                }\r\n            }\r\n            else\r\n            {\r\n                ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, -1);\r\n                draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));\r\n            }\r\n        }\r\n    }\r\n\r\n#ifdef IMGUI_HAS_DOCK\r\n    // Overlay: Display Docking info\r\n    if (show_docking_nodes && g.IO.KeyCtrl)\r\n    {\r\n    }\r\n#endif // #ifdef IMGUI_HAS_DOCK\r\n\r\n    End();\r\n}\r\n\r\n// [DEBUG] List fonts in a font atlas and display its texture\r\nvoid ImGui::ShowFontAtlas(ImFontAtlas* atlas)\r\n{\r\n    for (int i = 0; i < atlas->Fonts.Size; i++)\r\n    {\r\n        ImFont* font = atlas->Fonts[i];\r\n        PushID(font);\r\n        DebugNodeFont(font);\r\n        PopID();\r\n    }\r\n    if (TreeNode(\"Atlas texture\", \"Atlas texture (%dx%d pixels)\", atlas->TexWidth, atlas->TexHeight))\r\n    {\r\n        ImVec4 tint_col = ImVec4(1.0f, 1.0f, 1.0f, 1.0f);\r\n        ImVec4 border_col = ImVec4(1.0f, 1.0f, 1.0f, 0.5f);\r\n        Image(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), tint_col, border_col);\r\n        TreePop();\r\n    }\r\n}\r\n\r\n// [DEBUG] Display contents of Columns\r\nvoid ImGui::DebugNodeColumns(ImGuiOldColumns* columns)\r\n{\r\n    if (!TreeNode((void*)(uintptr_t)columns->ID, \"Columns Id: 0x%08X, Count: %d, Flags: 0x%04X\", columns->ID, columns->Count, columns->Flags))\r\n        return;\r\n    BulletText(\"Width: %.1f (MinX: %.1f, MaxX: %.1f)\", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX);\r\n    for (int column_n = 0; column_n < columns->Columns.Size; column_n++)\r\n        BulletText(\"Column %02d: OffsetNorm %.3f (= %.1f px)\", column_n, columns->Columns[column_n].OffsetNorm, GetColumnOffsetFromNorm(columns, columns->Columns[column_n].OffsetNorm));\r\n    TreePop();\r\n}\r\n\r\n// [DEBUG] Display contents of ImDrawList\r\nvoid ImGui::DebugNodeDrawList(ImGuiWindow* window, const ImDrawList* draw_list, const char* label)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;\r\n    int cmd_count = draw_list->CmdBuffer.Size;\r\n    if (cmd_count > 0 && draw_list->CmdBuffer.back().ElemCount == 0 && draw_list->CmdBuffer.back().UserCallback == NULL)\r\n        cmd_count--;\r\n    bool node_open = TreeNode(draw_list, \"%s: '%s' %d vtx, %d indices, %d cmds\", label, draw_list->_OwnerName ? draw_list->_OwnerName : \"\", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, cmd_count);\r\n    if (draw_list == GetWindowDrawList())\r\n    {\r\n        SameLine();\r\n        TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), \"CURRENTLY APPENDING\"); // Can't display stats for active draw list! (we don't have the data double-buffered)\r\n        if (node_open)\r\n            TreePop();\r\n        return;\r\n    }\r\n\r\n    ImDrawList* fg_draw_list = GetForegroundDrawList(window); // Render additional visuals into the top-most draw list\r\n    if (window && IsItemHovered() && fg_draw_list)\r\n        fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));\r\n    if (!node_open)\r\n        return;\r\n\r\n    if (window && !window->WasActive)\r\n        TextDisabled(\"Warning: owning Window is inactive. This DrawList is not being rendered!\");\r\n\r\n    for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.Data; pcmd < draw_list->CmdBuffer.Data + cmd_count; pcmd++)\r\n    {\r\n        if (pcmd->UserCallback)\r\n        {\r\n            BulletText(\"Callback %p, user_data %p\", pcmd->UserCallback, pcmd->UserCallbackData);\r\n            continue;\r\n        }\r\n\r\n        char buf[300];\r\n        ImFormatString(buf, IM_ARRAYSIZE(buf), \"DrawCmd:%5d tris, Tex 0x%p, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)\",\r\n            pcmd->ElemCount / 3, (void*)(intptr_t)pcmd->TextureId,\r\n            pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);\r\n        bool pcmd_node_open = TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), \"%s\", buf);\r\n        if (IsItemHovered() && (cfg->ShowDrawCmdMesh || cfg->ShowDrawCmdBoundingBoxes) && fg_draw_list)\r\n            DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, cfg->ShowDrawCmdMesh, cfg->ShowDrawCmdBoundingBoxes);\r\n        if (!pcmd_node_open)\r\n            continue;\r\n\r\n        // Calculate approximate coverage area (touched pixel count)\r\n        // This will be in pixels squared as long there's no post-scaling happening to the renderer output.\r\n        const ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;\r\n        const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + pcmd->VtxOffset;\r\n        float total_area = 0.0f;\r\n        for (unsigned int idx_n = pcmd->IdxOffset; idx_n < pcmd->IdxOffset + pcmd->ElemCount; )\r\n        {\r\n            ImVec2 triangle[3];\r\n            for (int n = 0; n < 3; n++, idx_n++)\r\n                triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos;\r\n            total_area += ImTriangleArea(triangle[0], triangle[1], triangle[2]);\r\n        }\r\n\r\n        // Display vertex information summary. Hover to get all triangles drawn in wire-frame\r\n        ImFormatString(buf, IM_ARRAYSIZE(buf), \"Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px\", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area);\r\n        Selectable(buf);\r\n        if (IsItemHovered() && fg_draw_list)\r\n            DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, true, false);\r\n\r\n        // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.\r\n        ImGuiListClipper clipper;\r\n        clipper.Begin(pcmd->ElemCount / 3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.\r\n        while (clipper.Step())\r\n            for (int prim = clipper.DisplayStart, idx_i = pcmd->IdxOffset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++)\r\n            {\r\n                char* buf_p = buf, * buf_end = buf + IM_ARRAYSIZE(buf);\r\n                ImVec2 triangle[3];\r\n                for (int n = 0; n < 3; n++, idx_i++)\r\n                {\r\n                    const ImDrawVert& v = vtx_buffer[idx_buffer ? idx_buffer[idx_i] : idx_i];\r\n                    triangle[n] = v.pos;\r\n                    buf_p += ImFormatString(buf_p, buf_end - buf_p, \"%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\\n\",\r\n                        (n == 0) ? \"Vert:\" : \"     \", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);\r\n                }\r\n\r\n                Selectable(buf, false);\r\n                if (fg_draw_list && IsItemHovered())\r\n                {\r\n                    ImDrawListFlags backup_flags = fg_draw_list->Flags;\r\n                    fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.\r\n                    fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f);\r\n                    fg_draw_list->Flags = backup_flags;\r\n                }\r\n            }\r\n        TreePop();\r\n    }\r\n    TreePop();\r\n}\r\n\r\n// [DEBUG] Display mesh/aabb of a ImDrawCmd\r\nvoid ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb)\r\n{\r\n    IM_ASSERT(show_mesh || show_aabb);\r\n\r\n    // Draw wire-frame version of all triangles\r\n    ImRect clip_rect = draw_cmd->ClipRect;\r\n    ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);\r\n    ImDrawListFlags backup_flags = out_draw_list->Flags;\r\n    out_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.\r\n    for (unsigned int idx_n = draw_cmd->IdxOffset, idx_end = draw_cmd->IdxOffset + draw_cmd->ElemCount; idx_n < idx_end; )\r\n    {\r\n        ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; // We don't hold on those pointers past iterations as ->AddPolyline() may invalidate them if out_draw_list==draw_list\r\n        ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + draw_cmd->VtxOffset;\r\n\r\n        ImVec2 triangle[3];\r\n        for (int n = 0; n < 3; n++, idx_n++)\r\n            vtxs_rect.Add((triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos));\r\n        if (show_mesh)\r\n            out_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f); // In yellow: mesh triangles\r\n    }\r\n    // Draw bounding boxes\r\n    if (show_aabb)\r\n    {\r\n        out_draw_list->AddRect(ImFloor(clip_rect.Min), ImFloor(clip_rect.Max), IM_COL32(255, 0, 255, 255)); // In pink: clipping rectangle submitted to GPU\r\n        out_draw_list->AddRect(ImFloor(vtxs_rect.Min), ImFloor(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)); // In cyan: bounding box of triangles\r\n    }\r\n    out_draw_list->Flags = backup_flags;\r\n}\r\n\r\n// [DEBUG] Display details for a single font, called by ShowStyleEditor().\r\nvoid ImGui::DebugNodeFont(ImFont* font)\r\n{\r\n    bool opened = TreeNode(font, \"Font: \\\"%s\\\"\\n%.2f px, %d glyphs, %d file(s)\",\r\n        font->ConfigData ? font->ConfigData[0].Name : \"\", font->FontSize, font->Glyphs.Size, font->ConfigDataCount);\r\n    SameLine();\r\n    if (SmallButton(\"Set as default\"))\r\n        GetIO().FontDefault = font;\r\n    if (!opened)\r\n        return;\r\n\r\n    // Display preview text\r\n    PushFont(font);\r\n    Text(\"The quick brown fox jumps over the lazy dog\");\r\n    PopFont();\r\n\r\n    // Display details\r\n    SetNextItemWidth(GetFontSize() * 8);\r\n    DragFloat(\"Font scale\", &font->Scale, 0.005f, 0.3f, 2.0f, \"%.1f\");\r\n    SameLine(); MetricsHelpMarker(\r\n        \"Note than the default embedded font is NOT meant to be scaled.\\n\\n\"\r\n        \"Font are currently rendered into bitmaps at a given size at the time of building the atlas. \"\r\n        \"You may oversample them to get some flexibility with scaling. \"\r\n        \"You can also render at multiple sizes and select which one to use at runtime.\\n\\n\"\r\n        \"(Glimmer of hope: the atlas system will be rewritten in the future to make scaling more flexible.)\");\r\n    Text(\"Ascent: %f, Descent: %f, Height: %f\", font->Ascent, font->Descent, font->Ascent - font->Descent);\r\n    char c_str[5];\r\n    Text(\"Fallback character: '%s' (U+%04X)\", ImTextCharToUtf8(c_str, font->FallbackChar), font->FallbackChar);\r\n    Text(\"Ellipsis character: '%s' (U+%04X)\", ImTextCharToUtf8(c_str, font->EllipsisChar), font->EllipsisChar);\r\n    const int surface_sqrt = (int)ImSqrt((float)font->MetricsTotalSurface);\r\n    Text(\"Texture Area: about %d px ~%dx%d px\", font->MetricsTotalSurface, surface_sqrt, surface_sqrt);\r\n    for (int config_i = 0; config_i < font->ConfigDataCount; config_i++)\r\n        if (font->ConfigData)\r\n            if (const ImFontConfig* cfg = &font->ConfigData[config_i])\r\n                BulletText(\"Input %d: \\'%s\\', Oversample: (%d,%d), PixelSnapH: %d, Offset: (%.1f,%.1f)\",\r\n                    config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH, cfg->GlyphOffset.x, cfg->GlyphOffset.y);\r\n\r\n    // Display all glyphs of the fonts in separate pages of 256 characters\r\n    if (TreeNode(\"Glyphs\", \"Glyphs (%d)\", font->Glyphs.Size))\r\n    {\r\n        ImDrawList* draw_list = GetWindowDrawList();\r\n        const ImU32 glyph_col = GetColorU32(ImGuiCol_Text);\r\n        const float cell_size = font->FontSize * 1;\r\n        const float cell_spacing = GetStyle().ItemSpacing.y;\r\n        for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256)\r\n        {\r\n            // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k)\r\n            // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT\r\n            // is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here)\r\n            if (!(base & 4095) && font->IsGlyphRangeUnused(base, base + 4095))\r\n            {\r\n                base += 4096 - 256;\r\n                continue;\r\n            }\r\n\r\n            int count = 0;\r\n            for (unsigned int n = 0; n < 256; n++)\r\n                if (font->FindGlyphNoFallback((ImWchar)(base + n)))\r\n                    count++;\r\n            if (count <= 0)\r\n                continue;\r\n            if (!TreeNode((void*)(intptr_t)base, \"U+%04X..U+%04X (%d %s)\", base, base + 255, count, count > 1 ? \"glyphs\" : \"glyph\"))\r\n                continue;\r\n\r\n            // Draw a 16x16 grid of glyphs\r\n            ImVec2 base_pos = GetCursorScreenPos();\r\n            for (unsigned int n = 0; n < 256; n++)\r\n            {\r\n                // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions\r\n                // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string.\r\n                ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing));\r\n                ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size);\r\n                const ImFontGlyph* glyph = font->FindGlyphNoFallback((ImWchar)(base + n));\r\n                draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50));\r\n                if (glyph)\r\n                    font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n));\r\n                if (glyph && IsMouseHoveringRect(cell_p1, cell_p2))\r\n                {\r\n                    BeginTooltip();\r\n                    Text(\"Codepoint: U+%04X\", base + n);\r\n                    Separator();\r\n                    Text(\"Visible: %d\", glyph->Visible);\r\n                    Text(\"AdvanceX: %.1f\", glyph->AdvanceX);\r\n                    Text(\"Pos: (%.2f,%.2f)->(%.2f,%.2f)\", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1);\r\n                    Text(\"UV: (%.3f,%.3f)->(%.3f,%.3f)\", glyph->U0, glyph->V0, glyph->U1, glyph->V1);\r\n                    EndTooltip();\r\n                }\r\n            }\r\n            Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16));\r\n            TreePop();\r\n        }\r\n        TreePop();\r\n    }\r\n    TreePop();\r\n}\r\n\r\n// [DEBUG] Display contents of ImGuiStorage\r\nvoid ImGui::DebugNodeStorage(ImGuiStorage* storage, const char* label)\r\n{\r\n    if (!TreeNode(label, \"%s: %d entries, %d bytes\", label, storage->Data.Size, storage->Data.size_in_bytes()))\r\n        return;\r\n    for (int n = 0; n < storage->Data.Size; n++)\r\n    {\r\n        const ImGuiStorage::ImGuiStoragePair& p = storage->Data[n];\r\n        BulletText(\"Key 0x%08X Value { i: %d }\", p.key, p.val_i); // Important: we currently don't store a type, real value may not be integer.\r\n    }\r\n    TreePop();\r\n}\r\n\r\n// [DEBUG] Display contents of ImGuiTabBar\r\nvoid ImGui::DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label)\r\n{\r\n    // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings.\r\n    char buf[256];\r\n    char* p = buf;\r\n    const char* buf_end = buf + IM_ARRAYSIZE(buf);\r\n    const bool is_active = (tab_bar->PrevFrameVisible >= GetFrameCount() - 2);\r\n    p += ImFormatString(p, buf_end - p, \"%s 0x%08X (%d tabs)%s\", label, tab_bar->ID, tab_bar->Tabs.Size, is_active ? \"\" : \" *Inactive*\");\r\n    p += ImFormatString(p, buf_end - p, \"  { \");\r\n    for (int tab_n = 0; tab_n < ImMin(tab_bar->Tabs.Size, 3); tab_n++)\r\n    {\r\n        ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];\r\n        p += ImFormatString(p, buf_end - p, \"%s'%s'\",\r\n            tab_n > 0 ? \", \" : \"\", (tab->NameOffset != -1) ? tab_bar->GetTabName(tab) : \"???\");\r\n    }\r\n    p += ImFormatString(p, buf_end - p, (tab_bar->Tabs.Size > 3) ? \" ... }\" : \" } \");\r\n    if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }\r\n    bool open = TreeNode(label, \"%s\", buf);\r\n    if (!is_active) { PopStyleColor(); }\r\n    if (is_active && IsItemHovered())\r\n    {\r\n        ImDrawList* draw_list = GetForegroundDrawList();\r\n        draw_list->AddRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255));\r\n        draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));\r\n        draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));\r\n    }\r\n    if (open)\r\n    {\r\n        for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)\r\n        {\r\n            const ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];\r\n            PushID(tab);\r\n            if (SmallButton(\"<\")) { TabBarQueueReorder(tab_bar, tab, -1); } SameLine(0, 2);\r\n            if (SmallButton(\">\")) { TabBarQueueReorder(tab_bar, tab, +1); } SameLine();\r\n            Text(\"%02d%c Tab 0x%08X '%s' Offset: %.1f, Width: %.1f/%.1f\",\r\n                tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, (tab->NameOffset != -1) ? tab_bar->GetTabName(tab) : \"???\", tab->Offset, tab->Width, tab->ContentWidth);\r\n            PopID();\r\n        }\r\n        TreePop();\r\n    }\r\n}\r\n\r\nvoid ImGui::DebugNodeViewport(ImGuiViewportP* viewport)\r\n{\r\n    SetNextItemOpen(true, ImGuiCond_Once);\r\n    if (TreeNode(\"viewport0\", \"Viewport #%d\", 0))\r\n    {\r\n        ImGuiWindowFlags flags = viewport->Flags;\r\n        BulletText(\"Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\\nWorkArea Offset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f\",\r\n            viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y,\r\n            viewport->WorkOffsetMin.x, viewport->WorkOffsetMin.y, viewport->WorkOffsetMax.x, viewport->WorkOffsetMax.y);\r\n        BulletText(\"Flags: 0x%04X =%s%s%s\", viewport->Flags,\r\n            (flags & ImGuiViewportFlags_IsPlatformWindow)  ? \" IsPlatformWindow\"  : \"\",\r\n            (flags & ImGuiViewportFlags_IsPlatformMonitor) ? \" IsPlatformMonitor\" : \"\",\r\n            (flags & ImGuiViewportFlags_OwnedByApp)        ? \" OwnedByApp\"        : \"\");\r\n        for (int layer_i = 0; layer_i < IM_ARRAYSIZE(viewport->DrawDataBuilder.Layers); layer_i++)\r\n            for (int draw_list_i = 0; draw_list_i < viewport->DrawDataBuilder.Layers[layer_i].Size; draw_list_i++)\r\n                DebugNodeDrawList(NULL, viewport->DrawDataBuilder.Layers[layer_i][draw_list_i], \"DrawList\");\r\n        TreePop();\r\n    }\r\n}\r\n\r\nvoid ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label)\r\n{\r\n    if (window == NULL)\r\n    {\r\n        BulletText(\"%s: NULL\", label);\r\n        return;\r\n    }\r\n\r\n    ImGuiContext& g = *GImGui;\r\n    const bool is_active = window->WasActive;\r\n    ImGuiTreeNodeFlags tree_node_flags = (window == g.NavWindow) ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;\r\n    if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }\r\n    const bool open = TreeNodeEx(label, tree_node_flags, \"%s '%s'%s\", label, window->Name, is_active ? \"\" : \" *Inactive*\");\r\n    if (!is_active) { PopStyleColor(); }\r\n    if (IsItemHovered() && is_active)\r\n        GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));\r\n    if (!open)\r\n        return;\r\n\r\n    if (window->MemoryCompacted)\r\n        TextDisabled(\"Note: some memory buffers have been compacted/freed.\");\r\n\r\n    ImGuiWindowFlags flags = window->Flags;\r\n    DebugNodeDrawList(window, window->DrawList, \"DrawList\");\r\n    BulletText(\"Pos: (%.1f,%.1f), Size: (%.1f,%.1f), ContentSize (%.1f,%.1f) Ideal (%.1f,%.1f)\", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->ContentSize.x, window->ContentSize.y, window->ContentSizeIdeal.x, window->ContentSizeIdeal.y);\r\n    BulletText(\"Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)\", flags,\r\n        (flags & ImGuiWindowFlags_ChildWindow)  ? \"Child \" : \"\",      (flags & ImGuiWindowFlags_Tooltip)     ? \"Tooltip \"   : \"\",  (flags & ImGuiWindowFlags_Popup) ? \"Popup \" : \"\",\r\n        (flags & ImGuiWindowFlags_Modal)        ? \"Modal \" : \"\",      (flags & ImGuiWindowFlags_ChildMenu)   ? \"ChildMenu \" : \"\",  (flags & ImGuiWindowFlags_NoSavedSettings) ? \"NoSavedSettings \" : \"\",\r\n        (flags & ImGuiWindowFlags_NoMouseInputs)? \"NoMouseInputs\":\"\", (flags & ImGuiWindowFlags_NoNavInputs) ? \"NoNavInputs\" : \"\", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? \"AlwaysAutoResize\" : \"\");\r\n    BulletText(\"Scroll: (%.2f/%.2f,%.2f/%.2f) Scrollbar:%s%s\", window->Scroll.x, window->ScrollMax.x, window->Scroll.y, window->ScrollMax.y, window->ScrollbarX ? \"X\" : \"\", window->ScrollbarY ? \"Y\" : \"\");\r\n    BulletText(\"Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d\", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);\r\n    BulletText(\"Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d\", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems);\r\n    for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)\r\n    {\r\n        ImRect r = window->NavRectRel[layer];\r\n        if (r.Min.x >= r.Max.y && r.Min.y >= r.Max.y)\r\n        {\r\n            BulletText(\"NavLastIds[%d]: 0x%08X\", layer, window->NavLastIds[layer]);\r\n            continue;\r\n        }\r\n        BulletText(\"NavLastIds[%d]: 0x%08X at +(%.1f,%.1f)(%.1f,%.1f)\", layer, window->NavLastIds[layer], r.Min.x, r.Min.y, r.Max.x, r.Max.y);\r\n        if (IsItemHovered())\r\n            GetForegroundDrawList(window)->AddRect(r.Min + window->Pos, r.Max + window->Pos, IM_COL32(255, 255, 0, 255));\r\n    }\r\n    BulletText(\"NavLayersActiveMask: %X, NavLastChildNavWindow: %s\", window->DC.NavLayersActiveMask, window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : \"NULL\");\r\n    if (window->RootWindow != window)       { DebugNodeWindow(window->RootWindow, \"RootWindow\"); }\r\n    if (window->ParentWindow != NULL)       { DebugNodeWindow(window->ParentWindow, \"ParentWindow\"); }\r\n    if (window->DC.ChildWindows.Size > 0)   { DebugNodeWindowsList(&window->DC.ChildWindows, \"ChildWindows\"); }\r\n    if (window->ColumnsStorage.Size > 0 && TreeNode(\"Columns\", \"Columns sets (%d)\", window->ColumnsStorage.Size))\r\n    {\r\n        for (int n = 0; n < window->ColumnsStorage.Size; n++)\r\n            DebugNodeColumns(&window->ColumnsStorage[n]);\r\n        TreePop();\r\n    }\r\n    DebugNodeStorage(&window->StateStorage, \"Storage\");\r\n    TreePop();\r\n}\r\n\r\nvoid ImGui::DebugNodeWindowSettings(ImGuiWindowSettings* settings)\r\n{\r\n    Text(\"0x%08X \\\"%s\\\" Pos (%d,%d) Size (%d,%d) Collapsed=%d\",\r\n        settings->ID, settings->GetName(), settings->Pos.x, settings->Pos.y, settings->Size.x, settings->Size.y, settings->Collapsed);\r\n}\r\n\r\nvoid ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>* windows, const char* label)\r\n{\r\n    if (!TreeNode(label, \"%s (%d)\", label, windows->Size))\r\n        return;\r\n    for (int i = windows->Size - 1; i >= 0; i--) // Iterate front to back\r\n    {\r\n        PushID((*windows)[i]);\r\n        DebugNodeWindow((*windows)[i], \"Window\");\r\n        PopID();\r\n    }\r\n    TreePop();\r\n}\r\n\r\n// FIXME-OPT: This is technically suboptimal, but it is simpler this way.\r\nvoid ImGui::DebugNodeWindowsListByBeginStackParent(ImGuiWindow** windows, int windows_size, ImGuiWindow* parent_in_begin_stack)\r\n{\r\n    for (int i = 0; i < windows_size; i++)\r\n    {\r\n        ImGuiWindow* window = windows[i];\r\n        if (window->ParentWindowInBeginStack != parent_in_begin_stack)\r\n            continue;\r\n        char buf[20];\r\n        ImFormatString(buf, IM_ARRAYSIZE(buf), \"[%04d] Window\", window->BeginOrderWithinContext);\r\n        //BulletText(\"[%04d] Window '%s'\", window->BeginOrderWithinContext, window->Name);\r\n        DebugNodeWindow(window, buf);\r\n        Indent();\r\n        DebugNodeWindowsListByBeginStackParent(windows + i + 1, windows_size - i - 1, window);\r\n        Unindent();\r\n    }\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, STACK TOOL)\r\n//-----------------------------------------------------------------------------\r\n\r\n// [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.\r\nvoid ImGui::UpdateDebugToolItemPicker()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    g.DebugItemPickerBreakId = 0;\r\n    if (!g.DebugItemPickerActive)\r\n        return;\r\n\r\n    const ImGuiID hovered_id = g.HoveredIdPreviousFrame;\r\n    SetMouseCursor(ImGuiMouseCursor_Hand);\r\n    if (IsKeyPressed(ImGuiKey_Escape))\r\n        g.DebugItemPickerActive = false;\r\n    if (IsMouseClicked(0) && hovered_id)\r\n    {\r\n        g.DebugItemPickerBreakId = hovered_id;\r\n        g.DebugItemPickerActive = false;\r\n    }\r\n    SetNextWindowBgAlpha(0.60f);\r\n    BeginTooltip();\r\n    Text(\"HoveredId: 0x%08X\", hovered_id);\r\n    Text(\"Press ESC to abort picking.\");\r\n    TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), \"Click to break in debugger!\");\r\n    EndTooltip();\r\n}\r\n\r\n// [DEBUG] Stack Tool: update queries. Called by NewFrame()\r\nvoid ImGui::UpdateDebugToolStackQueries()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiStackTool* tool = &g.DebugStackTool;\r\n\r\n    // Clear hook when stack tool is not visible\r\n    g.DebugHookIdInfo = 0;\r\n    if (g.FrameCount != tool->LastActiveFrame + 1)\r\n        return;\r\n\r\n    // Update queries. The steps are: -1: query Stack, >= 0: query each stack item\r\n    // We can only perform 1 ID Info query every frame. This is designed so the GetID() tests are cheap and constant-time\r\n    const ImGuiID query_id = g.HoveredIdPreviousFrame ? g.HoveredIdPreviousFrame : g.ActiveId;\r\n    if (tool->QueryId != query_id)\r\n    {\r\n        tool->QueryId = query_id;\r\n        tool->StackLevel = -1;\r\n        tool->Results.resize(0);\r\n    }\r\n    if (query_id == 0)\r\n        return;\r\n\r\n    // Advance to next stack level when we got our result, or after 2 frames (in case we never get a result)\r\n    int stack_level = tool->StackLevel;\r\n    if (stack_level >= 0 && stack_level < tool->Results.Size)\r\n        if (tool->Results[stack_level].QuerySuccess || tool->Results[stack_level].QueryFrameCount > 2)\r\n            tool->StackLevel++;\r\n\r\n    // Update hook\r\n    stack_level = tool->StackLevel;\r\n    if (stack_level == -1)\r\n        g.DebugHookIdInfo = query_id;\r\n    if (stack_level >= 0 && stack_level < tool->Results.Size)\r\n    {\r\n        g.DebugHookIdInfo = tool->Results[stack_level].ID;\r\n        tool->Results[stack_level].QueryFrameCount++;\r\n    }\r\n}\r\n\r\n// [DEBUG] Stack tool: hooks called by GetID() family functions\r\nvoid ImGui::DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* data_id, const void* data_id_end)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    ImGuiStackTool* tool = &g.DebugStackTool;\r\n\r\n    // Step 0: stack query\r\n    // This assume that the ID was computed with the current ID stack, which tends to be the case for our widget.\r\n    if (tool->StackLevel == -1)\r\n    {\r\n        tool->StackLevel++;\r\n        tool->Results.resize(window->IDStack.Size + 1, ImGuiStackLevelInfo());\r\n        for (int n = 0; n < window->IDStack.Size + 1; n++)\r\n            tool->Results[n].ID = (n < window->IDStack.Size) ? window->IDStack[n] : id;\r\n        return;\r\n    }\r\n\r\n    // Step 1+: query for individual level\r\n    IM_ASSERT(tool->StackLevel >= 0);\r\n    if (tool->StackLevel != window->IDStack.Size)\r\n        return;\r\n    ImGuiStackLevelInfo* info = &tool->Results[tool->StackLevel];\r\n    IM_ASSERT(info->ID == id && info->QueryFrameCount > 0);\r\n\r\n    int data_len;\r\n    switch (data_type)\r\n    {\r\n    case ImGuiDataType_S32:\r\n        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), \"%d\", (int)(intptr_t)data_id);\r\n        break;\r\n    case ImGuiDataType_String:\r\n        data_len = data_id_end ? (int)((const char*)data_id_end - (const char*)data_id) : (int)strlen((const char*)data_id);\r\n        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), \"\\\"%.*s\\\"\", data_len, (const char*)data_id);\r\n        break;\r\n    case ImGuiDataType_Pointer:\r\n        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), \"(void*)0x%p\", data_id);\r\n        break;\r\n    case ImGuiDataType_ID:\r\n        if (info->Desc[0] == 0) // PushOverrideID() is often used to avoid hashing twice, which would lead to 2 calls to DebugHookIdInfo(). We prioritize the first one.\r\n            ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), \"0x%08X [override]\", id);\r\n        break;\r\n    default:\r\n        IM_ASSERT(0);\r\n    }\r\n    info->QuerySuccess = true;\r\n}\r\n\r\n// Stack Tool: Display UI\r\nvoid ImGui::ShowStackToolWindow(bool* p_open)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))\r\n        SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 8.0f), ImGuiCond_FirstUseEver);\r\n    if (!Begin(\"Dear ImGui Stack Tool\", p_open) || GetCurrentWindow()->BeginCount > 1)\r\n    {\r\n        End();\r\n        return;\r\n    }\r\n\r\n    // Display hovered/active status\r\n    const ImGuiID hovered_id = g.HoveredIdPreviousFrame;\r\n    const ImGuiID active_id = g.ActiveId;\r\n#ifdef IMGUI_ENABLE_TEST_ENGINE\r\n    Text(\"HoveredId: 0x%08X (\\\"%s\\\"), ActiveId:  0x%08X (\\\"%s\\\")\", hovered_id, hovered_id ? ImGuiTestEngine_FindItemDebugLabel(&g, hovered_id) : \"\", active_id, active_id ? ImGuiTestEngine_FindItemDebugLabel(&g, active_id) : \"\");\r\n#else\r\n    Text(\"HoveredId: 0x%08X, ActiveId:  0x%08X\", hovered_id, active_id);\r\n#endif\r\n    SameLine();\r\n    MetricsHelpMarker(\"Hover an item with the mouse to display elements of the ID Stack leading to the item's final ID.\\nEach level of the stack correspond to a PushID() call.\\nAll levels of the stack are hashed together to make the final ID of a widget (ID displayed at the bottom level of the stack).\\nRead FAQ entry about the ID stack for details.\");\r\n\r\n    // Display decorated stack\r\n    ImGuiStackTool* tool = &g.DebugStackTool;\r\n    tool->LastActiveFrame = g.FrameCount;\r\n    if (tool->Results.Size > 0 && BeginTable(\"##table\", 3, ImGuiTableFlags_Borders))\r\n    {\r\n        const float id_width = CalcTextSize(\"0xDDDDDDDD\").x;\r\n        TableSetupColumn(\"Seed\", ImGuiTableColumnFlags_WidthFixed, id_width);\r\n        TableSetupColumn(\"PushID\", ImGuiTableColumnFlags_WidthStretch);\r\n        TableSetupColumn(\"Result\", ImGuiTableColumnFlags_WidthFixed, id_width);\r\n        TableHeadersRow();\r\n        for (int n = 0; n < tool->Results.Size; n++)\r\n        {\r\n            ImGuiStackLevelInfo* info = &tool->Results[n];\r\n            TableNextColumn();\r\n            Text(\"0x%08X\", (n > 0) ? tool->Results[n - 1].ID : 0);\r\n\r\n            TableNextColumn();\r\n            ImGuiWindow* window = (info->Desc[0] == 0 && n == 0) ? FindWindowByID(info->ID) : NULL;\r\n            if (window)                                         // Source: window name (because the root ID don't call GetID() and so doesn't get hooked)\r\n                Text(\"\\\"%s\\\" [window]\", window->Name);\r\n            else if (info->QuerySuccess)                        // Source: GetID() hooks (prioritize over ItemInfo() because we frequently use patterns like: PushID(str), Button(\"\") where they both have same id)\r\n                TextUnformatted(info->Desc);\r\n            else if (tool->StackLevel >= tool->Results.Size)    // Only start using fallback below when all queries are done, so during queries we don't flickering ??? markers.\r\n            {\r\n#ifdef IMGUI_ENABLE_TEST_ENGINE\r\n                if (const char* label = ImGuiTestEngine_FindItemDebugLabel(&g, info->ID))    // Source: ImGuiTestEngine's ItemInfo()\r\n                    Text(\"??? \\\"%s\\\"\", label);\r\n                else\r\n#endif\r\n                    TextUnformatted(\"???\");\r\n            }\r\n\r\n            TableNextColumn();\r\n            Text(\"0x%08X\", info->ID);\r\n            if (n == tool->Results.Size - 1)\r\n                TableSetBgColor(ImGuiTableBgTarget_CellBg, GetColorU32(ImGuiCol_Header));\r\n        }\r\n        EndTable();\r\n    }\r\n    End();\r\n}\r\n\r\n#else\r\n\r\nvoid ImGui::ShowMetricsWindow(bool*) {}\r\nvoid ImGui::ShowFontAtlas(ImFontAtlas*) {}\r\nvoid ImGui::DebugNodeColumns(ImGuiOldColumns*) {}\r\nvoid ImGui::DebugNodeDrawList(ImGuiWindow*, const ImDrawList*, const char*) {}\r\nvoid ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList*, const ImDrawList*, const ImDrawCmd*, bool, bool) {}\r\nvoid ImGui::DebugNodeFont(ImFont*) {}\r\nvoid ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {}\r\nvoid ImGui::DebugNodeTabBar(ImGuiTabBar*, const char*) {}\r\nvoid ImGui::DebugNodeWindow(ImGuiWindow*, const char*) {}\r\nvoid ImGui::DebugNodeWindowSettings(ImGuiWindowSettings*) {}\r\nvoid ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>*, const char*) {}\r\nvoid ImGui::DebugNodeViewport(ImGuiViewportP*) {}\r\n\r\nvoid ImGui::ShowStackToolWindow(bool*) {}\r\nvoid ImGui::DebugHookIdInfo(ImGuiID, ImGuiDataType, const void*, const void*) {}\r\nvoid ImGui::UpdateDebugToolItemPicker() {}\r\nvoid ImGui::UpdateDebugToolStackQueries() {}\r\n\r\n#endif // #ifndef IMGUI_DISABLE_METRICS_WINDOW\r\n\r\n//-----------------------------------------------------------------------------\r\n\r\n// Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.\r\n// Prefer just including imgui_internal.h from your code rather than using this define. If a declaration is missing from imgui_internal.h add it or request it on the github.\r\n#ifdef IMGUI_INCLUDE_IMGUI_USER_INL\r\n#include \"imgui_user.inl\"\r\n#endif\r\n\r\n//-----------------------------------------------------------------------------\r\n\r\n#endif // #ifndef IMGUI_DISABLE\r\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/imgui/imgui.h",
    "content": "// dear imgui, v1.87 WIP\r\n// (headers)\r\n\r\n// Help:\r\n// - Read FAQ at http://dearimgui.org/faq\r\n// - Newcomers, read 'Programmer guide' in imgui.cpp for notes on how to setup Dear ImGui in your codebase.\r\n// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that.\r\n// Read imgui.cpp for details, links and comments.\r\n\r\n// Resources:\r\n// - FAQ                   http://dearimgui.org/faq\r\n// - Homepage & latest     https://github.com/ocornut/imgui\r\n// - Releases & changelog  https://github.com/ocornut/imgui/releases\r\n// - Gallery               https://github.com/ocornut/imgui/issues/4451 (please post your screenshots/video there!)\r\n// - Wiki                  https://github.com/ocornut/imgui/wiki (lots of good stuff there)\r\n// - Glossary              https://github.com/ocornut/imgui/wiki/Glossary\r\n// - Issues & support      https://github.com/ocornut/imgui/issues\r\n\r\n// Getting Started?\r\n// - For first-time users having issues compiling/linking/running or issues loading fonts:\r\n//   please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above.\r\n\r\n/*\r\n\r\nIndex of this file:\r\n// [SECTION] Header mess\r\n// [SECTION] Forward declarations and basic types\r\n// [SECTION] Dear ImGui end-user API functions\r\n// [SECTION] Flags & Enumerations\r\n// [SECTION] Helpers: Memory allocations macros, ImVector<>\r\n// [SECTION] ImGuiStyle\r\n// [SECTION] ImGuiIO\r\n// [SECTION] Misc data structures (ImGuiInputTextCallbackData, ImGuiSizeCallbackData, ImGuiPayload, ImGuiTableSortSpecs, ImGuiTableColumnSortSpecs)\r\n// [SECTION] Helpers (ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, ImColor)\r\n// [SECTION] Drawing API (ImDrawCallback, ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawFlags, ImDrawListFlags, ImDrawList, ImDrawData)\r\n// [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontGlyphRangesBuilder, ImFontAtlasFlags, ImFontAtlas, ImFont)\r\n// [SECTION] Viewports (ImGuiViewportFlags, ImGuiViewport)\r\n// [SECTION] Platform Dependent Interfaces (ImGuiPlatformImeData)\r\n// [SECTION] Obsolete functions and types\r\n\r\n*/\r\n\r\n#pragma once\r\n\r\n// Configuration file with compile-time options (edit imconfig.h or '#define IMGUI_USER_CONFIG \"myfilename.h\" from your build system')\r\n#ifdef IMGUI_USER_CONFIG\r\n#include IMGUI_USER_CONFIG\r\n#endif\r\n#if !defined(IMGUI_DISABLE_INCLUDE_IMCONFIG_H) || defined(IMGUI_INCLUDE_IMCONFIG_H)\r\n#include \"imconfig.h\"\r\n#endif\r\n\r\n#ifndef IMGUI_DISABLE\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Header mess\r\n//-----------------------------------------------------------------------------\r\n\r\n// Includes\r\n#include <float.h>                  // FLT_MIN, FLT_MAX\r\n#include <stdarg.h>                 // va_list, va_start, va_end\r\n#include <stddef.h>                 // ptrdiff_t, NULL\r\n#include <string.h>                 // memset, memmove, memcpy, strlen, strchr, strcpy, strcmp\r\n\r\n// Version\r\n// (Integer encoded as XYYZZ for use in #if preprocessor conditionals. Work in progress versions typically starts at XYY99 then bounce up to XYY00, XYY01 etc. when release tagging happens)\r\n#define IMGUI_VERSION               \"1.87 WIP\"\r\n#define IMGUI_VERSION_NUM           18616\r\n#define IMGUI_CHECKVERSION()        ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert), sizeof(ImDrawIdx))\r\n#define IMGUI_HAS_TABLE\r\n\r\n// Define attributes of all API symbols declarations (e.g. for DLL under Windows)\r\n// IMGUI_API is used for core imgui functions, IMGUI_IMPL_API is used for the default backends files (imgui_impl_xxx.h)\r\n// Using dear imgui via a shared library is not recommended, because we don't guarantee backward nor forward ABI compatibility (also function call overhead, as dear imgui is a call-heavy API)\r\n#ifndef IMGUI_API\r\n#define IMGUI_API\r\n#endif\r\n#ifndef IMGUI_IMPL_API\r\n#define IMGUI_IMPL_API              IMGUI_API\r\n#endif\r\n\r\n// Helper Macros\r\n#ifndef IM_ASSERT\r\n#include <assert.h>\r\n#define IM_ASSERT(_EXPR)            assert(_EXPR)                               // You can override the default assert handler by editing imconfig.h\r\n#endif\r\n#define IM_ARRAYSIZE(_ARR)          ((int)(sizeof(_ARR) / sizeof(*(_ARR))))     // Size of a static C-style array. Don't use on pointers!\r\n#define IM_UNUSED(_VAR)             ((void)(_VAR))                              // Used to silence \"unused variable warnings\". Often useful as asserts may be stripped out from final builds.\r\n#define IM_OFFSETOF(_TYPE,_MEMBER)  offsetof(_TYPE, _MEMBER)                    // Offset of _MEMBER within _TYPE. Standardized as offsetof() in C++11\r\n\r\n// Helper Macros - IM_FMTARGS, IM_FMTLIST: Apply printf-style warnings to our formatting functions.\r\n#if !defined(IMGUI_USE_STB_SPRINTF) && defined(__MINGW32__) && !defined(__clang__)\r\n#define IM_FMTARGS(FMT)             __attribute__((format(gnu_printf, FMT, FMT+1)))\r\n#define IM_FMTLIST(FMT)             __attribute__((format(gnu_printf, FMT, 0)))\r\n#elif !defined(IMGUI_USE_STB_SPRINTF) && (defined(__clang__) || defined(__GNUC__))\r\n#define IM_FMTARGS(FMT)             __attribute__((format(printf, FMT, FMT+1)))\r\n#define IM_FMTLIST(FMT)             __attribute__((format(printf, FMT, 0)))\r\n#else\r\n#define IM_FMTARGS(FMT)\r\n#define IM_FMTLIST(FMT)\r\n#endif\r\n\r\n// Disable some of MSVC most aggressive Debug runtime checks in function header/footer (used in some simple/low-level functions)\r\n#if defined(_MSC_VER) && !defined(__clang__)  && !defined(__INTEL_COMPILER) && !defined(IMGUI_DEBUG_PARANOID)\r\n#define IM_MSVC_RUNTIME_CHECKS_OFF      __pragma(runtime_checks(\"\",off))     __pragma(check_stack(off)) __pragma(strict_gs_check(push,off))\r\n#define IM_MSVC_RUNTIME_CHECKS_RESTORE  __pragma(runtime_checks(\"\",restore)) __pragma(check_stack())    __pragma(strict_gs_check(pop))\r\n#else\r\n#define IM_MSVC_RUNTIME_CHECKS_OFF\r\n#define IM_MSVC_RUNTIME_CHECKS_RESTORE\r\n#endif\r\n\r\n// Warnings\r\n#ifdef _MSC_VER\r\n#pragma warning (push)\r\n#pragma warning (disable: 26495)    // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6).\r\n#endif\r\n#if defined(__clang__)\r\n#pragma clang diagnostic push\r\n#pragma clang diagnostic ignored \"-Wold-style-cast\"\r\n#if __has_warning(\"-Wzero-as-null-pointer-constant\")\r\n#pragma clang diagnostic ignored \"-Wzero-as-null-pointer-constant\"\r\n#endif\r\n#elif defined(__GNUC__)\r\n#pragma GCC diagnostic push\r\n#pragma GCC diagnostic ignored \"-Wpragmas\"          // warning: unknown option after '#pragma GCC diagnostic' kind\r\n#pragma GCC diagnostic ignored \"-Wclass-memaccess\"  // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead\r\n#endif\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Forward declarations and basic types\r\n//-----------------------------------------------------------------------------\r\n\r\n// Forward declarations\r\nstruct ImDrawChannel;               // Temporary storage to output draw commands out of order, used by ImDrawListSplitter and ImDrawList::ChannelsSplit()\r\nstruct ImDrawCmd;                   // A single draw command within a parent ImDrawList (generally maps to 1 GPU draw call, unless it is a callback)\r\nstruct ImDrawData;                  // All draw command lists required to render the frame + pos/size coordinates to use for the projection matrix.\r\nstruct ImDrawList;                  // A single draw command list (generally one per window, conceptually you may see this as a dynamic \"mesh\" builder)\r\nstruct ImDrawListSharedData;        // Data shared among multiple draw lists (typically owned by parent ImGui context, but you may create one yourself)\r\nstruct ImDrawListSplitter;          // Helper to split a draw list into different layers which can be drawn into out of order, then flattened back.\r\nstruct ImDrawVert;                  // A single vertex (pos + uv + col = 20 bytes by default. Override layout with IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT)\r\nstruct ImFont;                      // Runtime data for a single font within a parent ImFontAtlas\r\nstruct ImFontAtlas;                 // Runtime data for multiple fonts, bake multiple fonts into a single texture, TTF/OTF font loader\r\nstruct ImFontBuilderIO;             // Opaque interface to a font builder (stb_truetype or FreeType).\r\nstruct ImFontConfig;                // Configuration data when adding a font or merging fonts\r\nstruct ImFontGlyph;                 // A single font glyph (code point + coordinates within in ImFontAtlas + offset)\r\nstruct ImFontGlyphRangesBuilder;    // Helper to build glyph ranges from text/string data\r\nstruct ImColor;                     // Helper functions to create a color that can be converted to either u32 or float4 (*OBSOLETE* please avoid using)\r\nstruct ImGuiContext;                // Dear ImGui context (opaque structure, unless including imgui_internal.h)\r\nstruct ImGuiIO;                     // Main configuration and I/O between your application and ImGui\r\nstruct ImGuiInputTextCallbackData;  // Shared state of InputText() when using custom ImGuiInputTextCallback (rare/advanced use)\r\nstruct ImGuiKeyData;                // Storage for ImGuiIO and IsKeyDown(), IsKeyPressed() etc functions.\r\nstruct ImGuiListClipper;            // Helper to manually clip large list of items\r\nstruct ImGuiOnceUponAFrame;         // Helper for running a block of code not more than once a frame\r\nstruct ImGuiPayload;                // User data payload for drag and drop operations\r\nstruct ImGuiPlatformImeData;        // Platform IME data for io.SetPlatformImeDataFn() function.\r\nstruct ImGuiSizeCallbackData;       // Callback data when using SetNextWindowSizeConstraints() (rare/advanced use)\r\nstruct ImGuiStorage;                // Helper for key->value storage\r\nstruct ImGuiStyle;                  // Runtime data for styling/colors\r\nstruct ImGuiTableSortSpecs;         // Sorting specifications for a table (often handling sort specs for a single column, occasionally more)\r\nstruct ImGuiTableColumnSortSpecs;   // Sorting specification for one column of a table\r\nstruct ImGuiTextBuffer;             // Helper to hold and append into a text buffer (~string builder)\r\nstruct ImGuiTextFilter;             // Helper to parse and apply text filters (e.g. \"aaaaa[,bbbbb][,ccccc]\")\r\nstruct ImGuiViewport;               // A Platform Window (always only one in 'master' branch), in the future may represent Platform Monitor\r\n\r\n// Enums/Flags (declared as int for compatibility with old C++, to allow using as flags without overhead, and to not pollute the top of this file)\r\n// - Tip: Use your programming IDE navigation facilities on the names in the _central column_ below to find the actual flags/enum lists!\r\n//   In Visual Studio IDE: CTRL+comma (\"Edit.NavigateTo\") can follow symbols in comments, whereas CTRL+F12 (\"Edit.GoToImplementation\") cannot.\r\n//   With Visual Assist installed: ALT+G (\"VAssistX.GoToImplementation\") can also follow symbols in comments.\r\ntypedef int ImGuiCol;               // -> enum ImGuiCol_             // Enum: A color identifier for styling\r\ntypedef int ImGuiCond;              // -> enum ImGuiCond_            // Enum: A condition for many Set*() functions\r\ntypedef int ImGuiDataType;          // -> enum ImGuiDataType_        // Enum: A primary data type\r\ntypedef int ImGuiDir;               // -> enum ImGuiDir_             // Enum: A cardinal direction\r\ntypedef int ImGuiKey;               // -> enum ImGuiKey_             // Enum: A key identifier\r\ntypedef int ImGuiNavInput;          // -> enum ImGuiNavInput_        // Enum: An input identifier for navigation\r\ntypedef int ImGuiMouseButton;       // -> enum ImGuiMouseButton_     // Enum: A mouse button identifier (0=left, 1=right, 2=middle)\r\ntypedef int ImGuiMouseCursor;       // -> enum ImGuiMouseCursor_     // Enum: A mouse cursor identifier\r\ntypedef int ImGuiSortDirection;     // -> enum ImGuiSortDirection_   // Enum: A sorting direction (ascending or descending)\r\ntypedef int ImGuiStyleVar;          // -> enum ImGuiStyleVar_        // Enum: A variable identifier for styling\r\ntypedef int ImGuiTableBgTarget;     // -> enum ImGuiTableBgTarget_   // Enum: A color target for TableSetBgColor()\r\ntypedef int ImDrawFlags;            // -> enum ImDrawFlags_          // Flags: for ImDrawList functions\r\ntypedef int ImDrawListFlags;        // -> enum ImDrawListFlags_      // Flags: for ImDrawList instance\r\ntypedef int ImFontAtlasFlags;       // -> enum ImFontAtlasFlags_     // Flags: for ImFontAtlas build\r\ntypedef int ImGuiBackendFlags;      // -> enum ImGuiBackendFlags_    // Flags: for io.BackendFlags\r\ntypedef int ImGuiButtonFlags;       // -> enum ImGuiButtonFlags_     // Flags: for InvisibleButton()\r\ntypedef int ImGuiColorEditFlags;    // -> enum ImGuiColorEditFlags_  // Flags: for ColorEdit4(), ColorPicker4() etc.\r\ntypedef int ImGuiConfigFlags;       // -> enum ImGuiConfigFlags_     // Flags: for io.ConfigFlags\r\ntypedef int ImGuiComboFlags;        // -> enum ImGuiComboFlags_      // Flags: for BeginCombo()\r\ntypedef int ImGuiDragDropFlags;     // -> enum ImGuiDragDropFlags_   // Flags: for BeginDragDropSource(), AcceptDragDropPayload()\r\ntypedef int ImGuiFocusedFlags;      // -> enum ImGuiFocusedFlags_    // Flags: for IsWindowFocused()\r\ntypedef int ImGuiHoveredFlags;      // -> enum ImGuiHoveredFlags_    // Flags: for IsItemHovered(), IsWindowHovered() etc.\r\ntypedef int ImGuiInputTextFlags;    // -> enum ImGuiInputTextFlags_  // Flags: for InputText(), InputTextMultiline()\r\ntypedef int ImGuiKeyModFlags;       // -> enum ImGuiKeyModFlags_     // Flags: for io.KeyMods (Ctrl/Shift/Alt/Super)\r\ntypedef int ImGuiPopupFlags;        // -> enum ImGuiPopupFlags_      // Flags: for OpenPopup*(), BeginPopupContext*(), IsPopupOpen()\r\ntypedef int ImGuiSelectableFlags;   // -> enum ImGuiSelectableFlags_ // Flags: for Selectable()\r\ntypedef int ImGuiSliderFlags;       // -> enum ImGuiSliderFlags_     // Flags: for DragFloat(), DragInt(), SliderFloat(), SliderInt() etc.\r\ntypedef int ImGuiTabBarFlags;       // -> enum ImGuiTabBarFlags_     // Flags: for BeginTabBar()\r\ntypedef int ImGuiTabItemFlags;      // -> enum ImGuiTabItemFlags_    // Flags: for BeginTabItem()\r\ntypedef int ImGuiTableFlags;        // -> enum ImGuiTableFlags_      // Flags: For BeginTable()\r\ntypedef int ImGuiTableColumnFlags;  // -> enum ImGuiTableColumnFlags_// Flags: For TableSetupColumn()\r\ntypedef int ImGuiTableRowFlags;     // -> enum ImGuiTableRowFlags_   // Flags: For TableNextRow()\r\ntypedef int ImGuiTreeNodeFlags;     // -> enum ImGuiTreeNodeFlags_   // Flags: for TreeNode(), TreeNodeEx(), CollapsingHeader()\r\ntypedef int ImGuiViewportFlags;     // -> enum ImGuiViewportFlags_   // Flags: for ImGuiViewport\r\ntypedef int ImGuiWindowFlags;       // -> enum ImGuiWindowFlags_     // Flags: for Begin(), BeginChild()\r\n\r\n// ImTexture: user data for renderer backend to identify a texture [Compile-time configurable type]\r\n// - To use something else than an opaque void* pointer: override with e.g. '#define ImTextureID MyTextureType*' in your imconfig.h file.\r\n// - This can be whatever to you want it to be! read the FAQ about ImTextureID for details.\r\n#ifndef ImTextureID\r\ntypedef void* ImTextureID;          // Default: store a pointer or an integer fitting in a pointer (most renderer backends are ok with that)\r\n#endif\r\n\r\n// ImDrawIdx: vertex index. [Compile-time configurable type]\r\n// - To use 16-bit indices + allow large meshes: backend need to set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset' and handle ImDrawCmd::VtxOffset (recommended).\r\n// - To use 32-bit indices: override with '#define ImDrawIdx unsigned int' in your imconfig.h file.\r\n#ifndef ImDrawIdx\r\ntypedef unsigned short ImDrawIdx;   // Default: 16-bit (for maximum compatibility with renderer backends)\r\n#endif\r\n\r\n// Scalar data types\r\ntypedef unsigned int        ImGuiID;// A unique ID used by widgets (typically the result of hashing a stack of string)\r\ntypedef signed char         ImS8;   // 8-bit signed integer\r\ntypedef unsigned char       ImU8;   // 8-bit unsigned integer\r\ntypedef signed short        ImS16;  // 16-bit signed integer\r\ntypedef unsigned short      ImU16;  // 16-bit unsigned integer\r\ntypedef signed int          ImS32;  // 32-bit signed integer == int\r\ntypedef unsigned int        ImU32;  // 32-bit unsigned integer (often used to store packed colors)\r\ntypedef signed   long long  ImS64;  // 64-bit signed integer\r\ntypedef unsigned long long  ImU64;  // 64-bit unsigned integer\r\n\r\n// Character types\r\n// (we generally use UTF-8 encoded string in the API. This is storage specifically for a decoded character used for keyboard input and display)\r\ntypedef unsigned short ImWchar16;   // A single decoded U16 character/code point. We encode them as multi bytes UTF-8 when used in strings.\r\ntypedef unsigned int ImWchar32;     // A single decoded U32 character/code point. We encode them as multi bytes UTF-8 when used in strings.\r\n#ifdef IMGUI_USE_WCHAR32            // ImWchar [configurable type: override in imconfig.h with '#define IMGUI_USE_WCHAR32' to support Unicode planes 1-16]\r\ntypedef ImWchar32 ImWchar;\r\n#else\r\ntypedef ImWchar16 ImWchar;\r\n#endif\r\n\r\n// Callback and functions types\r\ntypedef int     (*ImGuiInputTextCallback)(ImGuiInputTextCallbackData* data);    // Callback function for ImGui::InputText()\r\ntypedef void    (*ImGuiSizeCallback)(ImGuiSizeCallbackData* data);              // Callback function for ImGui::SetNextWindowSizeConstraints()\r\ntypedef void*   (*ImGuiMemAllocFunc)(size_t sz, void* user_data);               // Function signature for ImGui::SetAllocatorFunctions()\r\ntypedef void    (*ImGuiMemFreeFunc)(void* ptr, void* user_data);                // Function signature for ImGui::SetAllocatorFunctions()\r\n\r\n// ImVec2: 2D vector used to store positions, sizes etc. [Compile-time configurable type]\r\n// This is a frequently used type in the API. Consider using IM_VEC2_CLASS_EXTRA to create implicit cast from/to our preferred type.\r\nIM_MSVC_RUNTIME_CHECKS_OFF\r\nstruct ImVec2\r\n{\r\n    float                                   x, y;\r\n    ImVec2()                                { x = y = 0.0f; }\r\n    ImVec2(float _x, float _y)              { x = _x; y = _y; }\r\n    float  operator[] (size_t idx) const    { IM_ASSERT(idx <= 1); return (&x)[idx]; }    // We very rarely use this [] operator, the assert overhead is fine.\r\n    float& operator[] (size_t idx)          { IM_ASSERT(idx <= 1); return (&x)[idx]; }    // We very rarely use this [] operator, the assert overhead is fine.\r\n#ifdef IM_VEC2_CLASS_EXTRA\r\n    IM_VEC2_CLASS_EXTRA     // Define additional constructors and implicit cast operators in imconfig.h to convert back and forth between your math types and ImVec2.\r\n#endif\r\n};\r\n\r\n// ImVec4: 4D vector used to store clipping rectangles, colors etc. [Compile-time configurable type]\r\nstruct ImVec4\r\n{\r\n    float                                           x, y, z, w;\r\n    ImVec4()                                        { x = y = z = w = 0.0f; }\r\n    ImVec4(float _x, float _y, float _z, float _w)  { x = _x; y = _y; z = _z; w = _w; }\r\n#ifdef IM_VEC4_CLASS_EXTRA\r\n    IM_VEC4_CLASS_EXTRA     // Define additional constructors and implicit cast operators in imconfig.h to convert back and forth between your math types and ImVec4.\r\n#endif\r\n};\r\nIM_MSVC_RUNTIME_CHECKS_RESTORE\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Dear ImGui end-user API functions\r\n// (Note that ImGui:: being a namespace, you can add extra ImGui:: functions in your own separate file. Please don't modify imgui source files!)\r\n//-----------------------------------------------------------------------------\r\n\r\nnamespace ImGui\r\n{\r\n    // Context creation and access\r\n    // - Each context create its own ImFontAtlas by default. You may instance one yourself and pass it to CreateContext() to share a font atlas between contexts.\r\n    // - DLL users: heaps and globals are not shared across DLL boundaries! You will need to call SetCurrentContext() + SetAllocatorFunctions()\r\n    //   for each static/DLL boundary you are calling from. Read \"Context and Memory Allocators\" section of imgui.cpp for details.\r\n    IMGUI_API ImGuiContext* CreateContext(ImFontAtlas* shared_font_atlas = NULL);\r\n    IMGUI_API void          DestroyContext(ImGuiContext* ctx = NULL);   // NULL = destroy current context\r\n    IMGUI_API ImGuiContext* GetCurrentContext();\r\n    IMGUI_API void          SetCurrentContext(ImGuiContext* ctx);\r\n\r\n    // Main\r\n    IMGUI_API ImGuiIO&      GetIO();                                    // access the IO structure (mouse/keyboard/gamepad inputs, time, various configuration options/flags)\r\n    IMGUI_API ImGuiStyle&   GetStyle();                                 // access the Style structure (colors, sizes). Always use PushStyleCol(), PushStyleVar() to modify style mid-frame!\r\n    IMGUI_API void          NewFrame();                                 // start a new Dear ImGui frame, you can submit any command from this point until Render()/EndFrame().\r\n    IMGUI_API void          EndFrame();                                 // ends the Dear ImGui frame. automatically called by Render(). If you don't need to render data (skipping rendering) you may call EndFrame() without Render()... but you'll have wasted CPU already! If you don't need to render, better to not create any windows and not call NewFrame() at all!\r\n    IMGUI_API void          Render();                                   // ends the Dear ImGui frame, finalize the draw data. You can then get call GetDrawData().\r\n    IMGUI_API ImDrawData*   GetDrawData();                              // valid after Render() and until the next call to NewFrame(). this is what you have to render.\r\n\r\n    // Demo, Debug, Information\r\n    IMGUI_API void          ShowDemoWindow(bool* p_open = NULL);        // create Demo window. demonstrate most ImGui features. call this to learn about the library! try to make it always available in your application!\r\n    IMGUI_API void          ShowMetricsWindow(bool* p_open = NULL);     // create Metrics/Debugger window. display Dear ImGui internals: windows, draw commands, various internal state, etc.\r\n    IMGUI_API void          ShowStackToolWindow(bool* p_open = NULL);   // create Stack Tool window. hover items with mouse to query information about the source of their unique ID.\r\n    IMGUI_API void          ShowAboutWindow(bool* p_open = NULL);       // create About window. display Dear ImGui version, credits and build/system information.\r\n    IMGUI_API void          ShowStyleEditor(ImGuiStyle* ref = NULL);    // add style editor block (not a window). you can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it uses the default style)\r\n    IMGUI_API bool          ShowStyleSelector(const char* label);       // add style selector block (not a window), essentially a combo listing the default styles.\r\n    IMGUI_API void          ShowFontSelector(const char* label);        // add font selector block (not a window), essentially a combo listing the loaded fonts.\r\n    IMGUI_API void          ShowUserGuide();                            // add basic help/info block (not a window): how to manipulate ImGui as a end-user (mouse/keyboard controls).\r\n    IMGUI_API const char*   GetVersion();                               // get the compiled version string e.g. \"1.80 WIP\" (essentially the value for IMGUI_VERSION from the compiled version of imgui.cpp)\r\n\r\n    // Styles\r\n    IMGUI_API void          StyleColorsDark(ImGuiStyle* dst = NULL);    // new, recommended style (default)\r\n    IMGUI_API void          StyleColorsLight(ImGuiStyle* dst = NULL);   // best used with borders and a custom, thicker font\r\n    IMGUI_API void          StyleColorsClassic(ImGuiStyle* dst = NULL); // classic imgui style\r\n\r\n    // Windows\r\n    // - Begin() = push window to the stack and start appending to it. End() = pop window from the stack.\r\n    // - Passing 'bool* p_open != NULL' shows a window-closing widget in the upper-right corner of the window,\r\n    //   which clicking will set the boolean to false when clicked.\r\n    // - You may append multiple times to the same window during the same frame by calling Begin()/End() pairs multiple times.\r\n    //   Some information such as 'flags' or 'p_open' will only be considered by the first call to Begin().\r\n    // - Begin() return false to indicate the window is collapsed or fully clipped, so you may early out and omit submitting\r\n    //   anything to the window. Always call a matching End() for each Begin() call, regardless of its return value!\r\n    //   [Important: due to legacy reason, this is inconsistent with most other functions such as BeginMenu/EndMenu,\r\n    //    BeginPopup/EndPopup, etc. where the EndXXX call should only be called if the corresponding BeginXXX function\r\n    //    returned true. Begin and BeginChild are the only odd ones out. Will be fixed in a future update.]\r\n    // - Note that the bottom of window stack always contains a window called \"Debug\".\r\n    IMGUI_API bool          Begin(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0);\r\n    IMGUI_API void          End();\r\n\r\n    // Child Windows\r\n    // - Use child windows to begin into a self-contained independent scrolling/clipping regions within a host window. Child windows can embed their own child.\r\n    // - For each independent axis of 'size': ==0.0f: use remaining host window size / >0.0f: fixed size / <0.0f: use remaining window size minus abs(size) / Each axis can use a different mode, e.g. ImVec2(0,400).\r\n    // - BeginChild() returns false to indicate the window is collapsed or fully clipped, so you may early out and omit submitting anything to the window.\r\n    //   Always call a matching EndChild() for each BeginChild() call, regardless of its return value.\r\n    //   [Important: due to legacy reason, this is inconsistent with most other functions such as BeginMenu/EndMenu,\r\n    //    BeginPopup/EndPopup, etc. where the EndXXX call should only be called if the corresponding BeginXXX function\r\n    //    returned true. Begin and BeginChild are the only odd ones out. Will be fixed in a future update.]\r\n    IMGUI_API bool          BeginChild(const char* str_id, const ImVec2& size = ImVec2(0, 0), bool border = false, ImGuiWindowFlags flags = 0);\r\n    IMGUI_API bool          BeginChild(ImGuiID id, const ImVec2& size = ImVec2(0, 0), bool border = false, ImGuiWindowFlags flags = 0);\r\n    IMGUI_API void          EndChild();\r\n\r\n    // Windows Utilities\r\n    // - 'current window' = the window we are appending into while inside a Begin()/End() block. 'next window' = next window we will Begin() into.\r\n    IMGUI_API bool          IsWindowAppearing();\r\n    IMGUI_API bool          IsWindowCollapsed();\r\n    IMGUI_API bool          IsWindowFocused(ImGuiFocusedFlags flags=0); // is current window focused? or its root/child, depending on flags. see flags for options.\r\n    IMGUI_API bool          IsWindowHovered(ImGuiHoveredFlags flags=0); // is current window hovered (and typically: not blocked by a popup/modal)? see flags for options. NB: If you are trying to check whether your mouse should be dispatched to imgui or to your app, you should use the 'io.WantCaptureMouse' boolean for that! Please read the FAQ!\r\n    IMGUI_API ImDrawList*   GetWindowDrawList();                        // get draw list associated to the current window, to append your own drawing primitives\r\n    IMGUI_API ImVec2        GetWindowPos();                             // get current window position in screen space (useful if you want to do your own drawing via the DrawList API)\r\n    IMGUI_API ImVec2        GetWindowSize();                            // get current window size\r\n    IMGUI_API float         GetWindowWidth();                           // get current window width (shortcut for GetWindowSize().x)\r\n    IMGUI_API float         GetWindowHeight();                          // get current window height (shortcut for GetWindowSize().y)\r\n\r\n    // Window manipulation\r\n    // - Prefer using SetNextXXX functions (before Begin) rather that SetXXX functions (after Begin).\r\n    IMGUI_API void          SetNextWindowPos(const ImVec2& pos, ImGuiCond cond = 0, const ImVec2& pivot = ImVec2(0, 0)); // set next window position. call before Begin(). use pivot=(0.5f,0.5f) to center on given point, etc.\r\n    IMGUI_API void          SetNextWindowSize(const ImVec2& size, ImGuiCond cond = 0);                  // set next window size. set axis to 0.0f to force an auto-fit on this axis. call before Begin()\r\n    IMGUI_API void          SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback = NULL, void* custom_callback_data = NULL); // set next window size limits. use -1,-1 on either X/Y axis to preserve the current size. Sizes will be rounded down. Use callback to apply non-trivial programmatic constraints.\r\n    IMGUI_API void          SetNextWindowContentSize(const ImVec2& size);                               // set next window content size (~ scrollable client area, which enforce the range of scrollbars). Not including window decorations (title bar, menu bar, etc.) nor WindowPadding. set an axis to 0.0f to leave it automatic. call before Begin()\r\n    IMGUI_API void          SetNextWindowCollapsed(bool collapsed, ImGuiCond cond = 0);                 // set next window collapsed state. call before Begin()\r\n    IMGUI_API void          SetNextWindowFocus();                                                       // set next window to be focused / top-most. call before Begin()\r\n    IMGUI_API void          SetNextWindowBgAlpha(float alpha);                                          // set next window background color alpha. helper to easily override the Alpha component of ImGuiCol_WindowBg/ChildBg/PopupBg. you may also use ImGuiWindowFlags_NoBackground.\r\n    IMGUI_API void          SetWindowPos(const ImVec2& pos, ImGuiCond cond = 0);                        // (not recommended) set current window position - call within Begin()/End(). prefer using SetNextWindowPos(), as this may incur tearing and side-effects.\r\n    IMGUI_API void          SetWindowSize(const ImVec2& size, ImGuiCond cond = 0);                      // (not recommended) set current window size - call within Begin()/End(). set to ImVec2(0, 0) to force an auto-fit. prefer using SetNextWindowSize(), as this may incur tearing and minor side-effects.\r\n    IMGUI_API void          SetWindowCollapsed(bool collapsed, ImGuiCond cond = 0);                     // (not recommended) set current window collapsed state. prefer using SetNextWindowCollapsed().\r\n    IMGUI_API void          SetWindowFocus();                                                           // (not recommended) set current window to be focused / top-most. prefer using SetNextWindowFocus().\r\n    IMGUI_API void          SetWindowFontScale(float scale);                                            // [OBSOLETE] set font scale. Adjust IO.FontGlobalScale if you want to scale all windows. This is an old API! For correct scaling, prefer to reload font + rebuild ImFontAtlas + call style.ScaleAllSizes().\r\n    IMGUI_API void          SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond = 0);      // set named window position.\r\n    IMGUI_API void          SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond = 0);    // set named window size. set axis to 0.0f to force an auto-fit on this axis.\r\n    IMGUI_API void          SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond = 0);   // set named window collapsed state\r\n    IMGUI_API void          SetWindowFocus(const char* name);                                           // set named window to be focused / top-most. use NULL to remove focus.\r\n\r\n    // Content region\r\n    // - Retrieve available space from a given point. GetContentRegionAvail() is frequently useful.\r\n    // - Those functions are bound to be redesigned (they are confusing, incomplete and the Min/Max return values are in local window coordinates which increases confusion)\r\n    IMGUI_API ImVec2        GetContentRegionAvail();                                        // == GetContentRegionMax() - GetCursorPos()\r\n    IMGUI_API ImVec2        GetContentRegionMax();                                          // current content boundaries (typically window boundaries including scrolling, or current column boundaries), in windows coordinates\r\n    IMGUI_API ImVec2        GetWindowContentRegionMin();                                    // content boundaries min for the full window (roughly (0,0)-Scroll), in window coordinates\r\n    IMGUI_API ImVec2        GetWindowContentRegionMax();                                    // content boundaries max for the full window (roughly (0,0)+Size-Scroll) where Size can be override with SetNextWindowContentSize(), in window coordinates\r\n\r\n    // Windows Scrolling\r\n    IMGUI_API float         GetScrollX();                                                   // get scrolling amount [0 .. GetScrollMaxX()]\r\n    IMGUI_API float         GetScrollY();                                                   // get scrolling amount [0 .. GetScrollMaxY()]\r\n    IMGUI_API void          SetScrollX(float scroll_x);                                     // set scrolling amount [0 .. GetScrollMaxX()]\r\n    IMGUI_API void          SetScrollY(float scroll_y);                                     // set scrolling amount [0 .. GetScrollMaxY()]\r\n    IMGUI_API float         GetScrollMaxX();                                                // get maximum scrolling amount ~~ ContentSize.x - WindowSize.x - DecorationsSize.x\r\n    IMGUI_API float         GetScrollMaxY();                                                // get maximum scrolling amount ~~ ContentSize.y - WindowSize.y - DecorationsSize.y\r\n    IMGUI_API void          SetScrollHereX(float center_x_ratio = 0.5f);                    // adjust scrolling amount to make current cursor position visible. center_x_ratio=0.0: left, 0.5: center, 1.0: right. When using to make a \"default/current item\" visible, consider using SetItemDefaultFocus() instead.\r\n    IMGUI_API void          SetScrollHereY(float center_y_ratio = 0.5f);                    // adjust scrolling amount to make current cursor position visible. center_y_ratio=0.0: top, 0.5: center, 1.0: bottom. When using to make a \"default/current item\" visible, consider using SetItemDefaultFocus() instead.\r\n    IMGUI_API void          SetScrollFromPosX(float local_x, float center_x_ratio = 0.5f);  // adjust scrolling amount to make given position visible. Generally GetCursorStartPos() + offset to compute a valid position.\r\n    IMGUI_API void          SetScrollFromPosY(float local_y, float center_y_ratio = 0.5f);  // adjust scrolling amount to make given position visible. Generally GetCursorStartPos() + offset to compute a valid position.\r\n\r\n    // Parameters stacks (shared)\r\n    IMGUI_API void          PushFont(ImFont* font);                                         // use NULL as a shortcut to push default font\r\n    IMGUI_API void          PopFont();\r\n    IMGUI_API void          PushStyleColor(ImGuiCol idx, ImU32 col);                        // modify a style color. always use this if you modify the style after NewFrame().\r\n    IMGUI_API void          PushStyleColor(ImGuiCol idx, const ImVec4& col);\r\n    IMGUI_API void          PopStyleColor(int count = 1);\r\n    IMGUI_API void          PushStyleVar(ImGuiStyleVar idx, float val);                     // modify a style float variable. always use this if you modify the style after NewFrame().\r\n    IMGUI_API void          PushStyleVar(ImGuiStyleVar idx, const ImVec2& val);             // modify a style ImVec2 variable. always use this if you modify the style after NewFrame().\r\n    IMGUI_API void          PopStyleVar(int count = 1);\r\n    IMGUI_API void          PushAllowKeyboardFocus(bool allow_keyboard_focus);              // == tab stop enable. Allow focusing using TAB/Shift-TAB, enabled by default but you can disable it for certain widgets\r\n    IMGUI_API void          PopAllowKeyboardFocus();\r\n    IMGUI_API void          PushButtonRepeat(bool repeat);                                  // in 'repeat' mode, Button*() functions return repeated true in a typematic manner (using io.KeyRepeatDelay/io.KeyRepeatRate setting). Note that you can call IsItemActive() after any Button() to tell if the button is held in the current frame.\r\n    IMGUI_API void          PopButtonRepeat();\r\n\r\n    // Parameters stacks (current window)\r\n    IMGUI_API void          PushItemWidth(float item_width);                                // push width of items for common large \"item+label\" widgets. >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -FLT_MIN always align width to the right side).\r\n    IMGUI_API void          PopItemWidth();\r\n    IMGUI_API void          SetNextItemWidth(float item_width);                             // set width of the _next_ common large \"item+label\" widget. >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -FLT_MIN always align width to the right side)\r\n    IMGUI_API float         CalcItemWidth();                                                // width of item given pushed settings and current cursor position. NOT necessarily the width of last item unlike most 'Item' functions.\r\n    IMGUI_API void          PushTextWrapPos(float wrap_local_pos_x = 0.0f);                 // push word-wrapping position for Text*() commands. < 0.0f: no wrapping; 0.0f: wrap to end of window (or column); > 0.0f: wrap at 'wrap_pos_x' position in window local space\r\n    IMGUI_API void          PopTextWrapPos();\r\n\r\n    // Style read access\r\n    // - Use the style editor (ShowStyleEditor() function) to interactively see what the colors are)\r\n    IMGUI_API ImFont*       GetFont();                                                      // get current font\r\n    IMGUI_API float         GetFontSize();                                                  // get current font size (= height in pixels) of current font with current scale applied\r\n    IMGUI_API ImVec2        GetFontTexUvWhitePixel();                                       // get UV coordinate for a while pixel, useful to draw custom shapes via the ImDrawList API\r\n    IMGUI_API ImU32         GetColorU32(ImGuiCol idx, float alpha_mul = 1.0f);              // retrieve given style color with style alpha applied and optional extra alpha multiplier, packed as a 32-bit value suitable for ImDrawList\r\n    IMGUI_API ImU32         GetColorU32(const ImVec4& col);                                 // retrieve given color with style alpha applied, packed as a 32-bit value suitable for ImDrawList\r\n    IMGUI_API ImU32         GetColorU32(ImU32 col);                                         // retrieve given color with style alpha applied, packed as a 32-bit value suitable for ImDrawList\r\n    IMGUI_API const ImVec4& GetStyleColorVec4(ImGuiCol idx);                                // retrieve style color as stored in ImGuiStyle structure. use to feed back into PushStyleColor(), otherwise use GetColorU32() to get style color with style alpha baked in.\r\n\r\n    // Cursor / Layout\r\n    // - By \"cursor\" we mean the current output position.\r\n    // - The typical widget behavior is to output themselves at the current cursor position, then move the cursor one line down.\r\n    // - You can call SameLine() between widgets to undo the last carriage return and output at the right of the preceding widget.\r\n    // - Attention! We currently have inconsistencies between window-local and absolute positions we will aim to fix with future API:\r\n    //    Window-local coordinates:   SameLine(), GetCursorPos(), SetCursorPos(), GetCursorStartPos(), GetContentRegionMax(), GetWindowContentRegion*(), PushTextWrapPos()\r\n    //    Absolute coordinate:        GetCursorScreenPos(), SetCursorScreenPos(), all ImDrawList:: functions.\r\n    IMGUI_API void          Separator();                                                    // separator, generally horizontal. inside a menu bar or in horizontal layout mode, this becomes a vertical separator.\r\n    IMGUI_API void          SameLine(float offset_from_start_x=0.0f, float spacing=-1.0f);  // call between widgets or groups to layout them horizontally. X position given in window coordinates.\r\n    IMGUI_API void          NewLine();                                                      // undo a SameLine() or force a new line when in an horizontal-layout context.\r\n    IMGUI_API void          Spacing();                                                      // add vertical spacing.\r\n    IMGUI_API void          Dummy(const ImVec2& size);                                      // add a dummy item of given size. unlike InvisibleButton(), Dummy() won't take the mouse click or be navigable into.\r\n    IMGUI_API void          Indent(float indent_w = 0.0f);                                  // move content position toward the right, by indent_w, or style.IndentSpacing if indent_w <= 0\r\n    IMGUI_API void          Unindent(float indent_w = 0.0f);                                // move content position back to the left, by indent_w, or style.IndentSpacing if indent_w <= 0\r\n    IMGUI_API void          BeginGroup();                                                   // lock horizontal starting position\r\n    IMGUI_API void          EndGroup();                                                     // unlock horizontal starting position + capture the whole group bounding box into one \"item\" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.)\r\n    IMGUI_API ImVec2        GetCursorPos();                                                 // cursor position in window coordinates (relative to window position)\r\n    IMGUI_API float         GetCursorPosX();                                                //   (some functions are using window-relative coordinates, such as: GetCursorPos, GetCursorStartPos, GetContentRegionMax, GetWindowContentRegion* etc.\r\n    IMGUI_API float         GetCursorPosY();                                                //    other functions such as GetCursorScreenPos or everything in ImDrawList::\r\n    IMGUI_API void          SetCursorPos(const ImVec2& local_pos);                          //    are using the main, absolute coordinate system.\r\n    IMGUI_API void          SetCursorPosX(float local_x);                                   //    GetWindowPos() + GetCursorPos() == GetCursorScreenPos() etc.)\r\n    IMGUI_API void          SetCursorPosY(float local_y);                                   //\r\n    IMGUI_API ImVec2        GetCursorStartPos();                                            // initial cursor position in window coordinates\r\n    IMGUI_API ImVec2        GetCursorScreenPos();                                           // cursor position in absolute coordinates (useful to work with ImDrawList API). generally top-left == GetMainViewport()->Pos == (0,0) in single viewport mode, and bottom-right == GetMainViewport()->Pos+Size == io.DisplaySize in single-viewport mode.\r\n    IMGUI_API void          SetCursorScreenPos(const ImVec2& pos);                          // cursor position in absolute coordinates\r\n    IMGUI_API void          AlignTextToFramePadding();                                      // vertically align upcoming text baseline to FramePadding.y so that it will align properly to regularly framed items (call if you have text on a line before a framed item)\r\n    IMGUI_API float         GetTextLineHeight();                                            // ~ FontSize\r\n    IMGUI_API float         GetTextLineHeightWithSpacing();                                 // ~ FontSize + style.ItemSpacing.y (distance in pixels between 2 consecutive lines of text)\r\n    IMGUI_API float         GetFrameHeight();                                               // ~ FontSize + style.FramePadding.y * 2\r\n    IMGUI_API float         GetFrameHeightWithSpacing();                                    // ~ FontSize + style.FramePadding.y * 2 + style.ItemSpacing.y (distance in pixels between 2 consecutive lines of framed widgets)\r\n\r\n    // ID stack/scopes\r\n    // Read the FAQ (docs/FAQ.md or http://dearimgui.org/faq) for more details about how ID are handled in dear imgui.\r\n    // - Those questions are answered and impacted by understanding of the ID stack system:\r\n    //   - \"Q: Why is my widget not reacting when I click on it?\"\r\n    //   - \"Q: How can I have widgets with an empty label?\"\r\n    //   - \"Q: How can I have multiple widgets with the same label?\"\r\n    // - Short version: ID are hashes of the entire ID stack. If you are creating widgets in a loop you most likely\r\n    //   want to push a unique identifier (e.g. object pointer, loop index) to uniquely differentiate them.\r\n    // - You can also use the \"Label##foobar\" syntax within widget label to distinguish them from each others.\r\n    // - In this header file we use the \"label\"/\"name\" terminology to denote a string that will be displayed + used as an ID,\r\n    //   whereas \"str_id\" denote a string that is only used as an ID and not normally displayed.\r\n    IMGUI_API void          PushID(const char* str_id);                                     // push string into the ID stack (will hash string).\r\n    IMGUI_API void          PushID(const char* str_id_begin, const char* str_id_end);       // push string into the ID stack (will hash string).\r\n    IMGUI_API void          PushID(const void* ptr_id);                                     // push pointer into the ID stack (will hash pointer).\r\n    IMGUI_API void          PushID(int int_id);                                             // push integer into the ID stack (will hash integer).\r\n    IMGUI_API void          PopID();                                                        // pop from the ID stack.\r\n    IMGUI_API ImGuiID       GetID(const char* str_id);                                      // calculate unique ID (hash of whole ID stack + given parameter). e.g. if you want to query into ImGuiStorage yourself\r\n    IMGUI_API ImGuiID       GetID(const char* str_id_begin, const char* str_id_end);\r\n    IMGUI_API ImGuiID       GetID(const void* ptr_id);\r\n\r\n    // Widgets: Text\r\n    IMGUI_API void          TextUnformatted(const char* text, const char* text_end = NULL); // raw text without formatting. Roughly equivalent to Text(\"%s\", text) but: A) doesn't require null terminated string if 'text_end' is specified, B) it's faster, no memory copy is done, no buffer size limits, recommended for long chunks of text.\r\n    IMGUI_API void          Text(const char* fmt, ...)                                      IM_FMTARGS(1); // formatted text\r\n    IMGUI_API void          TextV(const char* fmt, va_list args)                            IM_FMTLIST(1);\r\n    IMGUI_API void          TextColored(const ImVec4& col, const char* fmt, ...)            IM_FMTARGS(2); // shortcut for PushStyleColor(ImGuiCol_Text, col); Text(fmt, ...); PopStyleColor();\r\n    IMGUI_API void          TextColoredV(const ImVec4& col, const char* fmt, va_list args)  IM_FMTLIST(2);\r\n    IMGUI_API void          TextDisabled(const char* fmt, ...)                              IM_FMTARGS(1); // shortcut for PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]); Text(fmt, ...); PopStyleColor();\r\n    IMGUI_API void          TextDisabledV(const char* fmt, va_list args)                    IM_FMTLIST(1);\r\n    IMGUI_API void          TextWrapped(const char* fmt, ...)                               IM_FMTARGS(1); // shortcut for PushTextWrapPos(0.0f); Text(fmt, ...); PopTextWrapPos();. Note that this won't work on an auto-resizing window if there's no other widgets to extend the window width, yoy may need to set a size using SetNextWindowSize().\r\n    IMGUI_API void          TextWrappedV(const char* fmt, va_list args)                     IM_FMTLIST(1);\r\n    IMGUI_API void          LabelText(const char* label, const char* fmt, ...)              IM_FMTARGS(2); // display text+label aligned the same way as value+label widgets\r\n    IMGUI_API void          LabelTextV(const char* label, const char* fmt, va_list args)    IM_FMTLIST(2);\r\n    IMGUI_API void          BulletText(const char* fmt, ...)                                IM_FMTARGS(1); // shortcut for Bullet()+Text()\r\n    IMGUI_API void          BulletTextV(const char* fmt, va_list args)                      IM_FMTLIST(1);\r\n\r\n    // Widgets: Main\r\n    // - Most widgets return true when the value has been changed or when pressed/selected\r\n    // - You may also use one of the many IsItemXXX functions (e.g. IsItemActive, IsItemHovered, etc.) to query widget state.\r\n    IMGUI_API bool          Button(const char* label, const ImVec2& size = ImVec2(0, 0));   // button\r\n    IMGUI_API bool          SmallButton(const char* label);                                 // button with FramePadding=(0,0) to easily embed within text\r\n    IMGUI_API bool          InvisibleButton(const char* str_id, const ImVec2& size, ImGuiButtonFlags flags = 0); // flexible button behavior without the visuals, frequently useful to build custom behaviors using the public api (along with IsItemActive, IsItemHovered, etc.)\r\n    IMGUI_API bool          ArrowButton(const char* str_id, ImGuiDir dir);                  // square button with an arrow shape\r\n    IMGUI_API void          Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1,1), const ImVec4& tint_col = ImVec4(1,1,1,1), const ImVec4& border_col = ImVec4(0,0,0,0));\r\n    IMGUI_API bool          ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0, 0),  const ImVec2& uv1 = ImVec2(1,1), int frame_padding = -1, const ImVec4& bg_col = ImVec4(0,0,0,0), const ImVec4& tint_col = ImVec4(1,1,1,1));    // <0 frame_padding uses default frame padding settings. 0 for no padding\r\n    IMGUI_API bool          Checkbox(const char* label, bool* v);\r\n    IMGUI_API bool          CheckboxFlags(const char* label, int* flags, int flags_value);\r\n    IMGUI_API bool          CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value);\r\n    IMGUI_API bool          RadioButton(const char* label, bool active);                    // use with e.g. if (RadioButton(\"one\", my_value==1)) { my_value = 1; }\r\n    IMGUI_API bool          RadioButton(const char* label, int* v, int v_button);           // shortcut to handle the above pattern when value is an integer\r\n    IMGUI_API void          ProgressBar(float fraction, const ImVec2& size_arg = ImVec2(-FLT_MIN, 0), const char* overlay = NULL);\r\n    IMGUI_API void          Bullet();                                                       // draw a small circle + keep the cursor on the same line. advance cursor x position by GetTreeNodeToLabelSpacing(), same distance that TreeNode() uses\r\n\r\n    // Widgets: Combo Box\r\n    // - The BeginCombo()/EndCombo() api allows you to manage your contents and selection state however you want it, by creating e.g. Selectable() items.\r\n    // - The old Combo() api are helpers over BeginCombo()/EndCombo() which are kept available for convenience purpose. This is analogous to how ListBox are created.\r\n    IMGUI_API bool          BeginCombo(const char* label, const char* preview_value, ImGuiComboFlags flags = 0);\r\n    IMGUI_API void          EndCombo(); // only call EndCombo() if BeginCombo() returns true!\r\n    IMGUI_API bool          Combo(const char* label, int* current_item, const char* const items[], int items_count, int popup_max_height_in_items = -1);\r\n    IMGUI_API bool          Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int popup_max_height_in_items = -1);      // Separate items with \\0 within a string, end item-list with \\0\\0. e.g. \"One\\0Two\\0Three\\0\"\r\n    IMGUI_API bool          Combo(const char* label, int* current_item, bool(*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int popup_max_height_in_items = -1);\r\n\r\n    // Widgets: Drag Sliders\r\n    // - CTRL+Click on any drag box to turn them into an input box. Manually input values aren't clamped by default and can go off-bounds. Use ImGuiSliderFlags_AlwaysClamp to always clamp.\r\n    // - For all the Float2/Float3/Float4/Int2/Int3/Int4 versions of every functions, note that a 'float v[X]' function argument is the same as 'float* v',\r\n    //   the array syntax is just a way to document the number of elements that are expected to be accessible. You can pass address of your first element out of a contiguous set, e.g. &myvector.x\r\n    // - Adjust format string to decorate the value with a prefix, a suffix, or adapt the editing and display precision e.g. \"%.3f\" -> 1.234; \"%5.2f secs\" -> 01.23 secs; \"Biscuit: %.0f\" -> Biscuit: 1; etc.\r\n    // - Format string may also be set to NULL or use the default format (\"%f\" or \"%d\").\r\n    // - Speed are per-pixel of mouse movement (v_speed=0.2f: mouse needs to move by 5 pixels to increase value by 1). For gamepad/keyboard navigation, minimum speed is Max(v_speed, minimum_step_at_given_precision).\r\n    // - Use v_min < v_max to clamp edits to given limits. Note that CTRL+Click manual input can override those limits if ImGuiSliderFlags_AlwaysClamp is not used.\r\n    // - Use v_max = FLT_MAX / INT_MAX etc to avoid clamping to a maximum, same with v_min = -FLT_MAX / INT_MIN to avoid clamping to a minimum.\r\n    // - We use the same sets of flags for DragXXX() and SliderXXX() functions as the features are the same and it makes it easier to swap them.\r\n    // - Legacy: Pre-1.78 there are DragXXX() function signatures that takes a final `float power=1.0f' argument instead of the `ImGuiSliderFlags flags=0' argument.\r\n    //   If you get a warning converting a float to ImGuiSliderFlags, read https://github.com/ocornut/imgui/issues/3361\r\n    IMGUI_API bool          DragFloat(const char* label, float* v, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = \"%.3f\", ImGuiSliderFlags flags = 0);     // If v_min >= v_max we have no bound\r\n    IMGUI_API bool          DragFloat2(const char* label, float v[2], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = \"%.3f\", ImGuiSliderFlags flags = 0);\r\n    IMGUI_API bool          DragFloat3(const char* label, float v[3], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = \"%.3f\", ImGuiSliderFlags flags = 0);\r\n    IMGUI_API bool          DragFloat4(const char* label, float v[4], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = \"%.3f\", ImGuiSliderFlags flags = 0);\r\n    IMGUI_API bool          DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = \"%.3f\", const char* format_max = NULL, ImGuiSliderFlags flags = 0);\r\n    IMGUI_API bool          DragInt(const char* label, int* v, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = \"%d\", ImGuiSliderFlags flags = 0);  // If v_min >= v_max we have no bound\r\n    IMGUI_API bool          DragInt2(const char* label, int v[2], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = \"%d\", ImGuiSliderFlags flags = 0);\r\n    IMGUI_API bool          DragInt3(const char* label, int v[3], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = \"%d\", ImGuiSliderFlags flags = 0);\r\n    IMGUI_API bool          DragInt4(const char* label, int v[4], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = \"%d\", ImGuiSliderFlags flags = 0);\r\n    IMGUI_API bool          DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = \"%d\", const char* format_max = NULL, ImGuiSliderFlags flags = 0);\r\n    IMGUI_API bool          DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed = 1.0f, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, ImGuiSliderFlags flags = 0);\r\n    IMGUI_API bool          DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed = 1.0f, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, ImGuiSliderFlags flags = 0);\r\n\r\n    // Widgets: Regular Sliders\r\n    // - CTRL+Click on any slider to turn them into an input box. Manually input values aren't clamped by default and can go off-bounds. Use ImGuiSliderFlags_AlwaysClamp to always clamp.\r\n    // - Adjust format string to decorate the value with a prefix, a suffix, or adapt the editing and display precision e.g. \"%.3f\" -> 1.234; \"%5.2f secs\" -> 01.23 secs; \"Biscuit: %.0f\" -> Biscuit: 1; etc.\r\n    // - Format string may also be set to NULL or use the default format (\"%f\" or \"%d\").\r\n    // - Legacy: Pre-1.78 there are SliderXXX() function signatures that takes a final `float power=1.0f' argument instead of the `ImGuiSliderFlags flags=0' argument.\r\n    //   If you get a warning converting a float to ImGuiSliderFlags, read https://github.com/ocornut/imgui/issues/3361\r\n    IMGUI_API bool          SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format = \"%.3f\", ImGuiSliderFlags flags = 0);     // adjust format to decorate the value with a prefix or a suffix for in-slider labels or unit display.\r\n    IMGUI_API bool          SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format = \"%.3f\", ImGuiSliderFlags flags = 0);\r\n    IMGUI_API bool          SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format = \"%.3f\", ImGuiSliderFlags flags = 0);\r\n    IMGUI_API bool          SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format = \"%.3f\", ImGuiSliderFlags flags = 0);\r\n    IMGUI_API bool          SliderAngle(const char* label, float* v_rad, float v_degrees_min = -360.0f, float v_degrees_max = +360.0f, const char* format = \"%.0f deg\", ImGuiSliderFlags flags = 0);\r\n    IMGUI_API bool          SliderInt(const char* label, int* v, int v_min, int v_max, const char* format = \"%d\", ImGuiSliderFlags flags = 0);\r\n    IMGUI_API bool          SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format = \"%d\", ImGuiSliderFlags flags = 0);\r\n    IMGUI_API bool          SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format = \"%d\", ImGuiSliderFlags flags = 0);\r\n    IMGUI_API bool          SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format = \"%d\", ImGuiSliderFlags flags = 0);\r\n    IMGUI_API bool          SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, ImGuiSliderFlags flags = 0);\r\n    IMGUI_API bool          SliderScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_min, const void* p_max, const char* format = NULL, ImGuiSliderFlags flags = 0);\r\n    IMGUI_API bool          VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format = \"%.3f\", ImGuiSliderFlags flags = 0);\r\n    IMGUI_API bool          VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format = \"%d\", ImGuiSliderFlags flags = 0);\r\n    IMGUI_API bool          VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, ImGuiSliderFlags flags = 0);\r\n\r\n    // Widgets: Input with Keyboard\r\n    // - If you want to use InputText() with std::string or any custom dynamic string type, see misc/cpp/imgui_stdlib.h and comments in imgui_demo.cpp.\r\n    // - Most of the ImGuiInputTextFlags flags are only useful for InputText() and not for InputFloatX, InputIntX, InputDouble etc.\r\n    IMGUI_API bool          InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL);\r\n    IMGUI_API bool          InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size = ImVec2(0, 0), ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL);\r\n    IMGUI_API bool          InputTextWithHint(const char* label, const char* hint, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL);\r\n    IMGUI_API bool          InputFloat(const char* label, float* v, float step = 0.0f, float step_fast = 0.0f, const char* format = \"%.3f\", ImGuiInputTextFlags flags = 0);\r\n    IMGUI_API bool          InputFloat2(const char* label, float v[2], const char* format = \"%.3f\", ImGuiInputTextFlags flags = 0);\r\n    IMGUI_API bool          InputFloat3(const char* label, float v[3], const char* format = \"%.3f\", ImGuiInputTextFlags flags = 0);\r\n    IMGUI_API bool          InputFloat4(const char* label, float v[4], const char* format = \"%.3f\", ImGuiInputTextFlags flags = 0);\r\n    IMGUI_API bool          InputInt(const char* label, int* v, int step = 1, int step_fast = 100, ImGuiInputTextFlags flags = 0);\r\n    IMGUI_API bool          InputInt2(const char* label, int v[2], ImGuiInputTextFlags flags = 0);\r\n    IMGUI_API bool          InputInt3(const char* label, int v[3], ImGuiInputTextFlags flags = 0);\r\n    IMGUI_API bool          InputInt4(const char* label, int v[4], ImGuiInputTextFlags flags = 0);\r\n    IMGUI_API bool          InputDouble(const char* label, double* v, double step = 0.0, double step_fast = 0.0, const char* format = \"%.6f\", ImGuiInputTextFlags flags = 0);\r\n    IMGUI_API bool          InputScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_step = NULL, const void* p_step_fast = NULL, const char* format = NULL, ImGuiInputTextFlags flags = 0);\r\n    IMGUI_API bool          InputScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_step = NULL, const void* p_step_fast = NULL, const char* format = NULL, ImGuiInputTextFlags flags = 0);\r\n\r\n    // Widgets: Color Editor/Picker (tip: the ColorEdit* functions have a little color square that can be left-clicked to open a picker, and right-clicked to open an option menu.)\r\n    // - Note that in C++ a 'float v[X]' function argument is the _same_ as 'float* v', the array syntax is just a way to document the number of elements that are expected to be accessible.\r\n    // - You can pass the address of a first float element out of a contiguous structure, e.g. &myvector.x\r\n    IMGUI_API bool          ColorEdit3(const char* label, float col[3], ImGuiColorEditFlags flags = 0);\r\n    IMGUI_API bool          ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0);\r\n    IMGUI_API bool          ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags flags = 0);\r\n    IMGUI_API bool          ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags flags = 0, const float* ref_col = NULL);\r\n    IMGUI_API bool          ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0, 0)); // display a color square/button, hover for details, return true when pressed.\r\n    IMGUI_API void          SetColorEditOptions(ImGuiColorEditFlags flags);                     // initialize current options (generally on application startup) if you want to select a default format, picker type, etc. User will be able to change many settings, unless you pass the _NoOptions flag to your calls.\r\n\r\n    // Widgets: Trees\r\n    // - TreeNode functions return true when the node is open, in which case you need to also call TreePop() when you are finished displaying the tree node contents.\r\n    IMGUI_API bool          TreeNode(const char* label);\r\n    IMGUI_API bool          TreeNode(const char* str_id, const char* fmt, ...) IM_FMTARGS(2);   // helper variation to easily decorelate the id from the displayed string. Read the FAQ about why and how to use ID. to align arbitrary text at the same level as a TreeNode() you can use Bullet().\r\n    IMGUI_API bool          TreeNode(const void* ptr_id, const char* fmt, ...) IM_FMTARGS(2);   // \"\r\n    IMGUI_API bool          TreeNodeV(const char* str_id, const char* fmt, va_list args) IM_FMTLIST(2);\r\n    IMGUI_API bool          TreeNodeV(const void* ptr_id, const char* fmt, va_list args) IM_FMTLIST(2);\r\n    IMGUI_API bool          TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags = 0);\r\n    IMGUI_API bool          TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_FMTARGS(3);\r\n    IMGUI_API bool          TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_FMTARGS(3);\r\n    IMGUI_API bool          TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) IM_FMTLIST(3);\r\n    IMGUI_API bool          TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) IM_FMTLIST(3);\r\n    IMGUI_API void          TreePush(const char* str_id);                                       // ~ Indent()+PushId(). Already called by TreeNode() when returning true, but you can call TreePush/TreePop yourself if desired.\r\n    IMGUI_API void          TreePush(const void* ptr_id = NULL);                                // \"\r\n    IMGUI_API void          TreePop();                                                          // ~ Unindent()+PopId()\r\n    IMGUI_API float         GetTreeNodeToLabelSpacing();                                        // horizontal distance preceding label when using TreeNode*() or Bullet() == (g.FontSize + style.FramePadding.x*2) for a regular unframed TreeNode\r\n    IMGUI_API bool          CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags = 0);  // if returning 'true' the header is open. doesn't indent nor push on ID stack. user doesn't have to call TreePop().\r\n    IMGUI_API bool          CollapsingHeader(const char* label, bool* p_visible, ImGuiTreeNodeFlags flags = 0); // when 'p_visible != NULL': if '*p_visible==true' display an additional small close button on upper right of the header which will set the bool to false when clicked, if '*p_visible==false' don't display the header.\r\n    IMGUI_API void          SetNextItemOpen(bool is_open, ImGuiCond cond = 0);                  // set next TreeNode/CollapsingHeader open state.\r\n\r\n    // Widgets: Selectables\r\n    // - A selectable highlights when hovered, and can display another color when selected.\r\n    // - Neighbors selectable extend their highlight bounds in order to leave no gap between them. This is so a series of selected Selectable appear contiguous.\r\n    IMGUI_API bool          Selectable(const char* label, bool selected = false, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0, 0)); // \"bool selected\" carry the selection state (read-only). Selectable() is clicked is returns true so you can modify your selection state. size.x==0.0: use remaining width, size.x>0.0: specify width. size.y==0.0: use label height, size.y>0.0: specify height\r\n    IMGUI_API bool          Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0, 0));      // \"bool* p_selected\" point to the selection state (read-write), as a convenient helper.\r\n\r\n    // Widgets: List Boxes\r\n    // - This is essentially a thin wrapper to using BeginChild/EndChild with some stylistic changes.\r\n    // - The BeginListBox()/EndListBox() api allows you to manage your contents and selection state however you want it, by creating e.g. Selectable() or any items.\r\n    // - The simplified/old ListBox() api are helpers over BeginListBox()/EndListBox() which are kept available for convenience purpose. This is analoguous to how Combos are created.\r\n    // - Choose frame width:   size.x > 0.0f: custom  /  size.x < 0.0f or -FLT_MIN: right-align   /  size.x = 0.0f (default): use current ItemWidth\r\n    // - Choose frame height:  size.y > 0.0f: custom  /  size.y < 0.0f or -FLT_MIN: bottom-align  /  size.y = 0.0f (default): arbitrary default height which can fit ~7 items\r\n    IMGUI_API bool          BeginListBox(const char* label, const ImVec2& size = ImVec2(0, 0)); // open a framed scrolling region\r\n    IMGUI_API void          EndListBox();                                                       // only call EndListBox() if BeginListBox() returned true!\r\n    IMGUI_API bool          ListBox(const char* label, int* current_item, const char* const items[], int items_count, int height_in_items = -1);\r\n    IMGUI_API bool          ListBox(const char* label, int* current_item, bool (*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int height_in_items = -1);\r\n\r\n    // Widgets: Data Plotting\r\n    // - Consider using ImPlot (https://github.com/epezent/implot) which is much better!\r\n    IMGUI_API void          PlotLines(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0), int stride = sizeof(float));\r\n    IMGUI_API void          PlotLines(const char* label, float(*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0));\r\n    IMGUI_API void          PlotHistogram(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0), int stride = sizeof(float));\r\n    IMGUI_API void          PlotHistogram(const char* label, float(*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0));\r\n\r\n    // Widgets: Value() Helpers.\r\n    // - Those are merely shortcut to calling Text() with a format string. Output single value in \"name: value\" format (tip: freely declare more in your code to handle your types. you can add functions to the ImGui namespace)\r\n    IMGUI_API void          Value(const char* prefix, bool b);\r\n    IMGUI_API void          Value(const char* prefix, int v);\r\n    IMGUI_API void          Value(const char* prefix, unsigned int v);\r\n    IMGUI_API void          Value(const char* prefix, float v, const char* float_format = NULL);\r\n\r\n    // Widgets: Menus\r\n    // - Use BeginMenuBar() on a window ImGuiWindowFlags_MenuBar to append to its menu bar.\r\n    // - Use BeginMainMenuBar() to create a menu bar at the top of the screen and append to it.\r\n    // - Use BeginMenu() to create a menu. You can call BeginMenu() multiple time with the same identifier to append more items to it.\r\n    // - Not that MenuItem() keyboardshortcuts are displayed as a convenience but _not processed_ by Dear ImGui at the moment.\r\n    IMGUI_API bool          BeginMenuBar();                                                     // append to menu-bar of current window (requires ImGuiWindowFlags_MenuBar flag set on parent window).\r\n    IMGUI_API void          EndMenuBar();                                                       // only call EndMenuBar() if BeginMenuBar() returns true!\r\n    IMGUI_API bool          BeginMainMenuBar();                                                 // create and append to a full screen menu-bar.\r\n    IMGUI_API void          EndMainMenuBar();                                                   // only call EndMainMenuBar() if BeginMainMenuBar() returns true!\r\n    IMGUI_API bool          BeginMenu(const char* label, bool enabled = true);                  // create a sub-menu entry. only call EndMenu() if this returns true!\r\n    IMGUI_API void          EndMenu();                                                          // only call EndMenu() if BeginMenu() returns true!\r\n    IMGUI_API bool          MenuItem(const char* label, const char* shortcut = NULL, bool selected = false, bool enabled = true);  // return true when activated.\r\n    IMGUI_API bool          MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled = true);              // return true when activated + toggle (*p_selected) if p_selected != NULL\r\n\r\n    // Tooltips\r\n    // - Tooltip are windows following the mouse. They do not take focus away.\r\n    IMGUI_API void          BeginTooltip();                                                     // begin/append a tooltip window. to create full-featured tooltip (with any kind of items).\r\n    IMGUI_API void          EndTooltip();\r\n    IMGUI_API void          SetTooltip(const char* fmt, ...) IM_FMTARGS(1);                     // set a text-only tooltip, typically use with ImGui::IsItemHovered(). override any previous call to SetTooltip().\r\n    IMGUI_API void          SetTooltipV(const char* fmt, va_list args) IM_FMTLIST(1);\r\n\r\n    // Popups, Modals\r\n    //  - They block normal mouse hovering detection (and therefore most mouse interactions) behind them.\r\n    //  - If not modal: they can be closed by clicking anywhere outside them, or by pressing ESCAPE.\r\n    //  - Their visibility state (~bool) is held internally instead of being held by the programmer as we are used to with regular Begin*() calls.\r\n    //  - The 3 properties above are related: we need to retain popup visibility state in the library because popups may be closed as any time.\r\n    //  - You can bypass the hovering restriction by using ImGuiHoveredFlags_AllowWhenBlockedByPopup when calling IsItemHovered() or IsWindowHovered().\r\n    //  - IMPORTANT: Popup identifiers are relative to the current ID stack, so OpenPopup and BeginPopup generally needs to be at the same level of the stack.\r\n    //    This is sometimes leading to confusing mistakes. May rework this in the future.\r\n\r\n    // Popups: begin/end functions\r\n    //  - BeginPopup(): query popup state, if open start appending into the window. Call EndPopup() afterwards. ImGuiWindowFlags are forwarded to the window.\r\n    //  - BeginPopupModal(): block every interactions behind the window, cannot be closed by user, add a dimming background, has a title bar.\r\n    IMGUI_API bool          BeginPopup(const char* str_id, ImGuiWindowFlags flags = 0);                         // return true if the popup is open, and you can start outputting to it.\r\n    IMGUI_API bool          BeginPopupModal(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); // return true if the modal is open, and you can start outputting to it.\r\n    IMGUI_API void          EndPopup();                                                                         // only call EndPopup() if BeginPopupXXX() returns true!\r\n\r\n    // Popups: open/close functions\r\n    //  - OpenPopup(): set popup state to open. ImGuiPopupFlags are available for opening options.\r\n    //  - If not modal: they can be closed by clicking anywhere outside them, or by pressing ESCAPE.\r\n    //  - CloseCurrentPopup(): use inside the BeginPopup()/EndPopup() scope to close manually.\r\n    //  - CloseCurrentPopup() is called by default by Selectable()/MenuItem() when activated (FIXME: need some options).\r\n    //  - Use ImGuiPopupFlags_NoOpenOverExistingPopup to avoid opening a popup if there's already one at the same level. This is equivalent to e.g. testing for !IsAnyPopupOpen() prior to OpenPopup().\r\n    //  - Use IsWindowAppearing() after BeginPopup() to tell if a window just opened.\r\n    //  - IMPORTANT: Notice that for OpenPopupOnItemClick() we exceptionally default flags to 1 (== ImGuiPopupFlags_MouseButtonRight) for backward compatibility with older API taking 'int mouse_button = 1' parameter\r\n    IMGUI_API void          OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags = 0);                     // call to mark popup as open (don't call every frame!).\r\n    IMGUI_API void          OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags = 0);                             // id overload to facilitate calling from nested stacks\r\n    IMGUI_API void          OpenPopupOnItemClick(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1);   // helper to open popup when clicked on last item. Default to ImGuiPopupFlags_MouseButtonRight == 1. (note: actually triggers on the mouse _released_ event to be consistent with popup behaviors)\r\n    IMGUI_API void          CloseCurrentPopup();                                                                // manually close the popup we have begin-ed into.\r\n\r\n    // Popups: open+begin combined functions helpers\r\n    //  - Helpers to do OpenPopup+BeginPopup where the Open action is triggered by e.g. hovering an item and right-clicking.\r\n    //  - They are convenient to easily create context menus, hence the name.\r\n    //  - IMPORTANT: Notice that BeginPopupContextXXX takes ImGuiPopupFlags just like OpenPopup() and unlike BeginPopup(). For full consistency, we may add ImGuiWindowFlags to the BeginPopupContextXXX functions in the future.\r\n    //  - IMPORTANT: Notice that we exceptionally default their flags to 1 (== ImGuiPopupFlags_MouseButtonRight) for backward compatibility with older API taking 'int mouse_button = 1' parameter, so if you add other flags remember to re-add the ImGuiPopupFlags_MouseButtonRight.\r\n    IMGUI_API bool          BeginPopupContextItem(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1);  // open+begin popup when clicked on last item. Use str_id==NULL to associate the popup to previous item. If you want to use that on a non-interactive item such as Text() you need to pass in an explicit ID here. read comments in .cpp!\r\n    IMGUI_API bool          BeginPopupContextWindow(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1);// open+begin popup when clicked on current window.\r\n    IMGUI_API bool          BeginPopupContextVoid(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1);  // open+begin popup when clicked in void (where there are no windows).\r\n\r\n    // Popups: query functions\r\n    //  - IsPopupOpen(): return true if the popup is open at the current BeginPopup() level of the popup stack.\r\n    //  - IsPopupOpen() with ImGuiPopupFlags_AnyPopupId: return true if any popup is open at the current BeginPopup() level of the popup stack.\r\n    //  - IsPopupOpen() with ImGuiPopupFlags_AnyPopupId + ImGuiPopupFlags_AnyPopupLevel: return true if any popup is open.\r\n    IMGUI_API bool          IsPopupOpen(const char* str_id, ImGuiPopupFlags flags = 0);                         // return true if the popup is open.\r\n\r\n    // Tables\r\n    // - Full-featured replacement for old Columns API.\r\n    // - See Demo->Tables for demo code.\r\n    // - See top of imgui_tables.cpp for general commentary.\r\n    // - See ImGuiTableFlags_ and ImGuiTableColumnFlags_ enums for a description of available flags.\r\n    // The typical call flow is:\r\n    // - 1. Call BeginTable().\r\n    // - 2. Optionally call TableSetupColumn() to submit column name/flags/defaults.\r\n    // - 3. Optionally call TableSetupScrollFreeze() to request scroll freezing of columns/rows.\r\n    // - 4. Optionally call TableHeadersRow() to submit a header row. Names are pulled from TableSetupColumn() data.\r\n    // - 5. Populate contents:\r\n    //    - In most situations you can use TableNextRow() + TableSetColumnIndex(N) to start appending into a column.\r\n    //    - If you are using tables as a sort of grid, where every columns is holding the same type of contents,\r\n    //      you may prefer using TableNextColumn() instead of TableNextRow() + TableSetColumnIndex().\r\n    //      TableNextColumn() will automatically wrap-around into the next row if needed.\r\n    //    - IMPORTANT: Comparatively to the old Columns() API, we need to call TableNextColumn() for the first column!\r\n    //    - Summary of possible call flow:\r\n    //        --------------------------------------------------------------------------------------------------------\r\n    //        TableNextRow() -> TableSetColumnIndex(0) -> Text(\"Hello 0\") -> TableSetColumnIndex(1) -> Text(\"Hello 1\")  // OK\r\n    //        TableNextRow() -> TableNextColumn()      -> Text(\"Hello 0\") -> TableNextColumn()      -> Text(\"Hello 1\")  // OK\r\n    //                          TableNextColumn()      -> Text(\"Hello 0\") -> TableNextColumn()      -> Text(\"Hello 1\")  // OK: TableNextColumn() automatically gets to next row!\r\n    //        TableNextRow()                           -> Text(\"Hello 0\")                                               // Not OK! Missing TableSetColumnIndex() or TableNextColumn()! Text will not appear!\r\n    //        --------------------------------------------------------------------------------------------------------\r\n    // - 5. Call EndTable()\r\n    IMGUI_API bool          BeginTable(const char* str_id, int column, ImGuiTableFlags flags = 0, const ImVec2& outer_size = ImVec2(0.0f, 0.0f), float inner_width = 0.0f);\r\n    IMGUI_API void          EndTable();                                 // only call EndTable() if BeginTable() returns true!\r\n    IMGUI_API void          TableNextRow(ImGuiTableRowFlags row_flags = 0, float min_row_height = 0.0f); // append into the first cell of a new row.\r\n    IMGUI_API bool          TableNextColumn();                          // append into the next column (or first column of next row if currently in last column). Return true when column is visible.\r\n    IMGUI_API bool          TableSetColumnIndex(int column_n);          // append into the specified column. Return true when column is visible.\r\n\r\n    // Tables: Headers & Columns declaration\r\n    // - Use TableSetupColumn() to specify label, resizing policy, default width/weight, id, various other flags etc.\r\n    // - Use TableHeadersRow() to create a header row and automatically submit a TableHeader() for each column.\r\n    //   Headers are required to perform: reordering, sorting, and opening the context menu.\r\n    //   The context menu can also be made available in columns body using ImGuiTableFlags_ContextMenuInBody.\r\n    // - You may manually submit headers using TableNextRow() + TableHeader() calls, but this is only useful in\r\n    //   some advanced use cases (e.g. adding custom widgets in header row).\r\n    // - Use TableSetupScrollFreeze() to lock columns/rows so they stay visible when scrolled.\r\n    IMGUI_API void          TableSetupColumn(const char* label, ImGuiTableColumnFlags flags = 0, float init_width_or_weight = 0.0f, ImGuiID user_id = 0);\r\n    IMGUI_API void          TableSetupScrollFreeze(int cols, int rows); // lock columns/rows so they stay visible when scrolled.\r\n    IMGUI_API void          TableHeadersRow();                          // submit all headers cells based on data provided to TableSetupColumn() + submit context menu\r\n    IMGUI_API void          TableHeader(const char* label);             // submit one header cell manually (rarely used)\r\n\r\n    // Tables: Sorting\r\n    // - Call TableGetSortSpecs() to retrieve latest sort specs for the table. NULL when not sorting.\r\n    // - When 'SpecsDirty == true' you should sort your data. It will be true when sorting specs have changed\r\n    //   since last call, or the first time. Make sure to set 'SpecsDirty = false' after sorting, else you may\r\n    //   wastefully sort your data every frame!\r\n    // - Lifetime: don't hold on this pointer over multiple frames or past any subsequent call to BeginTable().\r\n    IMGUI_API ImGuiTableSortSpecs*  TableGetSortSpecs();                        // get latest sort specs for the table (NULL if not sorting).\r\n\r\n    // Tables: Miscellaneous functions\r\n    // - Functions args 'int column_n' treat the default value of -1 as the same as passing the current column index.\r\n    IMGUI_API int                   TableGetColumnCount();                      // return number of columns (value passed to BeginTable)\r\n    IMGUI_API int                   TableGetColumnIndex();                      // return current column index.\r\n    IMGUI_API int                   TableGetRowIndex();                         // return current row index.\r\n    IMGUI_API const char*           TableGetColumnName(int column_n = -1);      // return \"\" if column didn't have a name declared by TableSetupColumn(). Pass -1 to use current column.\r\n    IMGUI_API ImGuiTableColumnFlags TableGetColumnFlags(int column_n = -1);     // return column flags so you can query their Enabled/Visible/Sorted/Hovered status flags. Pass -1 to use current column.\r\n    IMGUI_API void                  TableSetColumnEnabled(int column_n, bool v);// change user accessible enabled/disabled state of a column. Set to false to hide the column. User can use the context menu to change this themselves (right-click in headers, or right-click in columns body with ImGuiTableFlags_ContextMenuInBody)\r\n    IMGUI_API void                  TableSetBgColor(ImGuiTableBgTarget target, ImU32 color, int column_n = -1);  // change the color of a cell, row, or column. See ImGuiTableBgTarget_ flags for details.\r\n\r\n    // Legacy Columns API (prefer using Tables!)\r\n    // - You can also use SameLine(pos_x) to mimic simplified columns.\r\n    IMGUI_API void          Columns(int count = 1, const char* id = NULL, bool border = true);\r\n    IMGUI_API void          NextColumn();                                                       // next column, defaults to current row or next row if the current row is finished\r\n    IMGUI_API int           GetColumnIndex();                                                   // get current column index\r\n    IMGUI_API float         GetColumnWidth(int column_index = -1);                              // get column width (in pixels). pass -1 to use current column\r\n    IMGUI_API void          SetColumnWidth(int column_index, float width);                      // set column width (in pixels). pass -1 to use current column\r\n    IMGUI_API float         GetColumnOffset(int column_index = -1);                             // get position of column line (in pixels, from the left side of the contents region). pass -1 to use current column, otherwise 0..GetColumnsCount() inclusive. column 0 is typically 0.0f\r\n    IMGUI_API void          SetColumnOffset(int column_index, float offset_x);                  // set position of column line (in pixels, from the left side of the contents region). pass -1 to use current column\r\n    IMGUI_API int           GetColumnsCount();\r\n\r\n    // Tab Bars, Tabs\r\n    IMGUI_API bool          BeginTabBar(const char* str_id, ImGuiTabBarFlags flags = 0);        // create and append into a TabBar\r\n    IMGUI_API void          EndTabBar();                                                        // only call EndTabBar() if BeginTabBar() returns true!\r\n    IMGUI_API bool          BeginTabItem(const char* label, bool* p_open = NULL, ImGuiTabItemFlags flags = 0); // create a Tab. Returns true if the Tab is selected.\r\n    IMGUI_API void          EndTabItem();                                                       // only call EndTabItem() if BeginTabItem() returns true!\r\n    IMGUI_API bool          TabItemButton(const char* label, ImGuiTabItemFlags flags = 0);      // create a Tab behaving like a button. return true when clicked. cannot be selected in the tab bar.\r\n    IMGUI_API void          SetTabItemClosed(const char* tab_or_docked_window_label);           // notify TabBar or Docking system of a closed tab/window ahead (useful to reduce visual flicker on reorderable tab bars). For tab-bar: call after BeginTabBar() and before Tab submissions. Otherwise call with a window name.\r\n\r\n    // Logging/Capture\r\n    // - All text output from the interface can be captured into tty/file/clipboard. By default, tree nodes are automatically opened during logging.\r\n    IMGUI_API void          LogToTTY(int auto_open_depth = -1);                                 // start logging to tty (stdout)\r\n    IMGUI_API void          LogToFile(int auto_open_depth = -1, const char* filename = NULL);   // start logging to file\r\n    IMGUI_API void          LogToClipboard(int auto_open_depth = -1);                           // start logging to OS clipboard\r\n    IMGUI_API void          LogFinish();                                                        // stop logging (close file, etc.)\r\n    IMGUI_API void          LogButtons();                                                       // helper to display buttons for logging to tty/file/clipboard\r\n    IMGUI_API void          LogText(const char* fmt, ...) IM_FMTARGS(1);                        // pass text data straight to log (without being displayed)\r\n    IMGUI_API void          LogTextV(const char* fmt, va_list args) IM_FMTLIST(1);\r\n\r\n    // Drag and Drop\r\n    // - On source items, call BeginDragDropSource(), if it returns true also call SetDragDropPayload() + EndDragDropSource().\r\n    // - On target candidates, call BeginDragDropTarget(), if it returns true also call AcceptDragDropPayload() + EndDragDropTarget().\r\n    // - If you stop calling BeginDragDropSource() the payload is preserved however it won't have a preview tooltip (we currently display a fallback \"...\" tooltip, see #1725)\r\n    // - An item can be both drag source and drop target.\r\n    IMGUI_API bool          BeginDragDropSource(ImGuiDragDropFlags flags = 0);                                      // call after submitting an item which may be dragged. when this return true, you can call SetDragDropPayload() + EndDragDropSource()\r\n    IMGUI_API bool          SetDragDropPayload(const char* type, const void* data, size_t sz, ImGuiCond cond = 0);  // type is a user defined string of maximum 32 characters. Strings starting with '_' are reserved for dear imgui internal types. Data is copied and held by imgui. Return true when payload has been accepted.\r\n    IMGUI_API void          EndDragDropSource();                                                                    // only call EndDragDropSource() if BeginDragDropSource() returns true!\r\n    IMGUI_API bool                  BeginDragDropTarget();                                                          // call after submitting an item that may receive a payload. If this returns true, you can call AcceptDragDropPayload() + EndDragDropTarget()\r\n    IMGUI_API const ImGuiPayload*   AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags = 0);          // accept contents of a given type. If ImGuiDragDropFlags_AcceptBeforeDelivery is set you can peek into the payload before the mouse button is released.\r\n    IMGUI_API void                  EndDragDropTarget();                                                            // only call EndDragDropTarget() if BeginDragDropTarget() returns true!\r\n    IMGUI_API const ImGuiPayload*   GetDragDropPayload();                                                           // peek directly into the current payload from anywhere. may return NULL. use ImGuiPayload::IsDataType() to test for the payload type.\r\n\r\n    // Disabling [BETA API]\r\n    // - Disable all user interactions and dim items visuals (applying style.DisabledAlpha over current colors)\r\n    // - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled)\r\n    // - BeginDisabled(false) essentially does nothing useful but is provided to facilitate use of boolean expressions. If you can avoid calling BeginDisabled(False)/EndDisabled() best to avoid it.\r\n    IMGUI_API void          BeginDisabled(bool disabled = true);\r\n    IMGUI_API void          EndDisabled();\r\n\r\n    // Clipping\r\n    // - Mouse hovering is affected by ImGui::PushClipRect() calls, unlike direct calls to ImDrawList::PushClipRect() which are render only.\r\n    IMGUI_API void          PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect);\r\n    IMGUI_API void          PopClipRect();\r\n\r\n    // Focus, Activation\r\n    // - Prefer using \"SetItemDefaultFocus()\" over \"if (IsWindowAppearing()) SetScrollHereY()\" when applicable to signify \"this is the default item\"\r\n    IMGUI_API void          SetItemDefaultFocus();                                              // make last item the default focused item of a window.\r\n    IMGUI_API void          SetKeyboardFocusHere(int offset = 0);                               // focus keyboard on the next widget. Use positive 'offset' to access sub components of a multiple component widget. Use -1 to access previous widget.\r\n\r\n    // Item/Widgets Utilities and Query Functions\r\n    // - Most of the functions are referring to the previous Item that has been submitted.\r\n    // - See Demo Window under \"Widgets->Querying Status\" for an interactive visualization of most of those functions.\r\n    IMGUI_API bool          IsItemHovered(ImGuiHoveredFlags flags = 0);                         // is the last item hovered? (and usable, aka not blocked by a popup, etc.). See ImGuiHoveredFlags for more options.\r\n    IMGUI_API bool          IsItemActive();                                                     // is the last item active? (e.g. button being held, text field being edited. This will continuously return true while holding mouse button on an item. Items that don't interact will always return false)\r\n    IMGUI_API bool          IsItemFocused();                                                    // is the last item focused for keyboard/gamepad navigation?\r\n    IMGUI_API bool          IsItemClicked(ImGuiMouseButton mouse_button = 0);                   // is the last item hovered and mouse clicked on? (**)  == IsMouseClicked(mouse_button) && IsItemHovered()Important. (**) this it NOT equivalent to the behavior of e.g. Button(). Read comments in function definition.\r\n    IMGUI_API bool          IsItemVisible();                                                    // is the last item visible? (items may be out of sight because of clipping/scrolling)\r\n    IMGUI_API bool          IsItemEdited();                                                     // did the last item modify its underlying value this frame? or was pressed? This is generally the same as the \"bool\" return value of many widgets.\r\n    IMGUI_API bool          IsItemActivated();                                                  // was the last item just made active (item was previously inactive).\r\n    IMGUI_API bool          IsItemDeactivated();                                                // was the last item just made inactive (item was previously active). Useful for Undo/Redo patterns with widgets that requires continuous editing.\r\n    IMGUI_API bool          IsItemDeactivatedAfterEdit();                                       // was the last item just made inactive and made a value change when it was active? (e.g. Slider/Drag moved). Useful for Undo/Redo patterns with widgets that requires continuous editing. Note that you may get false positives (some widgets such as Combo()/ListBox()/Selectable() will return true even when clicking an already selected item).\r\n    IMGUI_API bool          IsItemToggledOpen();                                                // was the last item open state toggled? set by TreeNode().\r\n    IMGUI_API bool          IsAnyItemHovered();                                                 // is any item hovered?\r\n    IMGUI_API bool          IsAnyItemActive();                                                  // is any item active?\r\n    IMGUI_API bool          IsAnyItemFocused();                                                 // is any item focused?\r\n    IMGUI_API ImVec2        GetItemRectMin();                                                   // get upper-left bounding rectangle of the last item (screen space)\r\n    IMGUI_API ImVec2        GetItemRectMax();                                                   // get lower-right bounding rectangle of the last item (screen space)\r\n    IMGUI_API ImVec2        GetItemRectSize();                                                  // get size of last item\r\n    IMGUI_API void          SetItemAllowOverlap();                                              // allow last item to be overlapped by a subsequent item. sometimes useful with invisible buttons, selectables, etc. to catch unused area.\r\n\r\n    // Viewports\r\n    // - Currently represents the Platform Window created by the application which is hosting our Dear ImGui windows.\r\n    // - In 'docking' branch with multi-viewport enabled, we extend this concept to have multiple active viewports.\r\n    // - In the future we will extend this concept further to also represent Platform Monitor and support a \"no main platform window\" operation mode.\r\n    IMGUI_API ImGuiViewport* GetMainViewport();                                                 // return primary/default viewport. This can never be NULL.\r\n\r\n    // Miscellaneous Utilities\r\n    IMGUI_API bool          IsRectVisible(const ImVec2& size);                                  // test if rectangle (of given size, starting from cursor position) is visible / not clipped.\r\n    IMGUI_API bool          IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max);      // test if rectangle (in screen space) is visible / not clipped. to perform coarse clipping on user's side.\r\n    IMGUI_API double        GetTime();                                                          // get global imgui time. incremented by io.DeltaTime every frame.\r\n    IMGUI_API int           GetFrameCount();                                                    // get global imgui frame count. incremented by 1 every frame.\r\n    IMGUI_API ImDrawList*   GetBackgroundDrawList();                                            // this draw list will be the first rendering one. Useful to quickly draw shapes/text behind dear imgui contents.\r\n    IMGUI_API ImDrawList*   GetForegroundDrawList();                                            // this draw list will be the last rendered one. Useful to quickly draw shapes/text over dear imgui contents.\r\n    IMGUI_API ImDrawListSharedData* GetDrawListSharedData();                                    // you may use this when creating your own ImDrawList instances.\r\n    IMGUI_API const char*   GetStyleColorName(ImGuiCol idx);                                    // get a string corresponding to the enum value (for display, saving, etc.).\r\n    IMGUI_API void          SetStateStorage(ImGuiStorage* storage);                             // replace current window storage with our own (if you want to manipulate it yourself, typically clear subsection of it)\r\n    IMGUI_API ImGuiStorage* GetStateStorage();\r\n    IMGUI_API bool          BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags flags = 0); // helper to create a child window / scrolling region that looks like a normal widget frame\r\n    IMGUI_API void          EndChildFrame();                                                    // always call EndChildFrame() regardless of BeginChildFrame() return values (which indicates a collapsed/clipped window)\r\n\r\n    // Text Utilities\r\n    IMGUI_API ImVec2        CalcTextSize(const char* text, const char* text_end = NULL, bool hide_text_after_double_hash = false, float wrap_width = -1.0f);\r\n\r\n    // Color Utilities\r\n    IMGUI_API ImVec4        ColorConvertU32ToFloat4(ImU32 in);\r\n    IMGUI_API ImU32         ColorConvertFloat4ToU32(const ImVec4& in);\r\n    IMGUI_API void          ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v);\r\n    IMGUI_API void          ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b);\r\n\r\n    // Inputs Utilities: Keyboard\r\n    // Without IMGUI_DISABLE_OBSOLETE_KEYIO: (legacy support)\r\n    //   - For 'ImGuiKey key' you can still use your legacy native/user indices according to how your backend/engine stored them in io.KeysDown[].\r\n    // With IMGUI_DISABLE_OBSOLETE_KEYIO: (this is the way forward)\r\n    //   - Any use of 'ImGuiKey' will assert when key < 512 will be passed, previously reserved as native/user keys indices\r\n    //   - GetKeyIndex() is pass-through and therefore deprecated (gone if IMGUI_DISABLE_OBSOLETE_KEYIO is defined)\r\n    IMGUI_API bool          IsKeyDown(ImGuiKey key);                                            // is key being held.\r\n    IMGUI_API bool          IsKeyPressed(ImGuiKey key, bool repeat = true);                     // was key pressed (went from !Down to Down)? if repeat=true, uses io.KeyRepeatDelay / KeyRepeatRate\r\n    IMGUI_API bool          IsKeyReleased(ImGuiKey key);                                        // was key released (went from Down to !Down)?\r\n    IMGUI_API int           GetKeyPressedAmount(ImGuiKey key, float repeat_delay, float rate);  // uses provided repeat rate/delay. return a count, most often 0 or 1 but might be >1 if RepeatRate is small enough that DeltaTime > RepeatRate\r\n    IMGUI_API const char*   GetKeyName(ImGuiKey key);                                           // [DEBUG] returns English name of the key. Those names a provided for debugging purpose and are not meant to be saved persistently not compared.\r\n    IMGUI_API void          CaptureKeyboardFromApp(bool want_capture_keyboard_value = true);    // attention: misleading name! manually override io.WantCaptureKeyboard flag next frame (said flag is entirely left for your application to handle). e.g. force capture keyboard when your widget is being hovered. This is equivalent to setting \"io.WantCaptureKeyboard = want_capture_keyboard_value\"; after the next NewFrame() call.\r\n\r\n    // Inputs Utilities: Mouse\r\n    // - To refer to a mouse button, you may use named enums in your code e.g. ImGuiMouseButton_Left, ImGuiMouseButton_Right.\r\n    // - You can also use regular integer: it is forever guaranteed that 0=Left, 1=Right, 2=Middle.\r\n    // - Dragging operations are only reported after mouse has moved a certain distance away from the initial clicking position (see 'lock_threshold' and 'io.MouseDraggingThreshold')\r\n    IMGUI_API bool          IsMouseDown(ImGuiMouseButton button);                               // is mouse button held?\r\n    IMGUI_API bool          IsMouseClicked(ImGuiMouseButton button, bool repeat = false);       // did mouse button clicked? (went from !Down to Down). Same as GetMouseClickedCount() == 1.\r\n    IMGUI_API bool          IsMouseReleased(ImGuiMouseButton button);                           // did mouse button released? (went from Down to !Down)\r\n    IMGUI_API bool          IsMouseDoubleClicked(ImGuiMouseButton button);                      // did mouse button double-clicked? Same as GetMouseClickedCount() == 2. (note that a double-click will also report IsMouseClicked() == true)\r\n    IMGUI_API int           GetMouseClickedCount(ImGuiMouseButton button);                      // return the number of successive mouse-clicks at the time where a click happen (otherwise 0).\r\n    IMGUI_API bool          IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip = true);// is mouse hovering given bounding rect (in screen space). clipped by current clipping settings, but disregarding of other consideration of focus/window ordering/popup-block.\r\n    IMGUI_API bool          IsMousePosValid(const ImVec2* mouse_pos = NULL);                    // by convention we use (-FLT_MAX,-FLT_MAX) to denote that there is no mouse available\r\n    IMGUI_API bool          IsAnyMouseDown();                                                   // [WILL OBSOLETE] is any mouse button held? This was designed for backends, but prefer having backend maintain a mask of held mouse buttons, because upcoming input queue system will make this invalid.\r\n    IMGUI_API ImVec2        GetMousePos();                                                      // shortcut to ImGui::GetIO().MousePos provided by user, to be consistent with other calls\r\n    IMGUI_API ImVec2        GetMousePosOnOpeningCurrentPopup();                                 // retrieve mouse position at the time of opening popup we have BeginPopup() into (helper to avoid user backing that value themselves)\r\n    IMGUI_API bool          IsMouseDragging(ImGuiMouseButton button, float lock_threshold = -1.0f);         // is mouse dragging? (if lock_threshold < -1.0f, uses io.MouseDraggingThreshold)\r\n    IMGUI_API ImVec2        GetMouseDragDelta(ImGuiMouseButton button = 0, float lock_threshold = -1.0f);   // return the delta from the initial clicking position while the mouse button is pressed or was just released. This is locked and return 0.0f until the mouse moves past a distance threshold at least once (if lock_threshold < -1.0f, uses io.MouseDraggingThreshold)\r\n    IMGUI_API void          ResetMouseDragDelta(ImGuiMouseButton button = 0);                   //\r\n    IMGUI_API ImGuiMouseCursor GetMouseCursor();                                                // get desired cursor type, reset in ImGui::NewFrame(), this is updated during the frame. valid before Render(). If you use software rendering by setting io.MouseDrawCursor ImGui will render those for you\r\n    IMGUI_API void          SetMouseCursor(ImGuiMouseCursor cursor_type);                       // set desired cursor type\r\n    IMGUI_API void          CaptureMouseFromApp(bool want_capture_mouse_value = true);          // attention: misleading name! manually override io.WantCaptureMouse flag next frame (said flag is entirely left for your application to handle). This is equivalent to setting \"io.WantCaptureMouse = want_capture_mouse_value;\" after the next NewFrame() call.\r\n\r\n    // Clipboard Utilities\r\n    // - Also see the LogToClipboard() function to capture GUI into clipboard, or easily output text data to the clipboard.\r\n    IMGUI_API const char*   GetClipboardText();\r\n    IMGUI_API void          SetClipboardText(const char* text);\r\n\r\n    // Settings/.Ini Utilities\r\n    // - The disk functions are automatically called if io.IniFilename != NULL (default is \"imgui.ini\").\r\n    // - Set io.IniFilename to NULL to load/save manually. Read io.WantSaveIniSettings description about handling .ini saving manually.\r\n    // - Important: default value \"imgui.ini\" is relative to current working dir! Most apps will want to lock this to an absolute path (e.g. same path as executables).\r\n    IMGUI_API void          LoadIniSettingsFromDisk(const char* ini_filename);                  // call after CreateContext() and before the first call to NewFrame(). NewFrame() automatically calls LoadIniSettingsFromDisk(io.IniFilename).\r\n    IMGUI_API void          LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size=0); // call after CreateContext() and before the first call to NewFrame() to provide .ini data from your own data source.\r\n    IMGUI_API void          SaveIniSettingsToDisk(const char* ini_filename);                    // this is automatically called (if io.IniFilename is not empty) a few seconds after any modification that should be reflected in the .ini file (and also by DestroyContext).\r\n    IMGUI_API const char*   SaveIniSettingsToMemory(size_t* out_ini_size = NULL);               // return a zero-terminated string with the .ini data which you can save by your own mean. call when io.WantSaveIniSettings is set, then save data by your own mean and clear io.WantSaveIniSettings.\r\n\r\n    // Debug Utilities\r\n    // - This is used by the IMGUI_CHECKVERSION() macro.\r\n    IMGUI_API bool          DebugCheckVersionAndDataLayout(const char* version_str, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_drawvert, size_t sz_drawidx); // This is called by IMGUI_CHECKVERSION() macro.\r\n\r\n    // Memory Allocators\r\n    // - Those functions are not reliant on the current context.\r\n    // - DLL users: heaps and globals are not shared across DLL boundaries! You will need to call SetCurrentContext() + SetAllocatorFunctions()\r\n    //   for each static/DLL boundary you are calling from. Read \"Context and Memory Allocators\" section of imgui.cpp for more details.\r\n    IMGUI_API void          SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data = NULL);\r\n    IMGUI_API void          GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data);\r\n    IMGUI_API void*         MemAlloc(size_t size);\r\n    IMGUI_API void          MemFree(void* ptr);\r\n\r\n} // namespace ImGui\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Flags & Enumerations\r\n//-----------------------------------------------------------------------------\r\n\r\n// Flags for ImGui::Begin()\r\nenum ImGuiWindowFlags_\r\n{\r\n    ImGuiWindowFlags_None                   = 0,\r\n    ImGuiWindowFlags_NoTitleBar             = 1 << 0,   // Disable title-bar\r\n    ImGuiWindowFlags_NoResize               = 1 << 1,   // Disable user resizing with the lower-right grip\r\n    ImGuiWindowFlags_NoMove                 = 1 << 2,   // Disable user moving the window\r\n    ImGuiWindowFlags_NoScrollbar            = 1 << 3,   // Disable scrollbars (window can still scroll with mouse or programmatically)\r\n    ImGuiWindowFlags_NoScrollWithMouse      = 1 << 4,   // Disable user vertically scrolling with mouse wheel. On child window, mouse wheel will be forwarded to the parent unless NoScrollbar is also set.\r\n    ImGuiWindowFlags_NoCollapse             = 1 << 5,   // Disable user collapsing window by double-clicking on it. Also referred to as Window Menu Button (e.g. within a docking node).\r\n    ImGuiWindowFlags_AlwaysAutoResize       = 1 << 6,   // Resize every window to its content every frame\r\n    ImGuiWindowFlags_NoBackground           = 1 << 7,   // Disable drawing background color (WindowBg, etc.) and outside border. Similar as using SetNextWindowBgAlpha(0.0f).\r\n    ImGuiWindowFlags_NoSavedSettings        = 1 << 8,   // Never load/save settings in .ini file\r\n    ImGuiWindowFlags_NoMouseInputs          = 1 << 9,   // Disable catching mouse, hovering test with pass through.\r\n    ImGuiWindowFlags_MenuBar                = 1 << 10,  // Has a menu-bar\r\n    ImGuiWindowFlags_HorizontalScrollbar    = 1 << 11,  // Allow horizontal scrollbar to appear (off by default). You may use SetNextWindowContentSize(ImVec2(width,0.0f)); prior to calling Begin() to specify width. Read code in imgui_demo in the \"Horizontal Scrolling\" section.\r\n    ImGuiWindowFlags_NoFocusOnAppearing     = 1 << 12,  // Disable taking focus when transitioning from hidden to visible state\r\n    ImGuiWindowFlags_NoBringToFrontOnFocus  = 1 << 13,  // Disable bringing window to front when taking focus (e.g. clicking on it or programmatically giving it focus)\r\n    ImGuiWindowFlags_AlwaysVerticalScrollbar= 1 << 14,  // Always show vertical scrollbar (even if ContentSize.y < Size.y)\r\n    ImGuiWindowFlags_AlwaysHorizontalScrollbar=1<< 15,  // Always show horizontal scrollbar (even if ContentSize.x < Size.x)\r\n    ImGuiWindowFlags_AlwaysUseWindowPadding = 1 << 16,  // Ensure child windows without border uses style.WindowPadding (ignored by default for non-bordered child windows, because more convenient)\r\n    ImGuiWindowFlags_NoNavInputs            = 1 << 18,  // No gamepad/keyboard navigation within the window\r\n    ImGuiWindowFlags_NoNavFocus             = 1 << 19,  // No focusing toward this window with gamepad/keyboard navigation (e.g. skipped by CTRL+TAB)\r\n    ImGuiWindowFlags_UnsavedDocument        = 1 << 20,  // Display a dot next to the title. When used in a tab/docking context, tab is selected when clicking the X + closure is not assumed (will wait for user to stop submitting the tab). Otherwise closure is assumed when pressing the X, so if you keep submitting the tab may reappear at end of tab bar.\r\n    ImGuiWindowFlags_NoNav                  = ImGuiWindowFlags_NoNavInputs | ImGuiWindowFlags_NoNavFocus,\r\n    ImGuiWindowFlags_NoDecoration           = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoCollapse,\r\n    ImGuiWindowFlags_NoInputs               = ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs | ImGuiWindowFlags_NoNavFocus,\r\n\r\n    // [Internal]\r\n    ImGuiWindowFlags_NavFlattened           = 1 << 23,  // [BETA] On child window: allow gamepad/keyboard navigation to cross over parent border to this child or between sibling child windows.\r\n    ImGuiWindowFlags_ChildWindow            = 1 << 24,  // Don't use! For internal use by BeginChild()\r\n    ImGuiWindowFlags_Tooltip                = 1 << 25,  // Don't use! For internal use by BeginTooltip()\r\n    ImGuiWindowFlags_Popup                  = 1 << 26,  // Don't use! For internal use by BeginPopup()\r\n    ImGuiWindowFlags_Modal                  = 1 << 27,  // Don't use! For internal use by BeginPopupModal()\r\n    ImGuiWindowFlags_ChildMenu              = 1 << 28   // Don't use! For internal use by BeginMenu()\r\n    //ImGuiWindowFlags_ResizeFromAnySide    = 1 << 17,  // [Obsolete] --> Set io.ConfigWindowsResizeFromEdges=true and make sure mouse cursors are supported by backend (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors)\r\n};\r\n\r\n// Flags for ImGui::InputText()\r\nenum ImGuiInputTextFlags_\r\n{\r\n    ImGuiInputTextFlags_None                = 0,\r\n    ImGuiInputTextFlags_CharsDecimal        = 1 << 0,   // Allow 0123456789.+-*/\r\n    ImGuiInputTextFlags_CharsHexadecimal    = 1 << 1,   // Allow 0123456789ABCDEFabcdef\r\n    ImGuiInputTextFlags_CharsUppercase      = 1 << 2,   // Turn a..z into A..Z\r\n    ImGuiInputTextFlags_CharsNoBlank        = 1 << 3,   // Filter out spaces, tabs\r\n    ImGuiInputTextFlags_AutoSelectAll       = 1 << 4,   // Select entire text when first taking mouse focus\r\n    ImGuiInputTextFlags_EnterReturnsTrue    = 1 << 5,   // Return 'true' when Enter is pressed (as opposed to every time the value was modified). Consider looking at the IsItemDeactivatedAfterEdit() function.\r\n    ImGuiInputTextFlags_CallbackCompletion  = 1 << 6,   // Callback on pressing TAB (for completion handling)\r\n    ImGuiInputTextFlags_CallbackHistory     = 1 << 7,   // Callback on pressing Up/Down arrows (for history handling)\r\n    ImGuiInputTextFlags_CallbackAlways      = 1 << 8,   // Callback on each iteration. User code may query cursor position, modify text buffer.\r\n    ImGuiInputTextFlags_CallbackCharFilter  = 1 << 9,   // Callback on character inputs to replace or discard them. Modify 'EventChar' to replace or discard, or return 1 in callback to discard.\r\n    ImGuiInputTextFlags_AllowTabInput       = 1 << 10,  // Pressing TAB input a '\\t' character into the text field\r\n    ImGuiInputTextFlags_CtrlEnterForNewLine = 1 << 11,  // In multi-line mode, unfocus with Enter, add new line with Ctrl+Enter (default is opposite: unfocus with Ctrl+Enter, add line with Enter).\r\n    ImGuiInputTextFlags_NoHorizontalScroll  = 1 << 12,  // Disable following the cursor horizontally\r\n    ImGuiInputTextFlags_AlwaysOverwrite     = 1 << 13,  // Overwrite mode\r\n    ImGuiInputTextFlags_ReadOnly            = 1 << 14,  // Read-only mode\r\n    ImGuiInputTextFlags_Password            = 1 << 15,  // Password mode, display all characters as '*'\r\n    ImGuiInputTextFlags_NoUndoRedo          = 1 << 16,  // Disable undo/redo. Note that input text owns the text data while active, if you want to provide your own undo/redo stack you need e.g. to call ClearActiveID().\r\n    ImGuiInputTextFlags_CharsScientific     = 1 << 17,  // Allow 0123456789.+-*/eE (Scientific notation input)\r\n    ImGuiInputTextFlags_CallbackResize      = 1 << 18,  // Callback on buffer capacity changes request (beyond 'buf_size' parameter value), allowing the string to grow. Notify when the string wants to be resized (for string types which hold a cache of their Size). You will be provided a new BufSize in the callback and NEED to honor it. (see misc/cpp/imgui_stdlib.h for an example of using this)\r\n    ImGuiInputTextFlags_CallbackEdit        = 1 << 19   // Callback on any edit (note that InputText() already returns true on edit, the callback is useful mainly to manipulate the underlying buffer while focus is active)\r\n\r\n    // Obsolete names (will be removed soon)\r\n#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS\r\n    , ImGuiInputTextFlags_AlwaysInsertMode    = ImGuiInputTextFlags_AlwaysOverwrite   // [renamed in 1.82] name was not matching behavior\r\n#endif\r\n};\r\n\r\n// Flags for ImGui::TreeNodeEx(), ImGui::CollapsingHeader*()\r\nenum ImGuiTreeNodeFlags_\r\n{\r\n    ImGuiTreeNodeFlags_None                 = 0,\r\n    ImGuiTreeNodeFlags_Selected             = 1 << 0,   // Draw as selected\r\n    ImGuiTreeNodeFlags_Framed               = 1 << 1,   // Draw frame with background (e.g. for CollapsingHeader)\r\n    ImGuiTreeNodeFlags_AllowItemOverlap     = 1 << 2,   // Hit testing to allow subsequent widgets to overlap this one\r\n    ImGuiTreeNodeFlags_NoTreePushOnOpen     = 1 << 3,   // Don't do a TreePush() when open (e.g. for CollapsingHeader) = no extra indent nor pushing on ID stack\r\n    ImGuiTreeNodeFlags_NoAutoOpenOnLog      = 1 << 4,   // Don't automatically and temporarily open node when Logging is active (by default logging will automatically open tree nodes)\r\n    ImGuiTreeNodeFlags_DefaultOpen          = 1 << 5,   // Default node to be open\r\n    ImGuiTreeNodeFlags_OpenOnDoubleClick    = 1 << 6,   // Need double-click to open node\r\n    ImGuiTreeNodeFlags_OpenOnArrow          = 1 << 7,   // Only open when clicking on the arrow part. If ImGuiTreeNodeFlags_OpenOnDoubleClick is also set, single-click arrow or double-click all box to open.\r\n    ImGuiTreeNodeFlags_Leaf                 = 1 << 8,   // No collapsing, no arrow (use as a convenience for leaf nodes).\r\n    ImGuiTreeNodeFlags_Bullet               = 1 << 9,   // Display a bullet instead of arrow\r\n    ImGuiTreeNodeFlags_FramePadding         = 1 << 10,  // Use FramePadding (even for an unframed text node) to vertically align text baseline to regular widget height. Equivalent to calling AlignTextToFramePadding().\r\n    ImGuiTreeNodeFlags_SpanAvailWidth       = 1 << 11,  // Extend hit box to the right-most edge, even if not framed. This is not the default in order to allow adding other items on the same line. In the future we may refactor the hit system to be front-to-back, allowing natural overlaps and then this can become the default.\r\n    ImGuiTreeNodeFlags_SpanFullWidth        = 1 << 12,  // Extend hit box to the left-most and right-most edges (bypass the indented area).\r\n    ImGuiTreeNodeFlags_NavLeftJumpsBackHere = 1 << 13,  // (WIP) Nav: left direction may move to this TreeNode() from any of its child (items submitted between TreeNode and TreePop)\r\n    //ImGuiTreeNodeFlags_NoScrollOnOpen     = 1 << 14,  // FIXME: TODO: Disable automatic scroll on TreePop() if node got just open and contents is not visible\r\n    ImGuiTreeNodeFlags_CollapsingHeader     = ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_NoAutoOpenOnLog\r\n};\r\n\r\n// Flags for OpenPopup*(), BeginPopupContext*(), IsPopupOpen() functions.\r\n// - To be backward compatible with older API which took an 'int mouse_button = 1' argument, we need to treat\r\n//   small flags values as a mouse button index, so we encode the mouse button in the first few bits of the flags.\r\n//   It is therefore guaranteed to be legal to pass a mouse button index in ImGuiPopupFlags.\r\n// - For the same reason, we exceptionally default the ImGuiPopupFlags argument of BeginPopupContextXXX functions to 1 instead of 0.\r\n//   IMPORTANT: because the default parameter is 1 (==ImGuiPopupFlags_MouseButtonRight), if you rely on the default parameter\r\n//   and want to another another flag, you need to pass in the ImGuiPopupFlags_MouseButtonRight flag.\r\n// - Multiple buttons currently cannot be combined/or-ed in those functions (we could allow it later).\r\nenum ImGuiPopupFlags_\r\n{\r\n    ImGuiPopupFlags_None                    = 0,\r\n    ImGuiPopupFlags_MouseButtonLeft         = 0,        // For BeginPopupContext*(): open on Left Mouse release. Guaranteed to always be == 0 (same as ImGuiMouseButton_Left)\r\n    ImGuiPopupFlags_MouseButtonRight        = 1,        // For BeginPopupContext*(): open on Right Mouse release. Guaranteed to always be == 1 (same as ImGuiMouseButton_Right)\r\n    ImGuiPopupFlags_MouseButtonMiddle       = 2,        // For BeginPopupContext*(): open on Middle Mouse release. Guaranteed to always be == 2 (same as ImGuiMouseButton_Middle)\r\n    ImGuiPopupFlags_MouseButtonMask_        = 0x1F,\r\n    ImGuiPopupFlags_MouseButtonDefault_     = 1,\r\n    ImGuiPopupFlags_NoOpenOverExistingPopup = 1 << 5,   // For OpenPopup*(), BeginPopupContext*(): don't open if there's already a popup at the same level of the popup stack\r\n    ImGuiPopupFlags_NoOpenOverItems         = 1 << 6,   // For BeginPopupContextWindow(): don't return true when hovering items, only when hovering empty space\r\n    ImGuiPopupFlags_AnyPopupId              = 1 << 7,   // For IsPopupOpen(): ignore the ImGuiID parameter and test for any popup.\r\n    ImGuiPopupFlags_AnyPopupLevel           = 1 << 8,   // For IsPopupOpen(): search/test at any level of the popup stack (default test in the current level)\r\n    ImGuiPopupFlags_AnyPopup                = ImGuiPopupFlags_AnyPopupId | ImGuiPopupFlags_AnyPopupLevel\r\n};\r\n\r\n// Flags for ImGui::Selectable()\r\nenum ImGuiSelectableFlags_\r\n{\r\n    ImGuiSelectableFlags_None               = 0,\r\n    ImGuiSelectableFlags_DontClosePopups    = 1 << 0,   // Clicking this don't close parent popup window\r\n    ImGuiSelectableFlags_SpanAllColumns     = 1 << 1,   // Selectable frame can span all columns (text will still fit in current column)\r\n    ImGuiSelectableFlags_AllowDoubleClick   = 1 << 2,   // Generate press events on double clicks too\r\n    ImGuiSelectableFlags_Disabled           = 1 << 3,   // Cannot be selected, display grayed out text\r\n    ImGuiSelectableFlags_AllowItemOverlap   = 1 << 4    // (WIP) Hit testing to allow subsequent widgets to overlap this one\r\n};\r\n\r\n// Flags for ImGui::BeginCombo()\r\nenum ImGuiComboFlags_\r\n{\r\n    ImGuiComboFlags_None                    = 0,\r\n    ImGuiComboFlags_PopupAlignLeft          = 1 << 0,   // Align the popup toward the left by default\r\n    ImGuiComboFlags_HeightSmall             = 1 << 1,   // Max ~4 items visible. Tip: If you want your combo popup to be a specific size you can use SetNextWindowSizeConstraints() prior to calling BeginCombo()\r\n    ImGuiComboFlags_HeightRegular           = 1 << 2,   // Max ~8 items visible (default)\r\n    ImGuiComboFlags_HeightLarge             = 1 << 3,   // Max ~20 items visible\r\n    ImGuiComboFlags_HeightLargest           = 1 << 4,   // As many fitting items as possible\r\n    ImGuiComboFlags_NoArrowButton           = 1 << 5,   // Display on the preview box without the square arrow button\r\n    ImGuiComboFlags_NoPreview               = 1 << 6,   // Display only a square arrow button\r\n    ImGuiComboFlags_HeightMask_             = ImGuiComboFlags_HeightSmall | ImGuiComboFlags_HeightRegular | ImGuiComboFlags_HeightLarge | ImGuiComboFlags_HeightLargest\r\n};\r\n\r\n// Flags for ImGui::BeginTabBar()\r\nenum ImGuiTabBarFlags_\r\n{\r\n    ImGuiTabBarFlags_None                           = 0,\r\n    ImGuiTabBarFlags_Reorderable                    = 1 << 0,   // Allow manually dragging tabs to re-order them + New tabs are appended at the end of list\r\n    ImGuiTabBarFlags_AutoSelectNewTabs              = 1 << 1,   // Automatically select new tabs when they appear\r\n    ImGuiTabBarFlags_TabListPopupButton             = 1 << 2,   // Disable buttons to open the tab list popup\r\n    ImGuiTabBarFlags_NoCloseWithMiddleMouseButton   = 1 << 3,   // Disable behavior of closing tabs (that are submitted with p_open != NULL) with middle mouse button. You can still repro this behavior on user's side with if (IsItemHovered() && IsMouseClicked(2)) *p_open = false.\r\n    ImGuiTabBarFlags_NoTabListScrollingButtons      = 1 << 4,   // Disable scrolling buttons (apply when fitting policy is ImGuiTabBarFlags_FittingPolicyScroll)\r\n    ImGuiTabBarFlags_NoTooltip                      = 1 << 5,   // Disable tooltips when hovering a tab\r\n    ImGuiTabBarFlags_FittingPolicyResizeDown        = 1 << 6,   // Resize tabs when they don't fit\r\n    ImGuiTabBarFlags_FittingPolicyScroll            = 1 << 7,   // Add scroll buttons when tabs don't fit\r\n    ImGuiTabBarFlags_FittingPolicyMask_             = ImGuiTabBarFlags_FittingPolicyResizeDown | ImGuiTabBarFlags_FittingPolicyScroll,\r\n    ImGuiTabBarFlags_FittingPolicyDefault_          = ImGuiTabBarFlags_FittingPolicyResizeDown\r\n};\r\n\r\n// Flags for ImGui::BeginTabItem()\r\nenum ImGuiTabItemFlags_\r\n{\r\n    ImGuiTabItemFlags_None                          = 0,\r\n    ImGuiTabItemFlags_UnsavedDocument               = 1 << 0,   // Display a dot next to the title + tab is selected when clicking the X + closure is not assumed (will wait for user to stop submitting the tab). Otherwise closure is assumed when pressing the X, so if you keep submitting the tab may reappear at end of tab bar.\r\n    ImGuiTabItemFlags_SetSelected                   = 1 << 1,   // Trigger flag to programmatically make the tab selected when calling BeginTabItem()\r\n    ImGuiTabItemFlags_NoCloseWithMiddleMouseButton  = 1 << 2,   // Disable behavior of closing tabs (that are submitted with p_open != NULL) with middle mouse button. You can still repro this behavior on user's side with if (IsItemHovered() && IsMouseClicked(2)) *p_open = false.\r\n    ImGuiTabItemFlags_NoPushId                      = 1 << 3,   // Don't call PushID(tab->ID)/PopID() on BeginTabItem()/EndTabItem()\r\n    ImGuiTabItemFlags_NoTooltip                     = 1 << 4,   // Disable tooltip for the given tab\r\n    ImGuiTabItemFlags_NoReorder                     = 1 << 5,   // Disable reordering this tab or having another tab cross over this tab\r\n    ImGuiTabItemFlags_Leading                       = 1 << 6,   // Enforce the tab position to the left of the tab bar (after the tab list popup button)\r\n    ImGuiTabItemFlags_Trailing                      = 1 << 7    // Enforce the tab position to the right of the tab bar (before the scrolling buttons)\r\n};\r\n\r\n// Flags for ImGui::BeginTable()\r\n// - Important! Sizing policies have complex and subtle side effects, much more so than you would expect.\r\n//   Read comments/demos carefully + experiment with live demos to get acquainted with them.\r\n// - The DEFAULT sizing policies are:\r\n//    - Default to ImGuiTableFlags_SizingFixedFit    if ScrollX is on, or if host window has ImGuiWindowFlags_AlwaysAutoResize.\r\n//    - Default to ImGuiTableFlags_SizingStretchSame if ScrollX is off.\r\n// - When ScrollX is off:\r\n//    - Table defaults to ImGuiTableFlags_SizingStretchSame -> all Columns defaults to ImGuiTableColumnFlags_WidthStretch with same weight.\r\n//    - Columns sizing policy allowed: Stretch (default), Fixed/Auto.\r\n//    - Fixed Columns (if any) will generally obtain their requested width (unless the table cannot fit them all).\r\n//    - Stretch Columns will share the remaining width according to their respective weight.\r\n//    - Mixed Fixed/Stretch columns is possible but has various side-effects on resizing behaviors.\r\n//      The typical use of mixing sizing policies is: any number of LEADING Fixed columns, followed by one or two TRAILING Stretch columns.\r\n//      (this is because the visible order of columns have subtle but necessary effects on how they react to manual resizing).\r\n// - When ScrollX is on:\r\n//    - Table defaults to ImGuiTableFlags_SizingFixedFit -> all Columns defaults to ImGuiTableColumnFlags_WidthFixed\r\n//    - Columns sizing policy allowed: Fixed/Auto mostly.\r\n//    - Fixed Columns can be enlarged as needed. Table will show an horizontal scrollbar if needed.\r\n//    - When using auto-resizing (non-resizable) fixed columns, querying the content width to use item right-alignment e.g. SetNextItemWidth(-FLT_MIN) doesn't make sense, would create a feedback loop.\r\n//    - Using Stretch columns OFTEN DOES NOT MAKE SENSE if ScrollX is on, UNLESS you have specified a value for 'inner_width' in BeginTable().\r\n//      If you specify a value for 'inner_width' then effectively the scrolling space is known and Stretch or mixed Fixed/Stretch columns become meaningful again.\r\n// - Read on documentation at the top of imgui_tables.cpp for details.\r\nenum ImGuiTableFlags_\r\n{\r\n    // Features\r\n    ImGuiTableFlags_None                       = 0,\r\n    ImGuiTableFlags_Resizable                  = 1 << 0,   // Enable resizing columns.\r\n    ImGuiTableFlags_Reorderable                = 1 << 1,   // Enable reordering columns in header row (need calling TableSetupColumn() + TableHeadersRow() to display headers)\r\n    ImGuiTableFlags_Hideable                   = 1 << 2,   // Enable hiding/disabling columns in context menu.\r\n    ImGuiTableFlags_Sortable                   = 1 << 3,   // Enable sorting. Call TableGetSortSpecs() to obtain sort specs. Also see ImGuiTableFlags_SortMulti and ImGuiTableFlags_SortTristate.\r\n    ImGuiTableFlags_NoSavedSettings            = 1 << 4,   // Disable persisting columns order, width and sort settings in the .ini file.\r\n    ImGuiTableFlags_ContextMenuInBody          = 1 << 5,   // Right-click on columns body/contents will display table context menu. By default it is available in TableHeadersRow().\r\n    // Decorations\r\n    ImGuiTableFlags_RowBg                      = 1 << 6,   // Set each RowBg color with ImGuiCol_TableRowBg or ImGuiCol_TableRowBgAlt (equivalent of calling TableSetBgColor with ImGuiTableBgFlags_RowBg0 on each row manually)\r\n    ImGuiTableFlags_BordersInnerH              = 1 << 7,   // Draw horizontal borders between rows.\r\n    ImGuiTableFlags_BordersOuterH              = 1 << 8,   // Draw horizontal borders at the top and bottom.\r\n    ImGuiTableFlags_BordersInnerV              = 1 << 9,   // Draw vertical borders between columns.\r\n    ImGuiTableFlags_BordersOuterV              = 1 << 10,  // Draw vertical borders on the left and right sides.\r\n    ImGuiTableFlags_BordersH                   = ImGuiTableFlags_BordersInnerH | ImGuiTableFlags_BordersOuterH, // Draw horizontal borders.\r\n    ImGuiTableFlags_BordersV                   = ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_BordersOuterV, // Draw vertical borders.\r\n    ImGuiTableFlags_BordersInner               = ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_BordersInnerH, // Draw inner borders.\r\n    ImGuiTableFlags_BordersOuter               = ImGuiTableFlags_BordersOuterV | ImGuiTableFlags_BordersOuterH, // Draw outer borders.\r\n    ImGuiTableFlags_Borders                    = ImGuiTableFlags_BordersInner | ImGuiTableFlags_BordersOuter,   // Draw all borders.\r\n    ImGuiTableFlags_NoBordersInBody            = 1 << 11,  // [ALPHA] Disable vertical borders in columns Body (borders will always appears in Headers). -> May move to style\r\n    ImGuiTableFlags_NoBordersInBodyUntilResize = 1 << 12,  // [ALPHA] Disable vertical borders in columns Body until hovered for resize (borders will always appears in Headers). -> May move to style\r\n    // Sizing Policy (read above for defaults)\r\n    ImGuiTableFlags_SizingFixedFit             = 1 << 13,  // Columns default to _WidthFixed or _WidthAuto (if resizable or not resizable), matching contents width.\r\n    ImGuiTableFlags_SizingFixedSame            = 2 << 13,  // Columns default to _WidthFixed or _WidthAuto (if resizable or not resizable), matching the maximum contents width of all columns. Implicitly enable ImGuiTableFlags_NoKeepColumnsVisible.\r\n    ImGuiTableFlags_SizingStretchProp          = 3 << 13,  // Columns default to _WidthStretch with default weights proportional to each columns contents widths.\r\n    ImGuiTableFlags_SizingStretchSame          = 4 << 13,  // Columns default to _WidthStretch with default weights all equal, unless overridden by TableSetupColumn().\r\n    // Sizing Extra Options\r\n    ImGuiTableFlags_NoHostExtendX              = 1 << 16,  // Make outer width auto-fit to columns, overriding outer_size.x value. Only available when ScrollX/ScrollY are disabled and Stretch columns are not used.\r\n    ImGuiTableFlags_NoHostExtendY              = 1 << 17,  // Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit). Only available when ScrollX/ScrollY are disabled. Data below the limit will be clipped and not visible.\r\n    ImGuiTableFlags_NoKeepColumnsVisible       = 1 << 18,  // Disable keeping column always minimally visible when ScrollX is off and table gets too small. Not recommended if columns are resizable.\r\n    ImGuiTableFlags_PreciseWidths              = 1 << 19,  // Disable distributing remainder width to stretched columns (width allocation on a 100-wide table with 3 columns: Without this flag: 33,33,34. With this flag: 33,33,33). With larger number of columns, resizing will appear to be less smooth.\r\n    // Clipping\r\n    ImGuiTableFlags_NoClip                     = 1 << 20,  // Disable clipping rectangle for every individual columns (reduce draw command count, items will be able to overflow into other columns). Generally incompatible with TableSetupScrollFreeze().\r\n    // Padding\r\n    ImGuiTableFlags_PadOuterX                  = 1 << 21,  // Default if BordersOuterV is on. Enable outer-most padding. Generally desirable if you have headers.\r\n    ImGuiTableFlags_NoPadOuterX                = 1 << 22,  // Default if BordersOuterV is off. Disable outer-most padding.\r\n    ImGuiTableFlags_NoPadInnerX                = 1 << 23,  // Disable inner padding between columns (double inner padding if BordersOuterV is on, single inner padding if BordersOuterV is off).\r\n    // Scrolling\r\n    ImGuiTableFlags_ScrollX                    = 1 << 24,  // Enable horizontal scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. Changes default sizing policy. Because this create a child window, ScrollY is currently generally recommended when using ScrollX.\r\n    ImGuiTableFlags_ScrollY                    = 1 << 25,  // Enable vertical scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size.\r\n    // Sorting\r\n    ImGuiTableFlags_SortMulti                  = 1 << 26,  // Hold shift when clicking headers to sort on multiple column. TableGetSortSpecs() may return specs where (SpecsCount > 1).\r\n    ImGuiTableFlags_SortTristate               = 1 << 27,  // Allow no sorting, disable default sorting. TableGetSortSpecs() may return specs where (SpecsCount == 0).\r\n\r\n    // [Internal] Combinations and masks\r\n    ImGuiTableFlags_SizingMask_                = ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_SizingFixedSame | ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_SizingStretchSame\r\n\r\n    // Obsolete names (will be removed soon)\r\n#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS\r\n    //, ImGuiTableFlags_ColumnsWidthFixed = ImGuiTableFlags_SizingFixedFit, ImGuiTableFlags_ColumnsWidthStretch = ImGuiTableFlags_SizingStretchSame   // WIP Tables 2020/12\r\n    //, ImGuiTableFlags_SizingPolicyFixed = ImGuiTableFlags_SizingFixedFit, ImGuiTableFlags_SizingPolicyStretch = ImGuiTableFlags_SizingStretchSame   // WIP Tables 2021/01\r\n#endif\r\n};\r\n\r\n// Flags for ImGui::TableSetupColumn()\r\nenum ImGuiTableColumnFlags_\r\n{\r\n    // Input configuration flags\r\n    ImGuiTableColumnFlags_None                  = 0,\r\n    ImGuiTableColumnFlags_Disabled              = 1 << 0,   // Overriding/master disable flag: hide column, won't show in context menu (unlike calling TableSetColumnEnabled() which manipulates the user accessible state)\r\n    ImGuiTableColumnFlags_DefaultHide           = 1 << 1,   // Default as a hidden/disabled column.\r\n    ImGuiTableColumnFlags_DefaultSort           = 1 << 2,   // Default as a sorting column.\r\n    ImGuiTableColumnFlags_WidthStretch          = 1 << 3,   // Column will stretch. Preferable with horizontal scrolling disabled (default if table sizing policy is _SizingStretchSame or _SizingStretchProp).\r\n    ImGuiTableColumnFlags_WidthFixed            = 1 << 4,   // Column will not stretch. Preferable with horizontal scrolling enabled (default if table sizing policy is _SizingFixedFit and table is resizable).\r\n    ImGuiTableColumnFlags_NoResize              = 1 << 5,   // Disable manual resizing.\r\n    ImGuiTableColumnFlags_NoReorder             = 1 << 6,   // Disable manual reordering this column, this will also prevent other columns from crossing over this column.\r\n    ImGuiTableColumnFlags_NoHide                = 1 << 7,   // Disable ability to hide/disable this column.\r\n    ImGuiTableColumnFlags_NoClip                = 1 << 8,   // Disable clipping for this column (all NoClip columns will render in a same draw command).\r\n    ImGuiTableColumnFlags_NoSort                = 1 << 9,   // Disable ability to sort on this field (even if ImGuiTableFlags_Sortable is set on the table).\r\n    ImGuiTableColumnFlags_NoSortAscending       = 1 << 10,  // Disable ability to sort in the ascending direction.\r\n    ImGuiTableColumnFlags_NoSortDescending      = 1 << 11,  // Disable ability to sort in the descending direction.\r\n    ImGuiTableColumnFlags_NoHeaderLabel         = 1 << 12,  // TableHeadersRow() will not submit label for this column. Convenient for some small columns. Name will still appear in context menu.\r\n    ImGuiTableColumnFlags_NoHeaderWidth         = 1 << 13,  // Disable header text width contribution to automatic column width.\r\n    ImGuiTableColumnFlags_PreferSortAscending   = 1 << 14,  // Make the initial sort direction Ascending when first sorting on this column (default).\r\n    ImGuiTableColumnFlags_PreferSortDescending  = 1 << 15,  // Make the initial sort direction Descending when first sorting on this column.\r\n    ImGuiTableColumnFlags_IndentEnable          = 1 << 16,  // Use current Indent value when entering cell (default for column 0).\r\n    ImGuiTableColumnFlags_IndentDisable         = 1 << 17,  // Ignore current Indent value when entering cell (default for columns > 0). Indentation changes _within_ the cell will still be honored.\r\n\r\n    // Output status flags, read-only via TableGetColumnFlags()\r\n    ImGuiTableColumnFlags_IsEnabled             = 1 << 24,  // Status: is enabled == not hidden by user/api (referred to as \"Hide\" in _DefaultHide and _NoHide) flags.\r\n    ImGuiTableColumnFlags_IsVisible             = 1 << 25,  // Status: is visible == is enabled AND not clipped by scrolling.\r\n    ImGuiTableColumnFlags_IsSorted              = 1 << 26,  // Status: is currently part of the sort specs\r\n    ImGuiTableColumnFlags_IsHovered             = 1 << 27,  // Status: is hovered by mouse\r\n\r\n    // [Internal] Combinations and masks\r\n    ImGuiTableColumnFlags_WidthMask_            = ImGuiTableColumnFlags_WidthStretch | ImGuiTableColumnFlags_WidthFixed,\r\n    ImGuiTableColumnFlags_IndentMask_           = ImGuiTableColumnFlags_IndentEnable | ImGuiTableColumnFlags_IndentDisable,\r\n    ImGuiTableColumnFlags_StatusMask_           = ImGuiTableColumnFlags_IsEnabled | ImGuiTableColumnFlags_IsVisible | ImGuiTableColumnFlags_IsSorted | ImGuiTableColumnFlags_IsHovered,\r\n    ImGuiTableColumnFlags_NoDirectResize_       = 1 << 30   // [Internal] Disable user resizing this column directly (it may however we resized indirectly from its left edge)\r\n\r\n    // Obsolete names (will be removed soon)\r\n#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS\r\n    //ImGuiTableColumnFlags_WidthAuto           = ImGuiTableColumnFlags_WidthFixed | ImGuiTableColumnFlags_NoResize, // Column will not stretch and keep resizing based on submitted contents.\r\n#endif\r\n};\r\n\r\n// Flags for ImGui::TableNextRow()\r\nenum ImGuiTableRowFlags_\r\n{\r\n    ImGuiTableRowFlags_None                         = 0,\r\n    ImGuiTableRowFlags_Headers                      = 1 << 0    // Identify header row (set default background color + width of its contents accounted differently for auto column width)\r\n};\r\n\r\n// Enum for ImGui::TableSetBgColor()\r\n// Background colors are rendering in 3 layers:\r\n//  - Layer 0: draw with RowBg0 color if set, otherwise draw with ColumnBg0 if set.\r\n//  - Layer 1: draw with RowBg1 color if set, otherwise draw with ColumnBg1 if set.\r\n//  - Layer 2: draw with CellBg color if set.\r\n// The purpose of the two row/columns layers is to let you decide if a background color changes should override or blend with the existing color.\r\n// When using ImGuiTableFlags_RowBg on the table, each row has the RowBg0 color automatically set for odd/even rows.\r\n// If you set the color of RowBg0 target, your color will override the existing RowBg0 color.\r\n// If you set the color of RowBg1 or ColumnBg1 target, your color will blend over the RowBg0 color.\r\nenum ImGuiTableBgTarget_\r\n{\r\n    ImGuiTableBgTarget_None                         = 0,\r\n    ImGuiTableBgTarget_RowBg0                       = 1,        // Set row background color 0 (generally used for background, automatically set when ImGuiTableFlags_RowBg is used)\r\n    ImGuiTableBgTarget_RowBg1                       = 2,        // Set row background color 1 (generally used for selection marking)\r\n    ImGuiTableBgTarget_CellBg                       = 3         // Set cell background color (top-most color)\r\n};\r\n\r\n// Flags for ImGui::IsWindowFocused()\r\nenum ImGuiFocusedFlags_\r\n{\r\n    ImGuiFocusedFlags_None                          = 0,\r\n    ImGuiFocusedFlags_ChildWindows                  = 1 << 0,   // Return true if any children of the window is focused\r\n    ImGuiFocusedFlags_RootWindow                    = 1 << 1,   // Test from root window (top most parent of the current hierarchy)\r\n    ImGuiFocusedFlags_AnyWindow                     = 1 << 2,   // Return true if any window is focused. Important: If you are trying to tell how to dispatch your low-level inputs, do NOT use this. Use 'io.WantCaptureMouse' instead! Please read the FAQ!\r\n    ImGuiFocusedFlags_NoPopupHierarchy              = 1 << 3,   // Do not consider popup hierarchy (do not treat popup emitter as parent of popup) (when used with _ChildWindows or _RootWindow)\r\n    //ImGuiFocusedFlags_DockHierarchy               = 1 << 4,   // Consider docking hierarchy (treat dockspace host as parent of docked window) (when used with _ChildWindows or _RootWindow)\r\n    ImGuiFocusedFlags_RootAndChildWindows           = ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows\r\n};\r\n\r\n// Flags for ImGui::IsItemHovered(), ImGui::IsWindowHovered()\r\n// Note: if you are trying to check whether your mouse should be dispatched to Dear ImGui or to your app, you should use 'io.WantCaptureMouse' instead! Please read the FAQ!\r\n// Note: windows with the ImGuiWindowFlags_NoInputs flag are ignored by IsWindowHovered() calls.\r\nenum ImGuiHoveredFlags_\r\n{\r\n    ImGuiHoveredFlags_None                          = 0,        // Return true if directly over the item/window, not obstructed by another window, not obstructed by an active popup or modal blocking inputs under them.\r\n    ImGuiHoveredFlags_ChildWindows                  = 1 << 0,   // IsWindowHovered() only: Return true if any children of the window is hovered\r\n    ImGuiHoveredFlags_RootWindow                    = 1 << 1,   // IsWindowHovered() only: Test from root window (top most parent of the current hierarchy)\r\n    ImGuiHoveredFlags_AnyWindow                     = 1 << 2,   // IsWindowHovered() only: Return true if any window is hovered\r\n    ImGuiHoveredFlags_NoPopupHierarchy              = 1 << 3,   // IsWindowHovered() only: Do not consider popup hierarchy (do not treat popup emitter as parent of popup) (when used with _ChildWindows or _RootWindow)\r\n    //ImGuiHoveredFlags_DockHierarchy               = 1 << 4,   // IsWindowHovered() only: Consider docking hierarchy (treat dockspace host as parent of docked window) (when used with _ChildWindows or _RootWindow)\r\n    ImGuiHoveredFlags_AllowWhenBlockedByPopup       = 1 << 5,   // Return true even if a popup window is normally blocking access to this item/window\r\n    //ImGuiHoveredFlags_AllowWhenBlockedByModal     = 1 << 6,   // Return true even if a modal popup window is normally blocking access to this item/window. FIXME-TODO: Unavailable yet.\r\n    ImGuiHoveredFlags_AllowWhenBlockedByActiveItem  = 1 << 7,   // Return true even if an active item is blocking access to this item/window. Useful for Drag and Drop patterns.\r\n    ImGuiHoveredFlags_AllowWhenOverlapped           = 1 << 8,   // IsItemHovered() only: Return true even if the position is obstructed or overlapped by another window\r\n    ImGuiHoveredFlags_AllowWhenDisabled             = 1 << 9,   // IsItemHovered() only: Return true even if the item is disabled\r\n    ImGuiHoveredFlags_RectOnly                      = ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenOverlapped,\r\n    ImGuiHoveredFlags_RootAndChildWindows           = ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows\r\n};\r\n\r\n// Flags for ImGui::BeginDragDropSource(), ImGui::AcceptDragDropPayload()\r\nenum ImGuiDragDropFlags_\r\n{\r\n    ImGuiDragDropFlags_None                         = 0,\r\n    // BeginDragDropSource() flags\r\n    ImGuiDragDropFlags_SourceNoPreviewTooltip       = 1 << 0,   // By default, a successful call to BeginDragDropSource opens a tooltip so you can display a preview or description of the source contents. This flag disable this behavior.\r\n    ImGuiDragDropFlags_SourceNoDisableHover         = 1 << 1,   // By default, when dragging we clear data so that IsItemHovered() will return false, to avoid subsequent user code submitting tooltips. This flag disable this behavior so you can still call IsItemHovered() on the source item.\r\n    ImGuiDragDropFlags_SourceNoHoldToOpenOthers     = 1 << 2,   // Disable the behavior that allows to open tree nodes and collapsing header by holding over them while dragging a source item.\r\n    ImGuiDragDropFlags_SourceAllowNullID            = 1 << 3,   // Allow items such as Text(), Image() that have no unique identifier to be used as drag source, by manufacturing a temporary identifier based on their window-relative position. This is extremely unusual within the dear imgui ecosystem and so we made it explicit.\r\n    ImGuiDragDropFlags_SourceExtern                 = 1 << 4,   // External source (from outside of dear imgui), won't attempt to read current item/window info. Will always return true. Only one Extern source can be active simultaneously.\r\n    ImGuiDragDropFlags_SourceAutoExpirePayload      = 1 << 5,   // Automatically expire the payload if the source cease to be submitted (otherwise payloads are persisting while being dragged)\r\n    // AcceptDragDropPayload() flags\r\n    ImGuiDragDropFlags_AcceptBeforeDelivery         = 1 << 10,  // AcceptDragDropPayload() will returns true even before the mouse button is released. You can then call IsDelivery() to test if the payload needs to be delivered.\r\n    ImGuiDragDropFlags_AcceptNoDrawDefaultRect      = 1 << 11,  // Do not draw the default highlight rectangle when hovering over target.\r\n    ImGuiDragDropFlags_AcceptNoPreviewTooltip       = 1 << 12,  // Request hiding the BeginDragDropSource tooltip from the BeginDragDropTarget site.\r\n    ImGuiDragDropFlags_AcceptPeekOnly               = ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect  // For peeking ahead and inspecting the payload before delivery.\r\n};\r\n\r\n// Standard Drag and Drop payload types. You can define you own payload types using short strings. Types starting with '_' are defined by Dear ImGui.\r\n#define IMGUI_PAYLOAD_TYPE_COLOR_3F     \"_COL3F\"    // float[3]: Standard type for colors, without alpha. User code may use this type.\r\n#define IMGUI_PAYLOAD_TYPE_COLOR_4F     \"_COL4F\"    // float[4]: Standard type for colors. User code may use this type.\r\n\r\n// A primary data type\r\nenum ImGuiDataType_\r\n{\r\n    ImGuiDataType_S8,       // signed char / char (with sensible compilers)\r\n    ImGuiDataType_U8,       // unsigned char\r\n    ImGuiDataType_S16,      // short\r\n    ImGuiDataType_U16,      // unsigned short\r\n    ImGuiDataType_S32,      // int\r\n    ImGuiDataType_U32,      // unsigned int\r\n    ImGuiDataType_S64,      // long long / __int64\r\n    ImGuiDataType_U64,      // unsigned long long / unsigned __int64\r\n    ImGuiDataType_Float,    // float\r\n    ImGuiDataType_Double,   // double\r\n    ImGuiDataType_COUNT\r\n};\r\n\r\n// A cardinal direction\r\nenum ImGuiDir_\r\n{\r\n    ImGuiDir_None    = -1,\r\n    ImGuiDir_Left    = 0,\r\n    ImGuiDir_Right   = 1,\r\n    ImGuiDir_Up      = 2,\r\n    ImGuiDir_Down    = 3,\r\n    ImGuiDir_COUNT\r\n};\r\n\r\n// A sorting direction\r\nenum ImGuiSortDirection_\r\n{\r\n    ImGuiSortDirection_None         = 0,\r\n    ImGuiSortDirection_Ascending    = 1,    // Ascending = 0->9, A->Z etc.\r\n    ImGuiSortDirection_Descending   = 2     // Descending = 9->0, Z->A etc.\r\n};\r\n\r\nenum ImGuiKey_\r\n{\r\n    // Keyboard\r\n    ImGuiKey_None = 0,\r\n    ImGuiKey_Tab = 512,             // == ImGuiKey_NamedKey_BEGIN\r\n    ImGuiKey_LeftArrow,\r\n    ImGuiKey_RightArrow,\r\n    ImGuiKey_UpArrow,\r\n    ImGuiKey_DownArrow,\r\n    ImGuiKey_PageUp,\r\n    ImGuiKey_PageDown,\r\n    ImGuiKey_Home,\r\n    ImGuiKey_End,\r\n    ImGuiKey_Insert,\r\n    ImGuiKey_Delete,\r\n    ImGuiKey_Backspace,\r\n    ImGuiKey_Space,\r\n    ImGuiKey_Enter,\r\n    ImGuiKey_Escape,\r\n    ImGuiKey_LeftCtrl, ImGuiKey_LeftShift, ImGuiKey_LeftAlt, ImGuiKey_LeftSuper,\r\n    ImGuiKey_RightCtrl, ImGuiKey_RightShift, ImGuiKey_RightAlt, ImGuiKey_RightSuper,\r\n    ImGuiKey_Menu,\r\n    ImGuiKey_0, ImGuiKey_1, ImGuiKey_2, ImGuiKey_3, ImGuiKey_4, ImGuiKey_5, ImGuiKey_6, ImGuiKey_7, ImGuiKey_8, ImGuiKey_9,\r\n    ImGuiKey_A, ImGuiKey_B, ImGuiKey_C, ImGuiKey_D, ImGuiKey_E, ImGuiKey_F, ImGuiKey_G, ImGuiKey_H, ImGuiKey_I, ImGuiKey_J,\r\n    ImGuiKey_K, ImGuiKey_L, ImGuiKey_M, ImGuiKey_N, ImGuiKey_O, ImGuiKey_P, ImGuiKey_Q, ImGuiKey_R, ImGuiKey_S, ImGuiKey_T,\r\n    ImGuiKey_U, ImGuiKey_V, ImGuiKey_W, ImGuiKey_X, ImGuiKey_Y, ImGuiKey_Z,\r\n    ImGuiKey_F1, ImGuiKey_F2, ImGuiKey_F3, ImGuiKey_F4, ImGuiKey_F5, ImGuiKey_F6,\r\n    ImGuiKey_F7, ImGuiKey_F8, ImGuiKey_F9, ImGuiKey_F10, ImGuiKey_F11, ImGuiKey_F12,\r\n    ImGuiKey_Apostrophe,        // '\r\n    ImGuiKey_Comma,             // ,\r\n    ImGuiKey_Minus,             // -\r\n    ImGuiKey_Period,            // .\r\n    ImGuiKey_Slash,             // /\r\n    ImGuiKey_Semicolon,         // ;\r\n    ImGuiKey_Equal,             // =\r\n    ImGuiKey_LeftBracket,       // [\r\n    ImGuiKey_Backslash,         // \\ (this text inhibit multiline comment caused by backslash)\r\n    ImGuiKey_RightBracket,      // ]\r\n    ImGuiKey_GraveAccent,       // `\r\n    ImGuiKey_CapsLock,\r\n    ImGuiKey_ScrollLock,\r\n    ImGuiKey_NumLock,\r\n    ImGuiKey_PrintScreen,\r\n    ImGuiKey_Pause,\r\n    ImGuiKey_Keypad0, ImGuiKey_Keypad1, ImGuiKey_Keypad2, ImGuiKey_Keypad3, ImGuiKey_Keypad4,\r\n    ImGuiKey_Keypad5, ImGuiKey_Keypad6, ImGuiKey_Keypad7, ImGuiKey_Keypad8, ImGuiKey_Keypad9,\r\n    ImGuiKey_KeypadDecimal,\r\n    ImGuiKey_KeypadDivide,\r\n    ImGuiKey_KeypadMultiply,\r\n    ImGuiKey_KeypadSubtract,\r\n    ImGuiKey_KeypadAdd,\r\n    ImGuiKey_KeypadEnter,\r\n    ImGuiKey_KeypadEqual,\r\n\r\n    // Gamepad (some of those are analog values, 0.0f to 1.0f)                              // NAVIGATION action\r\n    ImGuiKey_GamepadStart,          // Menu (Xbox)          + (Switch)   Start/Options (PS) // --\r\n    ImGuiKey_GamepadBack,           // View (Xbox)          - (Switch)   Share (PS)         // --\r\n    ImGuiKey_GamepadFaceUp,         // Y (Xbox)             X (Switch)   Triangle (PS)      // -> ImGuiNavInput_Input\r\n    ImGuiKey_GamepadFaceDown,       // A (Xbox)             B (Switch)   Cross (PS)         // -> ImGuiNavInput_Activate\r\n    ImGuiKey_GamepadFaceLeft,       // X (Xbox)             Y (Switch)   Square (PS)        // -> ImGuiNavInput_Menu\r\n    ImGuiKey_GamepadFaceRight,      // B (Xbox)             A (Switch)   Circle (PS)        // -> ImGuiNavInput_Cancel\r\n    ImGuiKey_GamepadDpadUp,         // D-pad Up                                             // -> ImGuiNavInput_DpadUp\r\n    ImGuiKey_GamepadDpadDown,       // D-pad Down                                           // -> ImGuiNavInput_DpadDown\r\n    ImGuiKey_GamepadDpadLeft,       // D-pad Left                                           // -> ImGuiNavInput_DpadLeft\r\n    ImGuiKey_GamepadDpadRight,      // D-pad Right                                          // -> ImGuiNavInput_DpadRight\r\n    ImGuiKey_GamepadL1,             // L Bumper (Xbox)      L (Switch)   L1 (PS)            // -> ImGuiNavInput_FocusPrev + ImGuiNavInput_TweakSlow\r\n    ImGuiKey_GamepadR1,             // R Bumper (Xbox)      R (Switch)   R1 (PS)            // -> ImGuiNavInput_FocusNext + ImGuiNavInput_TweakFast\r\n    ImGuiKey_GamepadL2,             // L Trigger (Xbox)     ZL (Switch)  L2 (PS) [Analog]\r\n    ImGuiKey_GamepadR2,             // R Trigger (Xbox)     ZR (Switch)  R2 (PS) [Analog]\r\n    ImGuiKey_GamepadL3,             // L Thumbstick (Xbox)  L3 (Switch)  L3 (PS)\r\n    ImGuiKey_GamepadR3,             // R Thumbstick (Xbox)  R3 (Switch)  R3 (PS)\r\n    ImGuiKey_GamepadLStickUp,       // [Analog]                                             // -> ImGuiNavInput_LStickUp\r\n    ImGuiKey_GamepadLStickDown,     // [Analog]                                             // -> ImGuiNavInput_LStickDown\r\n    ImGuiKey_GamepadLStickLeft,     // [Analog]                                             // -> ImGuiNavInput_LStickLeft\r\n    ImGuiKey_GamepadLStickRight,    // [Analog]                                             // -> ImGuiNavInput_LStickRight\r\n    ImGuiKey_GamepadRStickUp,       // [Analog]\r\n    ImGuiKey_GamepadRStickDown,     // [Analog]\r\n    ImGuiKey_GamepadRStickLeft,     // [Analog]\r\n    ImGuiKey_GamepadRStickRight,    // [Analog]\r\n\r\n    // Keyboard Modifiers\r\n    // - This is mirroring the data also written to io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper, in a format allowing\r\n    //   them to be accessed via standard key API, allowing calls such as IsKeyPressed(), IsKeyReleased(), querying duration etc.\r\n    // - Code polling every keys (e.g. an interface to detect a key press for input mapping) might want to ignore those\r\n    //   and prefer using the real keys (e.g. ImGuiKey_LeftCtrl, ImGuiKey_RightCtrl instead of ImGuiKey_ModCtrl).\r\n    // - In theory the value of keyboard modifiers should be roughly equivalent to a logical or of the equivalent left/right keys.\r\n    //   In practice: it's complicated; mods are often provided from different sources. Keyboard layout, IME, sticky keys and\r\n    //   backends tend to interfere and break that equivalence. The safer decision is to relay that ambiguity down to the end-user...\r\n    ImGuiKey_ModCtrl,\r\n    ImGuiKey_ModShift,\r\n    ImGuiKey_ModAlt,\r\n    ImGuiKey_ModSuper,\r\n\r\n    ImGuiKey_COUNT,                 // No valid ImGuiKey is ever greater than this value\r\n\r\n    // [Internal] Prior to 1.87 we required user to fill io.KeysDown[512] using their own native index + a io.KeyMap[] array.\r\n    // We are ditching this method but keeping a legacy path for user code doing e.g. IsKeyPressed(MY_NATIVE_KEY_CODE)\r\n    ImGuiKey_NamedKey_BEGIN         = 512,\r\n    ImGuiKey_NamedKey_END           = ImGuiKey_COUNT,\r\n    ImGuiKey_NamedKey_COUNT         = ImGuiKey_NamedKey_END - ImGuiKey_NamedKey_BEGIN,\r\n#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO\r\n    ImGuiKey_KeysData_SIZE          = ImGuiKey_NamedKey_COUNT,          // Size of KeysData[]: only hold named keys\r\n    ImGuiKey_KeysData_OFFSET        = ImGuiKey_NamedKey_BEGIN           // First key stored in KeysData[0]\r\n#else\r\n    ImGuiKey_KeysData_SIZE          = ImGuiKey_COUNT,                   // Size of KeysData[]: hold legacy 0..512 keycodes + named keys\r\n    ImGuiKey_KeysData_OFFSET        = 0                                 // First key stored in KeysData[0]\r\n#endif\r\n\r\n#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS\r\n    , ImGuiKey_KeyPadEnter = ImGuiKey_KeypadEnter   // Renamed in 1.87\r\n#endif\r\n};\r\n\r\n// Helper \"flags\" version of key-mods to store and compare multiple key-mods easily. Sometimes used for storage (e.g. io.KeyMods) but otherwise not much used in public API.\r\nenum ImGuiKeyModFlags_\r\n{\r\n    ImGuiKeyModFlags_None           = 0,\r\n    ImGuiKeyModFlags_Ctrl           = 1 << 0,\r\n    ImGuiKeyModFlags_Shift          = 1 << 1,\r\n    ImGuiKeyModFlags_Alt            = 1 << 2,\r\n    ImGuiKeyModFlags_Super          = 1 << 3    // Cmd/Super/Windows key\r\n};\r\n\r\n// Gamepad/Keyboard navigation\r\n// Keyboard: Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard to enable. NewFrame() will automatically fill io.NavInputs[] based on your io.AddKeyEvent() calls.\r\n// Gamepad:  Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad to enable. Backend: set ImGuiBackendFlags_HasGamepad and fill the io.NavInputs[] fields before calling NewFrame(). Note that io.NavInputs[] is cleared by EndFrame().\r\n// Read instructions in imgui.cpp for more details. Download PNG/PSD at http://dearimgui.org/controls_sheets.\r\nenum ImGuiNavInput_\r\n{\r\n    // Gamepad Mapping\r\n    ImGuiNavInput_Activate,      // Activate / Open / Toggle / Tweak value       // e.g. Cross  (PS4), A (Xbox), A (Switch), Space (Keyboard)\r\n    ImGuiNavInput_Cancel,        // Cancel / Close / Exit                        // e.g. Circle (PS4), B (Xbox), B (Switch), Escape (Keyboard)\r\n    ImGuiNavInput_Input,         // Text input / On-Screen keyboard              // e.g. Triang.(PS4), Y (Xbox), X (Switch), Return (Keyboard)\r\n    ImGuiNavInput_Menu,          // Tap: Toggle menu / Hold: Focus, Move, Resize // e.g. Square (PS4), X (Xbox), Y (Switch), Alt (Keyboard)\r\n    ImGuiNavInput_DpadLeft,      // Move / Tweak / Resize window (w/ PadMenu)    // e.g. D-pad Left/Right/Up/Down (Gamepads), Arrow keys (Keyboard)\r\n    ImGuiNavInput_DpadRight,     //\r\n    ImGuiNavInput_DpadUp,        //\r\n    ImGuiNavInput_DpadDown,      //\r\n    ImGuiNavInput_LStickLeft,    // Scroll / Move window (w/ PadMenu)            // e.g. Left Analog Stick Left/Right/Up/Down\r\n    ImGuiNavInput_LStickRight,   //\r\n    ImGuiNavInput_LStickUp,      //\r\n    ImGuiNavInput_LStickDown,    //\r\n    ImGuiNavInput_FocusPrev,     // Focus Next window (w/ PadMenu)               // e.g. L1 or L2 (PS4), LB or LT (Xbox), L or ZL (Switch)\r\n    ImGuiNavInput_FocusNext,     // Focus Prev window (w/ PadMenu)               // e.g. R1 or R2 (PS4), RB or RT (Xbox), R or ZL (Switch)\r\n    ImGuiNavInput_TweakSlow,     // Slower tweaks                                // e.g. L1 or L2 (PS4), LB or LT (Xbox), L or ZL (Switch)\r\n    ImGuiNavInput_TweakFast,     // Faster tweaks                                // e.g. R1 or R2 (PS4), RB or RT (Xbox), R or ZL (Switch)\r\n\r\n    // [Internal] Don't use directly! This is used internally to differentiate keyboard from gamepad inputs for behaviors that require to differentiate them.\r\n    // Keyboard behavior that have no corresponding gamepad mapping (e.g. CTRL+TAB) will be directly reading from keyboard keys instead of io.NavInputs[].\r\n    ImGuiNavInput_KeyLeft_,      // Move left                                    // = Arrow keys\r\n    ImGuiNavInput_KeyRight_,     // Move right\r\n    ImGuiNavInput_KeyUp_,        // Move up\r\n    ImGuiNavInput_KeyDown_,      // Move down\r\n    ImGuiNavInput_COUNT\r\n};\r\n\r\n// Configuration flags stored in io.ConfigFlags. Set by user/application.\r\nenum ImGuiConfigFlags_\r\n{\r\n    ImGuiConfigFlags_None                   = 0,\r\n    ImGuiConfigFlags_NavEnableKeyboard      = 1 << 0,   // Master keyboard navigation enable flag. NewFrame() will automatically fill io.NavInputs[] based on io.AddKeyEvent() calls\r\n    ImGuiConfigFlags_NavEnableGamepad       = 1 << 1,   // Master gamepad navigation enable flag. This is mostly to instruct your imgui backend to fill io.NavInputs[]. Backend also needs to set ImGuiBackendFlags_HasGamepad.\r\n    ImGuiConfigFlags_NavEnableSetMousePos   = 1 << 2,   // Instruct navigation to move the mouse cursor. May be useful on TV/console systems where moving a virtual mouse is awkward. Will update io.MousePos and set io.WantSetMousePos=true. If enabled you MUST honor io.WantSetMousePos requests in your backend, otherwise ImGui will react as if the mouse is jumping around back and forth.\r\n    ImGuiConfigFlags_NavNoCaptureKeyboard   = 1 << 3,   // Instruct navigation to not set the io.WantCaptureKeyboard flag when io.NavActive is set.\r\n    ImGuiConfigFlags_NoMouse                = 1 << 4,   // Instruct imgui to clear mouse position/buttons in NewFrame(). This allows ignoring the mouse information set by the backend.\r\n    ImGuiConfigFlags_NoMouseCursorChange    = 1 << 5,   // Instruct backend to not alter mouse cursor shape and visibility. Use if the backend cursor changes are interfering with yours and you don't want to use SetMouseCursor() to change mouse cursor. You may want to honor requests from imgui by reading GetMouseCursor() yourself instead.\r\n\r\n    // User storage (to allow your backend/engine to communicate to code that may be shared between multiple projects. Those flags are not used by core Dear ImGui)\r\n    ImGuiConfigFlags_IsSRGB                 = 1 << 20,  // Application is SRGB-aware.\r\n    ImGuiConfigFlags_IsTouchScreen          = 1 << 21   // Application is using a touch screen instead of a mouse.\r\n};\r\n\r\n// Backend capabilities flags stored in io.BackendFlags. Set by imgui_impl_xxx or custom backend.\r\nenum ImGuiBackendFlags_\r\n{\r\n    ImGuiBackendFlags_None                  = 0,\r\n    ImGuiBackendFlags_HasGamepad            = 1 << 0,   // Backend Platform supports gamepad and currently has one connected.\r\n    ImGuiBackendFlags_HasMouseCursors       = 1 << 1,   // Backend Platform supports honoring GetMouseCursor() value to change the OS cursor shape.\r\n    ImGuiBackendFlags_HasSetMousePos        = 1 << 2,   // Backend Platform supports io.WantSetMousePos requests to reposition the OS mouse position (only used if ImGuiConfigFlags_NavEnableSetMousePos is set).\r\n    ImGuiBackendFlags_RendererHasVtxOffset  = 1 << 3    // Backend Renderer supports ImDrawCmd::VtxOffset. This enables output of large meshes (64K+ vertices) while still using 16-bit indices.\r\n};\r\n\r\n// Enumeration for PushStyleColor() / PopStyleColor()\r\nenum ImGuiCol_\r\n{\r\n    ImGuiCol_Text,\r\n    ImGuiCol_TextDisabled,\r\n    ImGuiCol_WindowBg,              // Background of normal windows\r\n    ImGuiCol_ChildBg,               // Background of child windows\r\n    ImGuiCol_PopupBg,               // Background of popups, menus, tooltips windows\r\n    ImGuiCol_Border,\r\n    ImGuiCol_BorderShadow,\r\n    ImGuiCol_FrameBg,               // Background of checkbox, radio button, plot, slider, text input\r\n    ImGuiCol_FrameBgHovered,\r\n    ImGuiCol_FrameBgActive,\r\n    ImGuiCol_TitleBg,\r\n    ImGuiCol_TitleBgActive,\r\n    ImGuiCol_TitleBgCollapsed,\r\n    ImGuiCol_MenuBarBg,\r\n    ImGuiCol_ScrollbarBg,\r\n    ImGuiCol_ScrollbarGrab,\r\n    ImGuiCol_ScrollbarGrabHovered,\r\n    ImGuiCol_ScrollbarGrabActive,\r\n    ImGuiCol_CheckMark,\r\n    ImGuiCol_SliderGrab,\r\n    ImGuiCol_SliderGrabActive,\r\n    ImGuiCol_Button,\r\n    ImGuiCol_ButtonHovered,\r\n    ImGuiCol_ButtonActive,\r\n    ImGuiCol_Header,                // Header* colors are used for CollapsingHeader, TreeNode, Selectable, MenuItem\r\n    ImGuiCol_HeaderHovered,\r\n    ImGuiCol_HeaderActive,\r\n    ImGuiCol_Separator,\r\n    ImGuiCol_SeparatorHovered,\r\n    ImGuiCol_SeparatorActive,\r\n    ImGuiCol_ResizeGrip,\r\n    ImGuiCol_ResizeGripHovered,\r\n    ImGuiCol_ResizeGripActive,\r\n    ImGuiCol_Tab,\r\n    ImGuiCol_TabHovered,\r\n    ImGuiCol_TabActive,\r\n    ImGuiCol_TabUnfocused,\r\n    ImGuiCol_TabUnfocusedActive,\r\n    ImGuiCol_PlotLines,\r\n    ImGuiCol_PlotLinesHovered,\r\n    ImGuiCol_PlotHistogram,\r\n    ImGuiCol_PlotHistogramHovered,\r\n    ImGuiCol_TableHeaderBg,         // Table header background\r\n    ImGuiCol_TableBorderStrong,     // Table outer and header borders (prefer using Alpha=1.0 here)\r\n    ImGuiCol_TableBorderLight,      // Table inner borders (prefer using Alpha=1.0 here)\r\n    ImGuiCol_TableRowBg,            // Table row background (even rows)\r\n    ImGuiCol_TableRowBgAlt,         // Table row background (odd rows)\r\n    ImGuiCol_TextSelectedBg,\r\n    ImGuiCol_DragDropTarget,\r\n    ImGuiCol_NavHighlight,          // Gamepad/keyboard: current highlighted item\r\n    ImGuiCol_NavWindowingHighlight, // Highlight window when using CTRL+TAB\r\n    ImGuiCol_NavWindowingDimBg,     // Darken/colorize entire screen behind the CTRL+TAB window list, when active\r\n    ImGuiCol_ModalWindowDimBg,      // Darken/colorize entire screen behind a modal window, when one is active\r\n    ImGuiCol_COUNT\r\n};\r\n\r\n// Enumeration for PushStyleVar() / PopStyleVar() to temporarily modify the ImGuiStyle structure.\r\n// - The enum only refers to fields of ImGuiStyle which makes sense to be pushed/popped inside UI code.\r\n//   During initialization or between frames, feel free to just poke into ImGuiStyle directly.\r\n// - Tip: Use your programming IDE navigation facilities on the names in the _second column_ below to find the actual members and their description.\r\n//   In Visual Studio IDE: CTRL+comma (\"Edit.NavigateTo\") can follow symbols in comments, whereas CTRL+F12 (\"Edit.GoToImplementation\") cannot.\r\n//   With Visual Assist installed: ALT+G (\"VAssistX.GoToImplementation\") can also follow symbols in comments.\r\n// - When changing this enum, you need to update the associated internal table GStyleVarInfo[] accordingly. This is where we link enum values to members offset/type.\r\nenum ImGuiStyleVar_\r\n{\r\n    // Enum name --------------------- // Member in ImGuiStyle structure (see ImGuiStyle for descriptions)\r\n    ImGuiStyleVar_Alpha,               // float     Alpha\r\n    ImGuiStyleVar_DisabledAlpha,       // float     DisabledAlpha\r\n    ImGuiStyleVar_WindowPadding,       // ImVec2    WindowPadding\r\n    ImGuiStyleVar_WindowRounding,      // float     WindowRounding\r\n    ImGuiStyleVar_WindowBorderSize,    // float     WindowBorderSize\r\n    ImGuiStyleVar_WindowMinSize,       // ImVec2    WindowMinSize\r\n    ImGuiStyleVar_WindowTitleAlign,    // ImVec2    WindowTitleAlign\r\n    ImGuiStyleVar_ChildRounding,       // float     ChildRounding\r\n    ImGuiStyleVar_ChildBorderSize,     // float     ChildBorderSize\r\n    ImGuiStyleVar_PopupRounding,       // float     PopupRounding\r\n    ImGuiStyleVar_PopupBorderSize,     // float     PopupBorderSize\r\n    ImGuiStyleVar_FramePadding,        // ImVec2    FramePadding\r\n    ImGuiStyleVar_FrameRounding,       // float     FrameRounding\r\n    ImGuiStyleVar_FrameBorderSize,     // float     FrameBorderSize\r\n    ImGuiStyleVar_ItemSpacing,         // ImVec2    ItemSpacing\r\n    ImGuiStyleVar_ItemInnerSpacing,    // ImVec2    ItemInnerSpacing\r\n    ImGuiStyleVar_IndentSpacing,       // float     IndentSpacing\r\n    ImGuiStyleVar_CellPadding,         // ImVec2    CellPadding\r\n    ImGuiStyleVar_ScrollbarSize,       // float     ScrollbarSize\r\n    ImGuiStyleVar_ScrollbarRounding,   // float     ScrollbarRounding\r\n    ImGuiStyleVar_GrabMinSize,         // float     GrabMinSize\r\n    ImGuiStyleVar_GrabRounding,        // float     GrabRounding\r\n    ImGuiStyleVar_TabRounding,         // float     TabRounding\r\n    ImGuiStyleVar_ButtonTextAlign,     // ImVec2    ButtonTextAlign\r\n    ImGuiStyleVar_SelectableTextAlign, // ImVec2    SelectableTextAlign\r\n    ImGuiStyleVar_COUNT\r\n};\r\n\r\n// Flags for InvisibleButton() [extended in imgui_internal.h]\r\nenum ImGuiButtonFlags_\r\n{\r\n    ImGuiButtonFlags_None                   = 0,\r\n    ImGuiButtonFlags_MouseButtonLeft        = 1 << 0,   // React on left mouse button (default)\r\n    ImGuiButtonFlags_MouseButtonRight       = 1 << 1,   // React on right mouse button\r\n    ImGuiButtonFlags_MouseButtonMiddle      = 1 << 2,   // React on center mouse button\r\n\r\n    // [Internal]\r\n    ImGuiButtonFlags_MouseButtonMask_       = ImGuiButtonFlags_MouseButtonLeft | ImGuiButtonFlags_MouseButtonRight | ImGuiButtonFlags_MouseButtonMiddle,\r\n    ImGuiButtonFlags_MouseButtonDefault_    = ImGuiButtonFlags_MouseButtonLeft\r\n};\r\n\r\n// Flags for ColorEdit3() / ColorEdit4() / ColorPicker3() / ColorPicker4() / ColorButton()\r\nenum ImGuiColorEditFlags_\r\n{\r\n    ImGuiColorEditFlags_None            = 0,\r\n    ImGuiColorEditFlags_NoAlpha         = 1 << 1,   //              // ColorEdit, ColorPicker, ColorButton: ignore Alpha component (will only read 3 components from the input pointer).\r\n    ImGuiColorEditFlags_NoPicker        = 1 << 2,   //              // ColorEdit: disable picker when clicking on color square.\r\n    ImGuiColorEditFlags_NoOptions       = 1 << 3,   //              // ColorEdit: disable toggling options menu when right-clicking on inputs/small preview.\r\n    ImGuiColorEditFlags_NoSmallPreview  = 1 << 4,   //              // ColorEdit, ColorPicker: disable color square preview next to the inputs. (e.g. to show only the inputs)\r\n    ImGuiColorEditFlags_NoInputs        = 1 << 5,   //              // ColorEdit, ColorPicker: disable inputs sliders/text widgets (e.g. to show only the small preview color square).\r\n    ImGuiColorEditFlags_NoTooltip       = 1 << 6,   //              // ColorEdit, ColorPicker, ColorButton: disable tooltip when hovering the preview.\r\n    ImGuiColorEditFlags_NoLabel         = 1 << 7,   //              // ColorEdit, ColorPicker: disable display of inline text label (the label is still forwarded to the tooltip and picker).\r\n    ImGuiColorEditFlags_NoSidePreview   = 1 << 8,   //              // ColorPicker: disable bigger color preview on right side of the picker, use small color square preview instead.\r\n    ImGuiColorEditFlags_NoDragDrop      = 1 << 9,   //              // ColorEdit: disable drag and drop target. ColorButton: disable drag and drop source.\r\n    ImGuiColorEditFlags_NoBorder        = 1 << 10,  //              // ColorButton: disable border (which is enforced by default)\r\n\r\n    // User Options (right-click on widget to change some of them).\r\n    ImGuiColorEditFlags_AlphaBar        = 1 << 16,  //              // ColorEdit, ColorPicker: show vertical alpha bar/gradient in picker.\r\n    ImGuiColorEditFlags_AlphaPreview    = 1 << 17,  //              // ColorEdit, ColorPicker, ColorButton: display preview as a transparent color over a checkerboard, instead of opaque.\r\n    ImGuiColorEditFlags_AlphaPreviewHalf= 1 << 18,  //              // ColorEdit, ColorPicker, ColorButton: display half opaque / half checkerboard, instead of opaque.\r\n    ImGuiColorEditFlags_HDR             = 1 << 19,  //              // (WIP) ColorEdit: Currently only disable 0.0f..1.0f limits in RGBA edition (note: you probably want to use ImGuiColorEditFlags_Float flag as well).\r\n    ImGuiColorEditFlags_DisplayRGB      = 1 << 20,  // [Display]    // ColorEdit: override _display_ type among RGB/HSV/Hex. ColorPicker: select any combination using one or more of RGB/HSV/Hex.\r\n    ImGuiColorEditFlags_DisplayHSV      = 1 << 21,  // [Display]    // \"\r\n    ImGuiColorEditFlags_DisplayHex      = 1 << 22,  // [Display]    // \"\r\n    ImGuiColorEditFlags_Uint8           = 1 << 23,  // [DataType]   // ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0..255.\r\n    ImGuiColorEditFlags_Float           = 1 << 24,  // [DataType]   // ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0.0f..1.0f floats instead of 0..255 integers. No round-trip of value via integers.\r\n    ImGuiColorEditFlags_PickerHueBar    = 1 << 25,  // [Picker]     // ColorPicker: bar for Hue, rectangle for Sat/Value.\r\n    ImGuiColorEditFlags_PickerHueWheel  = 1 << 26,  // [Picker]     // ColorPicker: wheel for Hue, triangle for Sat/Value.\r\n    ImGuiColorEditFlags_InputRGB        = 1 << 27,  // [Input]      // ColorEdit, ColorPicker: input and output data in RGB format.\r\n    ImGuiColorEditFlags_InputHSV        = 1 << 28,  // [Input]      // ColorEdit, ColorPicker: input and output data in HSV format.\r\n\r\n    // Defaults Options. You can set application defaults using SetColorEditOptions(). The intent is that you probably don't want to\r\n    // override them in most of your calls. Let the user choose via the option menu and/or call SetColorEditOptions() once during startup.\r\n    ImGuiColorEditFlags_DefaultOptions_ = ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_InputRGB | ImGuiColorEditFlags_PickerHueBar,\r\n\r\n    // [Internal] Masks\r\n    ImGuiColorEditFlags_DisplayMask_    = ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_DisplayHex,\r\n    ImGuiColorEditFlags_DataTypeMask_   = ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_Float,\r\n    ImGuiColorEditFlags_PickerMask_     = ImGuiColorEditFlags_PickerHueWheel | ImGuiColorEditFlags_PickerHueBar,\r\n    ImGuiColorEditFlags_InputMask_      = ImGuiColorEditFlags_InputRGB | ImGuiColorEditFlags_InputHSV\r\n\r\n    // Obsolete names (will be removed)\r\n    // ImGuiColorEditFlags_RGB = ImGuiColorEditFlags_DisplayRGB, ImGuiColorEditFlags_HSV = ImGuiColorEditFlags_DisplayHSV, ImGuiColorEditFlags_HEX = ImGuiColorEditFlags_DisplayHex  // [renamed in 1.69]\r\n};\r\n\r\n// Flags for DragFloat(), DragInt(), SliderFloat(), SliderInt() etc.\r\n// We use the same sets of flags for DragXXX() and SliderXXX() functions as the features are the same and it makes it easier to swap them.\r\nenum ImGuiSliderFlags_\r\n{\r\n    ImGuiSliderFlags_None                   = 0,\r\n    ImGuiSliderFlags_AlwaysClamp            = 1 << 4,       // Clamp value to min/max bounds when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds.\r\n    ImGuiSliderFlags_Logarithmic            = 1 << 5,       // Make the widget logarithmic (linear otherwise). Consider using ImGuiSliderFlags_NoRoundToFormat with this if using a format-string with small amount of digits.\r\n    ImGuiSliderFlags_NoRoundToFormat        = 1 << 6,       // Disable rounding underlying value to match precision of the display format string (e.g. %.3f values are rounded to those 3 digits)\r\n    ImGuiSliderFlags_NoInput                = 1 << 7,       // Disable CTRL+Click or Enter key allowing to input text directly into the widget\r\n    ImGuiSliderFlags_InvalidMask_           = 0x7000000F    // [Internal] We treat using those bits as being potentially a 'float power' argument from the previous API that has got miscast to this enum, and will trigger an assert if needed.\r\n\r\n    // Obsolete names (will be removed)\r\n#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS\r\n    , ImGuiSliderFlags_ClampOnInput = ImGuiSliderFlags_AlwaysClamp // [renamed in 1.79]\r\n#endif\r\n};\r\n\r\n// Identify a mouse button.\r\n// Those values are guaranteed to be stable and we frequently use 0/1 directly. Named enums provided for convenience.\r\nenum ImGuiMouseButton_\r\n{\r\n    ImGuiMouseButton_Left = 0,\r\n    ImGuiMouseButton_Right = 1,\r\n    ImGuiMouseButton_Middle = 2,\r\n    ImGuiMouseButton_COUNT = 5\r\n};\r\n\r\n// Enumeration for GetMouseCursor()\r\n// User code may request backend to display given cursor by calling SetMouseCursor(), which is why we have some cursors that are marked unused here\r\nenum ImGuiMouseCursor_\r\n{\r\n    ImGuiMouseCursor_None = -1,\r\n    ImGuiMouseCursor_Arrow = 0,\r\n    ImGuiMouseCursor_TextInput,         // When hovering over InputText, etc.\r\n    ImGuiMouseCursor_ResizeAll,         // (Unused by Dear ImGui functions)\r\n    ImGuiMouseCursor_ResizeNS,          // When hovering over an horizontal border\r\n    ImGuiMouseCursor_ResizeEW,          // When hovering over a vertical border or a column\r\n    ImGuiMouseCursor_ResizeNESW,        // When hovering over the bottom-left corner of a window\r\n    ImGuiMouseCursor_ResizeNWSE,        // When hovering over the bottom-right corner of a window\r\n    ImGuiMouseCursor_Hand,              // (Unused by Dear ImGui functions. Use for e.g. hyperlinks)\r\n    ImGuiMouseCursor_NotAllowed,        // When hovering something with disallowed interaction. Usually a crossed circle.\r\n    ImGuiMouseCursor_COUNT\r\n};\r\n\r\n// Enumeration for ImGui::SetWindow***(), SetNextWindow***(), SetNextItem***() functions\r\n// Represent a condition.\r\n// Important: Treat as a regular enum! Do NOT combine multiple values using binary operators! All the functions above treat 0 as a shortcut to ImGuiCond_Always.\r\nenum ImGuiCond_\r\n{\r\n    ImGuiCond_None          = 0,        // No condition (always set the variable), same as _Always\r\n    ImGuiCond_Always        = 1 << 0,   // No condition (always set the variable)\r\n    ImGuiCond_Once          = 1 << 1,   // Set the variable once per runtime session (only the first call will succeed)\r\n    ImGuiCond_FirstUseEver  = 1 << 2,   // Set the variable if the object/window has no persistently saved data (no entry in .ini file)\r\n    ImGuiCond_Appearing     = 1 << 3    // Set the variable if the object/window is appearing after being hidden/inactive (or the first time)\r\n};\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Helpers: Memory allocations macros, ImVector<>\r\n//-----------------------------------------------------------------------------\r\n\r\n//-----------------------------------------------------------------------------\r\n// IM_MALLOC(), IM_FREE(), IM_NEW(), IM_PLACEMENT_NEW(), IM_DELETE()\r\n// We call C++ constructor on own allocated memory via the placement \"new(ptr) Type()\" syntax.\r\n// Defining a custom placement new() with a custom parameter allows us to bypass including <new> which on some platforms complains when user has disabled exceptions.\r\n//-----------------------------------------------------------------------------\r\n\r\nstruct ImNewWrapper {};\r\ninline void* operator new(size_t, ImNewWrapper, void* ptr) { return ptr; }\r\ninline void  operator delete(void*, ImNewWrapper, void*)   {} // This is only required so we can use the symmetrical new()\r\n#define IM_ALLOC(_SIZE)                     ImGui::MemAlloc(_SIZE)\r\n#define IM_FREE(_PTR)                       ImGui::MemFree(_PTR)\r\n#define IM_PLACEMENT_NEW(_PTR)              new(ImNewWrapper(), _PTR)\r\n#define IM_NEW(_TYPE)                       new(ImNewWrapper(), ImGui::MemAlloc(sizeof(_TYPE))) _TYPE\r\ntemplate<typename T> void IM_DELETE(T* p)   { if (p) { p->~T(); ImGui::MemFree(p); } }\r\n\r\n//-----------------------------------------------------------------------------\r\n// ImVector<>\r\n// Lightweight std::vector<>-like class to avoid dragging dependencies (also, some implementations of STL with debug enabled are absurdly slow, we bypass it so our code runs fast in debug).\r\n//-----------------------------------------------------------------------------\r\n// - You generally do NOT need to care or use this ever. But we need to make it available in imgui.h because some of our public structures are relying on it.\r\n// - We use std-like naming convention here, which is a little unusual for this codebase.\r\n// - Important: clear() frees memory, resize(0) keep the allocated buffer. We use resize(0) a lot to intentionally recycle allocated buffers across frames and amortize our costs.\r\n// - Important: our implementation does NOT call C++ constructors/destructors, we treat everything as raw data! This is intentional but be extra mindful of that,\r\n//   Do NOT use this class as a std::vector replacement in your own code! Many of the structures used by dear imgui can be safely initialized by a zero-memset.\r\n//-----------------------------------------------------------------------------\r\n\r\nIM_MSVC_RUNTIME_CHECKS_OFF\r\ntemplate<typename T>\r\nstruct ImVector\r\n{\r\n    int                 Size;\r\n    int                 Capacity;\r\n    T*                  Data;\r\n\r\n    // Provide standard typedefs but we don't use them ourselves.\r\n    typedef T                   value_type;\r\n    typedef value_type*         iterator;\r\n    typedef const value_type*   const_iterator;\r\n\r\n    // Constructors, destructor\r\n    inline ImVector()                                       { Size = Capacity = 0; Data = NULL; }\r\n    inline ImVector(const ImVector<T>& src)                 { Size = Capacity = 0; Data = NULL; operator=(src); }\r\n    inline ImVector<T>& operator=(const ImVector<T>& src)   { clear(); resize(src.Size); memcpy(Data, src.Data, (size_t)Size * sizeof(T)); return *this; }\r\n    inline ~ImVector()                                      { if (Data) IM_FREE(Data); } // Important: does not destruct anything\r\n\r\n    inline void         clear()                             { if (Data) { Size = Capacity = 0; IM_FREE(Data); Data = NULL; } }  // Important: does not destruct anything\r\n    inline void         clear_delete()                      { for (int n = 0; n < Size; n++) IM_DELETE(Data[n]); clear(); }     // Important: never called automatically! always explicit.\r\n    inline void         clear_destruct()                    { for (int n = 0; n < Size; n++) Data[n].~T(); clear(); }           // Important: never called automatically! always explicit.\r\n\r\n    inline bool         empty() const                       { return Size == 0; }\r\n    inline int          size() const                        { return Size; }\r\n    inline int          size_in_bytes() const               { return Size * (int)sizeof(T); }\r\n    inline int          max_size() const                    { return 0x7FFFFFFF / (int)sizeof(T); }\r\n    inline int          capacity() const                    { return Capacity; }\r\n    inline T&           operator[](int i)                   { IM_ASSERT(i >= 0 && i < Size); return Data[i]; }\r\n    inline const T&     operator[](int i) const             { IM_ASSERT(i >= 0 && i < Size); return Data[i]; }\r\n\r\n    inline T*           begin()                             { return Data; }\r\n    inline const T*     begin() const                       { return Data; }\r\n    inline T*           end()                               { return Data + Size; }\r\n    inline const T*     end() const                         { return Data + Size; }\r\n    inline T&           front()                             { IM_ASSERT(Size > 0); return Data[0]; }\r\n    inline const T&     front() const                       { IM_ASSERT(Size > 0); return Data[0]; }\r\n    inline T&           back()                              { IM_ASSERT(Size > 0); return Data[Size - 1]; }\r\n    inline const T&     back() const                        { IM_ASSERT(Size > 0); return Data[Size - 1]; }\r\n    inline void         swap(ImVector<T>& rhs)              { int rhs_size = rhs.Size; rhs.Size = Size; Size = rhs_size; int rhs_cap = rhs.Capacity; rhs.Capacity = Capacity; Capacity = rhs_cap; T* rhs_data = rhs.Data; rhs.Data = Data; Data = rhs_data; }\r\n\r\n    inline int          _grow_capacity(int sz) const        { int new_capacity = Capacity ? (Capacity + Capacity / 2) : 8; return new_capacity > sz ? new_capacity : sz; }\r\n    inline void         resize(int new_size)                { if (new_size > Capacity) reserve(_grow_capacity(new_size)); Size = new_size; }\r\n    inline void         resize(int new_size, const T& v)    { if (new_size > Capacity) reserve(_grow_capacity(new_size)); if (new_size > Size) for (int n = Size; n < new_size; n++) memcpy(&Data[n], &v, sizeof(v)); Size = new_size; }\r\n    inline void         shrink(int new_size)                { IM_ASSERT(new_size <= Size); Size = new_size; } // Resize a vector to a smaller size, guaranteed not to cause a reallocation\r\n    inline void         reserve(int new_capacity)           { if (new_capacity <= Capacity) return; T* new_data = (T*)IM_ALLOC((size_t)new_capacity * sizeof(T)); if (Data) { memcpy(new_data, Data, (size_t)Size * sizeof(T)); IM_FREE(Data); } Data = new_data; Capacity = new_capacity; }\r\n\r\n    // NB: It is illegal to call push_back/push_front/insert with a reference pointing inside the ImVector data itself! e.g. v.push_back(v[10]) is forbidden.\r\n    inline void         push_back(const T& v)               { if (Size == Capacity) reserve(_grow_capacity(Size + 1)); memcpy(&Data[Size], &v, sizeof(v)); Size++; }\r\n    inline void         pop_back()                          { IM_ASSERT(Size > 0); Size--; }\r\n    inline void         push_front(const T& v)              { if (Size == 0) push_back(v); else insert(Data, v); }\r\n    inline T*           erase(const T* it)                  { IM_ASSERT(it >= Data && it < Data + Size); const ptrdiff_t off = it - Data; memmove(Data + off, Data + off + 1, ((size_t)Size - (size_t)off - 1) * sizeof(T)); Size--; return Data + off; }\r\n    inline T*           erase(const T* it, const T* it_last){ IM_ASSERT(it >= Data && it < Data + Size && it_last > it && it_last <= Data + Size); const ptrdiff_t count = it_last - it; const ptrdiff_t off = it - Data; memmove(Data + off, Data + off + count, ((size_t)Size - (size_t)off - (size_t)count) * sizeof(T)); Size -= (int)count; return Data + off; }\r\n    inline T*           erase_unsorted(const T* it)         { IM_ASSERT(it >= Data && it < Data + Size);  const ptrdiff_t off = it - Data; if (it < Data + Size - 1) memcpy(Data + off, Data + Size - 1, sizeof(T)); Size--; return Data + off; }\r\n    inline T*           insert(const T* it, const T& v)     { IM_ASSERT(it >= Data && it <= Data + Size); const ptrdiff_t off = it - Data; if (Size == Capacity) reserve(_grow_capacity(Size + 1)); if (off < (int)Size) memmove(Data + off + 1, Data + off, ((size_t)Size - (size_t)off) * sizeof(T)); memcpy(&Data[off], &v, sizeof(v)); Size++; return Data + off; }\r\n    inline bool         contains(const T& v) const          { const T* data = Data;  const T* data_end = Data + Size; while (data < data_end) if (*data++ == v) return true; return false; }\r\n    inline T*           find(const T& v)                    { T* data = Data;  const T* data_end = Data + Size; while (data < data_end) if (*data == v) break; else ++data; return data; }\r\n    inline const T*     find(const T& v) const              { const T* data = Data;  const T* data_end = Data + Size; while (data < data_end) if (*data == v) break; else ++data; return data; }\r\n    inline bool         find_erase(const T& v)              { const T* it = find(v); if (it < Data + Size) { erase(it); return true; } return false; }\r\n    inline bool         find_erase_unsorted(const T& v)     { const T* it = find(v); if (it < Data + Size) { erase_unsorted(it); return true; } return false; }\r\n    inline int          index_from_ptr(const T* it) const   { IM_ASSERT(it >= Data && it < Data + Size); const ptrdiff_t off = it - Data; return (int)off; }\r\n};\r\nIM_MSVC_RUNTIME_CHECKS_RESTORE\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] ImGuiStyle\r\n//-----------------------------------------------------------------------------\r\n// You may modify the ImGui::GetStyle() main instance during initialization and before NewFrame().\r\n// During the frame, use ImGui::PushStyleVar(ImGuiStyleVar_XXXX)/PopStyleVar() to alter the main style values,\r\n// and ImGui::PushStyleColor(ImGuiCol_XXX)/PopStyleColor() for colors.\r\n//-----------------------------------------------------------------------------\r\n\r\nstruct ImGuiStyle\r\n{\r\n    float       Alpha;                      // Global alpha applies to everything in Dear ImGui.\r\n    float       DisabledAlpha;              // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha.\r\n    ImVec2      WindowPadding;              // Padding within a window.\r\n    float       WindowRounding;             // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended.\r\n    float       WindowBorderSize;           // Thickness of border around windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly).\r\n    ImVec2      WindowMinSize;              // Minimum window size. This is a global setting. If you want to constraint individual windows, use SetNextWindowSizeConstraints().\r\n    ImVec2      WindowTitleAlign;           // Alignment for title bar text. Defaults to (0.0f,0.5f) for left-aligned,vertically centered.\r\n    ImGuiDir    WindowMenuButtonPosition;   // Side of the collapsing/docking button in the title bar (None/Left/Right). Defaults to ImGuiDir_Left.\r\n    float       ChildRounding;              // Radius of child window corners rounding. Set to 0.0f to have rectangular windows.\r\n    float       ChildBorderSize;            // Thickness of border around child windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly).\r\n    float       PopupRounding;              // Radius of popup window corners rounding. (Note that tooltip windows use WindowRounding)\r\n    float       PopupBorderSize;            // Thickness of border around popup/tooltip windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly).\r\n    ImVec2      FramePadding;               // Padding within a framed rectangle (used by most widgets).\r\n    float       FrameRounding;              // Radius of frame corners rounding. Set to 0.0f to have rectangular frame (used by most widgets).\r\n    float       FrameBorderSize;            // Thickness of border around frames. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly).\r\n    ImVec2      ItemSpacing;                // Horizontal and vertical spacing between widgets/lines.\r\n    ImVec2      ItemInnerSpacing;           // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label).\r\n    ImVec2      CellPadding;                // Padding within a table cell\r\n    ImVec2      TouchExtraPadding;          // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!\r\n    float       IndentSpacing;              // Horizontal indentation when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).\r\n    float       ColumnsMinSpacing;          // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).\r\n    float       ScrollbarSize;              // Width of the vertical scrollbar, Height of the horizontal scrollbar.\r\n    float       ScrollbarRounding;          // Radius of grab corners for scrollbar.\r\n    float       GrabMinSize;                // Minimum width/height of a grab box for slider/scrollbar.\r\n    float       GrabRounding;               // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.\r\n    float       LogSliderDeadzone;          // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.\r\n    float       TabRounding;                // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.\r\n    float       TabBorderSize;              // Thickness of border around tabs.\r\n    float       TabMinWidthForCloseButton;  // Minimum width for close button to appears on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected.\r\n    ImGuiDir    ColorButtonPosition;        // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.\r\n    ImVec2      ButtonTextAlign;            // Alignment of button text when button is larger than text. Defaults to (0.5f, 0.5f) (centered).\r\n    ImVec2      SelectableTextAlign;        // Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line.\r\n    ImVec2      DisplayWindowPadding;       // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows.\r\n    ImVec2      DisplaySafeAreaPadding;     // If you cannot see the edges of your screen (e.g. on a TV) increase the safe area padding. Apply to popups/tooltips as well regular windows. NB: Prefer configuring your TV sets correctly!\r\n    float       MouseCursorScale;           // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.\r\n    bool        AntiAliasedLines;           // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame (copied to ImDrawList).\r\n    bool        AntiAliasedLinesUseTex;     // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering. Latched at the beginning of the frame (copied to ImDrawList).\r\n    bool        AntiAliasedFill;            // Enable anti-aliased edges around filled shapes (rounded rectangles, circles, etc.). Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame (copied to ImDrawList).\r\n    float       CurveTessellationTol;       // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.\r\n    float       CircleTessellationMaxError; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry.\r\n    ImVec4      Colors[ImGuiCol_COUNT];\r\n\r\n    IMGUI_API ImGuiStyle();\r\n    IMGUI_API void ScaleAllSizes(float scale_factor);\r\n};\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] ImGuiIO\r\n//-----------------------------------------------------------------------------\r\n// Communicate most settings and inputs/outputs to Dear ImGui using this structure.\r\n// Access via ImGui::GetIO(). Read 'Programmer guide' section in .cpp file for general usage.\r\n//-----------------------------------------------------------------------------\r\n\r\n// [Internal] Storage used by IsKeyDown(), IsKeyPressed() etc functions.\r\n// If prior to 1.87 you used io.KeysDownDuration[] (which was marked as internal), you should use GetKeyData(key)->DownDuration and not io.KeysData[key]->DownDuration.\r\nstruct ImGuiKeyData\r\n{\r\n    bool        Down;               // True for if key is down\r\n    float       DownDuration;       // Duration the key has been down (<0.0f: not pressed, 0.0f: just pressed, >0.0f: time held)\r\n    float       DownDurationPrev;   // Last frame duration the key has been down\r\n    float       AnalogValue;        // 0.0f..1.0f for gamepad values\r\n};\r\n\r\nstruct ImGuiIO\r\n{\r\n    //------------------------------------------------------------------\r\n    // Configuration (fill once)                // Default value\r\n    //------------------------------------------------------------------\r\n\r\n    ImGuiConfigFlags   ConfigFlags;             // = 0              // See ImGuiConfigFlags_ enum. Set by user/application. Gamepad/keyboard navigation options, etc.\r\n    ImGuiBackendFlags  BackendFlags;            // = 0              // See ImGuiBackendFlags_ enum. Set by backend (imgui_impl_xxx files or custom backend) to communicate features supported by the backend.\r\n    ImVec2      DisplaySize;                    // <unset>          // Main display size, in pixels (generally == GetMainViewport()->Size)\r\n    float       DeltaTime;                      // = 1.0f/60.0f     // Time elapsed since last frame, in seconds.\r\n    float       IniSavingRate;                  // = 5.0f           // Minimum time between saving positions/sizes to .ini file, in seconds.\r\n    const char* IniFilename;                    // = \"imgui.ini\"    // Path to .ini file (important: default \"imgui.ini\" is relative to current working dir!). Set NULL to disable automatic .ini loading/saving or if you want to manually call LoadIniSettingsXXX() / SaveIniSettingsXXX() functions.\r\n    const char* LogFilename;                    // = \"imgui_log.txt\"// Path to .log file (default parameter to ImGui::LogToFile when no file is specified).\r\n    float       MouseDoubleClickTime;           // = 0.30f          // Time for a double-click, in seconds.\r\n    float       MouseDoubleClickMaxDist;        // = 6.0f           // Distance threshold to stay in to validate a double-click, in pixels.\r\n    float       MouseDragThreshold;             // = 6.0f           // Distance threshold before considering we are dragging.\r\n    float       KeyRepeatDelay;                 // = 0.250f         // When holding a key/button, time before it starts repeating, in seconds (for buttons in Repeat mode, etc.).\r\n    float       KeyRepeatRate;                  // = 0.050f         // When holding a key/button, rate at which it repeats, in seconds.\r\n    void*       UserData;                       // = NULL           // Store your own data for retrieval by callbacks.\r\n\r\n    ImFontAtlas*Fonts;                          // <auto>           // Font atlas: load, rasterize and pack one or more fonts into a single texture.\r\n    float       FontGlobalScale;                // = 1.0f           // Global scale all fonts\r\n    bool        FontAllowUserScaling;           // = false          // Allow user scaling text of individual window with CTRL+Wheel.\r\n    ImFont*     FontDefault;                    // = NULL           // Font to use on NewFrame(). Use NULL to uses Fonts->Fonts[0].\r\n    ImVec2      DisplayFramebufferScale;        // = (1, 1)         // For retina display or other situations where window coordinates are different from framebuffer coordinates. This generally ends up in ImDrawData::FramebufferScale.\r\n\r\n    // Miscellaneous options\r\n    bool        MouseDrawCursor;                // = false          // Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor). Cannot be easily renamed to 'io.ConfigXXX' because this is frequently used by backend implementations.\r\n    bool        ConfigMacOSXBehaviors;          // = defined(__APPLE__) // OS X style: Text editing cursor movement using Alt instead of Ctrl, Shortcuts using Cmd/Super instead of Ctrl, Line/Text Start and End using Cmd+Arrows instead of Home/End, Double click selects by word instead of selecting whole text, Multi-selection in lists uses Cmd/Super instead of Ctrl.\r\n    bool        ConfigInputTrickleEventQueue;   // = true           // Enable input queue trickling: some types of events submitted during the same frame (e.g. button down + up) will be spread over multiple frames, improving interactions with low framerates.\r\n    bool        ConfigInputTextCursorBlink;     // = true           // Enable blinking cursor (optional as some users consider it to be distracting).\r\n    bool        ConfigDragClickToInputText;     // = false          // [BETA] Enable turning DragXXX widgets into text input with a simple mouse click-release (without moving). Not desirable on devices without a keyboard.\r\n    bool        ConfigWindowsResizeFromEdges;   // = true           // Enable resizing of windows from their edges and from the lower-left corner. This requires (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) because it needs mouse cursor feedback. (This used to be a per-window ImGuiWindowFlags_ResizeFromAnySide flag)\r\n    bool        ConfigWindowsMoveFromTitleBarOnly; // = false       // Enable allowing to move windows only when clicking on their title bar. Does not apply to windows without a title bar.\r\n    float       ConfigMemoryCompactTimer;       // = 60.0f          // Timer (in seconds) to free transient windows/tables memory buffers when unused. Set to -1.0f to disable.\r\n\r\n    //------------------------------------------------------------------\r\n    // Platform Functions\r\n    // (the imgui_impl_xxxx backend files are setting those up for you)\r\n    //------------------------------------------------------------------\r\n\r\n    // Optional: Platform/Renderer backend name (informational only! will be displayed in About Window) + User data for backend/wrappers to store their own stuff.\r\n    const char* BackendPlatformName;            // = NULL\r\n    const char* BackendRendererName;            // = NULL\r\n    void*       BackendPlatformUserData;        // = NULL           // User data for platform backend\r\n    void*       BackendRendererUserData;        // = NULL           // User data for renderer backend\r\n    void*       BackendLanguageUserData;        // = NULL           // User data for non C++ programming language backend\r\n\r\n    // Optional: Access OS clipboard\r\n    // (default to use native Win32 clipboard on Windows, otherwise uses a private clipboard. Override to access OS clipboard on other architectures)\r\n    const char* (*GetClipboardTextFn)(void* user_data);\r\n    void        (*SetClipboardTextFn)(void* user_data, const char* text);\r\n    void*       ClipboardUserData;\r\n\r\n    // Optional: Notify OS Input Method Editor of the screen position of your cursor for text input position (e.g. when using Japanese/Chinese IME on Windows)\r\n    // (default to use native imm32 api on Windows)\r\n    void        (*SetPlatformImeDataFn)(ImGuiViewport* viewport, ImGuiPlatformImeData* data);\r\n#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS\r\n    void*       ImeWindowHandle;                // = NULL           // [Obsolete] Set ImGuiViewport::PlatformHandleRaw instead. Set this to your HWND to get automatic IME cursor positioning.\r\n#else\r\n    void*       _UnusedPadding;                                     // Unused field to keep data structure the same size.\r\n#endif\r\n\r\n    //------------------------------------------------------------------\r\n    // Input - Call before calling NewFrame()\r\n    //------------------------------------------------------------------\r\n\r\n    // Input Functions\r\n    IMGUI_API void  AddKeyEvent(ImGuiKey key, bool down);                   // Queue a new key down/up event. Key should be \"translated\" (as in, generally ImGuiKey_A matches the key end-user would use to emit an 'A' character)\r\n    IMGUI_API void  AddKeyAnalogEvent(ImGuiKey key, bool down, float v);    // Queue a new key down/up event for analog values (e.g. ImGuiKey_Gamepad_ values). Dead-zones should be handled by the backend.\r\n    IMGUI_API void  AddMousePosEvent(float x, float y);                     // Queue a mouse position update. Use -FLT_MAX,-FLT_MAX to signify no mouse (e.g. app not focused and not hovered)\r\n    IMGUI_API void  AddMouseButtonEvent(int button, bool down);             // Queue a mouse button change\r\n    IMGUI_API void  AddMouseWheelEvent(float wh_x, float wh_y);             // Queue a mouse wheel update\r\n    IMGUI_API void  AddFocusEvent(bool focused);                            // Queue a gain/loss of focus for the application (generally based on OS/platform focus of your window)\r\n    IMGUI_API void  AddInputCharacter(unsigned int c);                      // Queue a new character input\r\n    IMGUI_API void  AddInputCharacterUTF16(ImWchar16 c);                    // Queue a new character input from an UTF-16 character, it can be a surrogate\r\n    IMGUI_API void  AddInputCharactersUTF8(const char* str);                // Queue a new characters input from an UTF-8 string\r\n\r\n    IMGUI_API void  ClearInputCharacters();                                 // [Internal] Clear the text input buffer manually\r\n    IMGUI_API void  ClearInputKeys();                                       // [Internal] Release all keys\r\n    IMGUI_API void  SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native_scancode, int native_legacy_index = -1); // [Optional] Specify index for legacy <1.87 IsKeyXXX() functions with native indices + specify native keycode, scancode.\r\n\r\n    //------------------------------------------------------------------\r\n    // Output - Updated by NewFrame() or EndFrame()/Render()\r\n    // (when reading from the io.WantCaptureMouse, io.WantCaptureKeyboard flags to dispatch your inputs, it is\r\n    //  generally easier and more correct to use their state BEFORE calling NewFrame(). See FAQ for details!)\r\n    //------------------------------------------------------------------\r\n\r\n    bool        WantCaptureMouse;                   // Set when Dear ImGui will use mouse inputs, in this case do not dispatch them to your main game/application (either way, always pass on mouse inputs to imgui). (e.g. unclicked mouse is hovering over an imgui window, widget is active, mouse was clicked over an imgui window, etc.).\r\n    bool        WantCaptureKeyboard;                // Set when Dear ImGui will use keyboard inputs, in this case do not dispatch them to your main game/application (either way, always pass keyboard inputs to imgui). (e.g. InputText active, or an imgui window is focused and navigation is enabled, etc.).\r\n    bool        WantTextInput;                      // Mobile/console: when set, you may display an on-screen keyboard. This is set by Dear ImGui when it wants textual keyboard input to happen (e.g. when a InputText widget is active).\r\n    bool        WantSetMousePos;                    // MousePos has been altered, backend should reposition mouse on next frame. Rarely used! Set only when ImGuiConfigFlags_NavEnableSetMousePos flag is enabled.\r\n    bool        WantSaveIniSettings;                // When manual .ini load/save is active (io.IniFilename == NULL), this will be set to notify your application that you can call SaveIniSettingsToMemory() and save yourself. Important: clear io.WantSaveIniSettings yourself after saving!\r\n    bool        NavActive;                          // Keyboard/Gamepad navigation is currently allowed (will handle ImGuiKey_NavXXX events) = a window is focused and it doesn't use the ImGuiWindowFlags_NoNavInputs flag.\r\n    bool        NavVisible;                         // Keyboard/Gamepad navigation is visible and allowed (will handle ImGuiKey_NavXXX events).\r\n    float       Framerate;                          // Rough estimate of application framerate, in frame per second. Solely for convenience. Rolling average estimation based on io.DeltaTime over 120 frames.\r\n    int         MetricsRenderVertices;              // Vertices output during last call to Render()\r\n    int         MetricsRenderIndices;               // Indices output during last call to Render() = number of triangles * 3\r\n    int         MetricsRenderWindows;               // Number of visible windows\r\n    int         MetricsActiveWindows;               // Number of active windows\r\n    int         MetricsActiveAllocations;           // Number of active allocations, updated by MemAlloc/MemFree based on current context. May be off if you have multiple imgui contexts.\r\n    ImVec2      MouseDelta;                         // Mouse delta. Note that this is zero if either current or previous position are invalid (-FLT_MAX,-FLT_MAX), so a disappearing/reappearing mouse won't have a huge delta.\r\n\r\n    // Legacy: before 1.87, we required backend to fill io.KeyMap[] (imgui->native map) during initialization and io.KeysDown[] (native indices) every frame.\r\n    // This is still temporarily supported as a legacy feature. However the new preferred scheme is for backend to call io.AddKeyEvent().\r\n#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO\r\n    int         KeyMap[ImGuiKey_COUNT];             // [LEGACY] Input: map of indices into the KeysDown[512] entries array which represent your \"native\" keyboard state. The first 512 are now unused and should be kept zero. Legacy backend will write into KeyMap[] using ImGuiKey_ indices which are always >512.\r\n    bool        KeysDown[512];                      // [LEGACY] Input: Keyboard keys that are pressed (ideally left in the \"native\" order your engine has access to keyboard keys, so you can use your own defines/enums for keys).\r\n#endif\r\n\r\n    //------------------------------------------------------------------\r\n    // [Internal] Dear ImGui will maintain those fields. Forward compatibility not guaranteed!\r\n    //------------------------------------------------------------------\r\n\r\n    // Main Input State\r\n    // (this block used to be written by backend, since 1.87 it is best to NOT write to those directly, call the AddXXX functions above instead)\r\n    // (reading from those variables is fair game, as they are extremely unlikely to be moving anywhere)\r\n    ImVec2      MousePos;                           // Mouse position, in pixels. Set to ImVec2(-FLT_MAX, -FLT_MAX) if mouse is unavailable (on another screen, etc.)\r\n    bool        MouseDown[5];                       // Mouse buttons: 0=left, 1=right, 2=middle + extras (ImGuiMouseButton_COUNT == 5). Dear ImGui mostly uses left and right buttons. Others buttons allows us to track if the mouse is being used by your application + available to user as a convenience via IsMouse** API.\r\n    float       MouseWheel;                         // Mouse wheel Vertical: 1 unit scrolls about 5 lines text.\r\n    float       MouseWheelH;                        // Mouse wheel Horizontal. Most users don't have a mouse with an horizontal wheel, may not be filled by all backends.\r\n    bool        KeyCtrl;                            // Keyboard modifier down: Control\r\n    bool        KeyShift;                           // Keyboard modifier down: Shift\r\n    bool        KeyAlt;                             // Keyboard modifier down: Alt\r\n    bool        KeySuper;                           // Keyboard modifier down: Cmd/Super/Windows\r\n    float       NavInputs[ImGuiNavInput_COUNT];     // Gamepad inputs. Cleared back to zero by EndFrame(). Keyboard keys will be auto-mapped and be written here by NewFrame().\r\n\r\n    // Other state maintained from data above + IO function calls\r\n    ImGuiKeyModFlags KeyMods;                       // Key mods flags (same as io.KeyCtrl/KeyShift/KeyAlt/KeySuper but merged into flags), updated by NewFrame()\r\n    ImGuiKeyModFlags KeyModsPrev;                   // Key mods flags (from previous frame)\r\n    ImGuiKeyData KeysData[ImGuiKey_KeysData_SIZE];  // Key state for all known keys. Use IsKeyXXX() functions to access this.\r\n    bool        WantCaptureMouseUnlessPopupClose;   // Alternative to WantCaptureMouse: (WantCaptureMouse == true && WantCaptureMouseUnlessPopupClose == false) when a click over void is expected to close a popup.\r\n    ImVec2      MousePosPrev;                       // Previous mouse position (note that MouseDelta is not necessary == MousePos-MousePosPrev, in case either position is invalid)\r\n    ImVec2      MouseClickedPos[5];                 // Position at time of clicking\r\n    double      MouseClickedTime[5];                // Time of last click (used to figure out double-click)\r\n    bool        MouseClicked[5];                    // Mouse button went from !Down to Down (same as MouseClickedCount[x] != 0)\r\n    bool        MouseDoubleClicked[5];              // Has mouse button been double-clicked? (same as MouseClickedCount[x] == 2)\r\n    ImU16       MouseClickedCount[5];               // == 0 (not clicked), == 1 (same as MouseClicked[]), == 2 (double-clicked), == 3 (triple-clicked) etc. when going from !Down to Down\r\n    ImU16       MouseClickedLastCount[5];           // Count successive number of clicks. Stays valid after mouse release. Reset after another click is done.\r\n    bool        MouseReleased[5];                   // Mouse button went from Down to !Down\r\n    bool        MouseDownOwned[5];                  // Track if button was clicked inside a dear imgui window or over void blocked by a popup. We don't request mouse capture from the application if click started outside ImGui bounds.\r\n    bool        MouseDownOwnedUnlessPopupClose[5];  //Track if button was clicked inside a dear imgui window.\r\n    float       MouseDownDuration[5];               // Duration the mouse button has been down (0.0f == just clicked)\r\n    float       MouseDownDurationPrev[5];           // Previous time the mouse button has been down\r\n    float       MouseDragMaxDistanceSqr[5];         // Squared maximum distance of how much mouse has traveled from the clicking point (used for moving thresholds)\r\n    float       NavInputsDownDuration[ImGuiNavInput_COUNT];\r\n    float       NavInputsDownDurationPrev[ImGuiNavInput_COUNT];\r\n    float       PenPressure;                        // Touch/Pen pressure (0.0f to 1.0f, should be >0.0f only when MouseDown[0] == true). Helper storage currently unused by Dear ImGui.\r\n    bool        AppFocusLost;\r\n    ImS8        BackendUsingLegacyKeyArrays;        // -1: unknown, 0: using AddKeyEvent(), 1: using legacy io.KeysDown[]\r\n    bool        BackendUsingLegacyNavInputArray;    // 0: using AddKeyAnalogEvent(), 1: writing to legacy io.NavInputs[] directly\r\n    ImWchar16   InputQueueSurrogate;                // For AddInputCharacterUTF16()\r\n    ImVector<ImWchar> InputQueueCharacters;         // Queue of _characters_ input (obtained by platform backend). Fill using AddInputCharacter() helper.\r\n\r\n    IMGUI_API   ImGuiIO();\r\n};\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Misc data structures\r\n//-----------------------------------------------------------------------------\r\n\r\n// Shared state of InputText(), passed as an argument to your callback when a ImGuiInputTextFlags_Callback* flag is used.\r\n// The callback function should return 0 by default.\r\n// Callbacks (follow a flag name and see comments in ImGuiInputTextFlags_ declarations for more details)\r\n// - ImGuiInputTextFlags_CallbackEdit:        Callback on buffer edit (note that InputText() already returns true on edit, the callback is useful mainly to manipulate the underlying buffer while focus is active)\r\n// - ImGuiInputTextFlags_CallbackAlways:      Callback on each iteration\r\n// - ImGuiInputTextFlags_CallbackCompletion:  Callback on pressing TAB\r\n// - ImGuiInputTextFlags_CallbackHistory:     Callback on pressing Up/Down arrows\r\n// - ImGuiInputTextFlags_CallbackCharFilter:  Callback on character inputs to replace or discard them. Modify 'EventChar' to replace or discard, or return 1 in callback to discard.\r\n// - ImGuiInputTextFlags_CallbackResize:      Callback on buffer capacity changes request (beyond 'buf_size' parameter value), allowing the string to grow.\r\nstruct ImGuiInputTextCallbackData\r\n{\r\n    ImGuiInputTextFlags EventFlag;      // One ImGuiInputTextFlags_Callback*    // Read-only\r\n    ImGuiInputTextFlags Flags;          // What user passed to InputText()      // Read-only\r\n    void*               UserData;       // What user passed to InputText()      // Read-only\r\n\r\n    // Arguments for the different callback events\r\n    // - To modify the text buffer in a callback, prefer using the InsertChars() / DeleteChars() function. InsertChars() will take care of calling the resize callback if necessary.\r\n    // - If you know your edits are not going to resize the underlying buffer allocation, you may modify the contents of 'Buf[]' directly. You need to update 'BufTextLen' accordingly (0 <= BufTextLen < BufSize) and set 'BufDirty'' to true so InputText can update its internal state.\r\n    ImWchar             EventChar;      // Character input                      // Read-write   // [CharFilter] Replace character with another one, or set to zero to drop. return 1 is equivalent to setting EventChar=0;\r\n    ImGuiKey            EventKey;       // Key pressed (Up/Down/TAB)            // Read-only    // [Completion,History]\r\n    char*               Buf;            // Text buffer                          // Read-write   // [Resize] Can replace pointer / [Completion,History,Always] Only write to pointed data, don't replace the actual pointer!\r\n    int                 BufTextLen;     // Text length (in bytes)               // Read-write   // [Resize,Completion,History,Always] Exclude zero-terminator storage. In C land: == strlen(some_text), in C++ land: string.length()\r\n    int                 BufSize;        // Buffer size (in bytes) = capacity+1  // Read-only    // [Resize,Completion,History,Always] Include zero-terminator storage. In C land == ARRAYSIZE(my_char_array), in C++ land: string.capacity()+1\r\n    bool                BufDirty;       // Set if you modify Buf/BufTextLen!    // Write        // [Completion,History,Always]\r\n    int                 CursorPos;      //                                      // Read-write   // [Completion,History,Always]\r\n    int                 SelectionStart; //                                      // Read-write   // [Completion,History,Always] == to SelectionEnd when no selection)\r\n    int                 SelectionEnd;   //                                      // Read-write   // [Completion,History,Always]\r\n\r\n    // Helper functions for text manipulation.\r\n    // Use those function to benefit from the CallbackResize behaviors. Calling those function reset the selection.\r\n    IMGUI_API ImGuiInputTextCallbackData();\r\n    IMGUI_API void      DeleteChars(int pos, int bytes_count);\r\n    IMGUI_API void      InsertChars(int pos, const char* text, const char* text_end = NULL);\r\n    void                SelectAll()             { SelectionStart = 0; SelectionEnd = BufTextLen; }\r\n    void                ClearSelection()        { SelectionStart = SelectionEnd = BufTextLen; }\r\n    bool                HasSelection() const    { return SelectionStart != SelectionEnd; }\r\n};\r\n\r\n// Resizing callback data to apply custom constraint. As enabled by SetNextWindowSizeConstraints(). Callback is called during the next Begin().\r\n// NB: For basic min/max size constraint on each axis you don't need to use the callback! The SetNextWindowSizeConstraints() parameters are enough.\r\nstruct ImGuiSizeCallbackData\r\n{\r\n    void*   UserData;       // Read-only.   What user passed to SetNextWindowSizeConstraints()\r\n    ImVec2  Pos;            // Read-only.   Window position, for reference.\r\n    ImVec2  CurrentSize;    // Read-only.   Current window size.\r\n    ImVec2  DesiredSize;    // Read-write.  Desired size, based on user's mouse position. Write to this field to restrain resizing.\r\n};\r\n\r\n// Data payload for Drag and Drop operations: AcceptDragDropPayload(), GetDragDropPayload()\r\nstruct ImGuiPayload\r\n{\r\n    // Members\r\n    void*           Data;               // Data (copied and owned by dear imgui)\r\n    int             DataSize;           // Data size\r\n\r\n    // [Internal]\r\n    ImGuiID         SourceId;           // Source item id\r\n    ImGuiID         SourceParentId;     // Source parent id (if available)\r\n    int             DataFrameCount;     // Data timestamp\r\n    char            DataType[32 + 1];   // Data type tag (short user-supplied string, 32 characters max)\r\n    bool            Preview;            // Set when AcceptDragDropPayload() was called and mouse has been hovering the target item (nb: handle overlapping drag targets)\r\n    bool            Delivery;           // Set when AcceptDragDropPayload() was called and mouse button is released over the target item.\r\n\r\n    ImGuiPayload()  { Clear(); }\r\n    void Clear()    { SourceId = SourceParentId = 0; Data = NULL; DataSize = 0; memset(DataType, 0, sizeof(DataType)); DataFrameCount = -1; Preview = Delivery = false; }\r\n    bool IsDataType(const char* type) const { return DataFrameCount != -1 && strcmp(type, DataType) == 0; }\r\n    bool IsPreview() const                  { return Preview; }\r\n    bool IsDelivery() const                 { return Delivery; }\r\n};\r\n\r\n// Sorting specification for one column of a table (sizeof == 12 bytes)\r\nstruct ImGuiTableColumnSortSpecs\r\n{\r\n    ImGuiID                     ColumnUserID;       // User id of the column (if specified by a TableSetupColumn() call)\r\n    ImS16                       ColumnIndex;        // Index of the column\r\n    ImS16                       SortOrder;          // Index within parent ImGuiTableSortSpecs (always stored in order starting from 0, tables sorted on a single criteria will always have a 0 here)\r\n    ImGuiSortDirection          SortDirection : 8;  // ImGuiSortDirection_Ascending or ImGuiSortDirection_Descending (you can use this or SortSign, whichever is more convenient for your sort function)\r\n\r\n    ImGuiTableColumnSortSpecs() { memset(this, 0, sizeof(*this)); }\r\n};\r\n\r\n// Sorting specifications for a table (often handling sort specs for a single column, occasionally more)\r\n// Obtained by calling TableGetSortSpecs().\r\n// When 'SpecsDirty == true' you can sort your data. It will be true with sorting specs have changed since last call, or the first time.\r\n// Make sure to set 'SpecsDirty = false' after sorting, else you may wastefully sort your data every frame!\r\nstruct ImGuiTableSortSpecs\r\n{\r\n    const ImGuiTableColumnSortSpecs* Specs;     // Pointer to sort spec array.\r\n    int                         SpecsCount;     // Sort spec count. Most often 1. May be > 1 when ImGuiTableFlags_SortMulti is enabled. May be == 0 when ImGuiTableFlags_SortTristate is enabled.\r\n    bool                        SpecsDirty;     // Set to true when specs have changed since last time! Use this to sort again, then clear the flag.\r\n\r\n    ImGuiTableSortSpecs()       { memset(this, 0, sizeof(*this)); }\r\n};\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Helpers (ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, ImColor)\r\n//-----------------------------------------------------------------------------\r\n\r\n// Helper: Unicode defines\r\n#define IM_UNICODE_CODEPOINT_INVALID 0xFFFD     // Invalid Unicode code point (standard value).\r\n#ifdef IMGUI_USE_WCHAR32\r\n#define IM_UNICODE_CODEPOINT_MAX     0x10FFFF   // Maximum Unicode code point supported by this build.\r\n#else\r\n#define IM_UNICODE_CODEPOINT_MAX     0xFFFF     // Maximum Unicode code point supported by this build.\r\n#endif\r\n\r\n// Helper: Execute a block of code at maximum once a frame. Convenient if you want to quickly create an UI within deep-nested code that runs multiple times every frame.\r\n// Usage: static ImGuiOnceUponAFrame oaf; if (oaf) ImGui::Text(\"This will be called only once per frame\");\r\nstruct ImGuiOnceUponAFrame\r\n{\r\n    ImGuiOnceUponAFrame() { RefFrame = -1; }\r\n    mutable int RefFrame;\r\n    operator bool() const { int current_frame = ImGui::GetFrameCount(); if (RefFrame == current_frame) return false; RefFrame = current_frame; return true; }\r\n};\r\n\r\n// Helper: Parse and apply text filters. In format \"aaaaa[,bbbb][,ccccc]\"\r\nstruct ImGuiTextFilter\r\n{\r\n    IMGUI_API           ImGuiTextFilter(const char* default_filter = \"\");\r\n    IMGUI_API bool      Draw(const char* label = \"Filter (inc,-exc)\", float width = 0.0f);  // Helper calling InputText+Build\r\n    IMGUI_API bool      PassFilter(const char* text, const char* text_end = NULL) const;\r\n    IMGUI_API void      Build();\r\n    void                Clear()          { InputBuf[0] = 0; Build(); }\r\n    bool                IsActive() const { return !Filters.empty(); }\r\n\r\n    // [Internal]\r\n    struct ImGuiTextRange\r\n    {\r\n        const char*     b;\r\n        const char*     e;\r\n\r\n        ImGuiTextRange()                                { b = e = NULL; }\r\n        ImGuiTextRange(const char* _b, const char* _e)  { b = _b; e = _e; }\r\n        bool            empty() const                   { return b == e; }\r\n        IMGUI_API void  split(char separator, ImVector<ImGuiTextRange>* out) const;\r\n    };\r\n    char                    InputBuf[256];\r\n    ImVector<ImGuiTextRange>Filters;\r\n    int                     CountGrep;\r\n};\r\n\r\n// Helper: Growable text buffer for logging/accumulating text\r\n// (this could be called 'ImGuiTextBuilder' / 'ImGuiStringBuilder')\r\nstruct ImGuiTextBuffer\r\n{\r\n    ImVector<char>      Buf;\r\n    IMGUI_API static char EmptyString[1];\r\n\r\n    ImGuiTextBuffer()   { }\r\n    inline char         operator[](int i) const { IM_ASSERT(Buf.Data != NULL); return Buf.Data[i]; }\r\n    const char*         begin() const           { return Buf.Data ? &Buf.front() : EmptyString; }\r\n    const char*         end() const             { return Buf.Data ? &Buf.back() : EmptyString; }   // Buf is zero-terminated, so end() will point on the zero-terminator\r\n    int                 size() const            { return Buf.Size ? Buf.Size - 1 : 0; }\r\n    bool                empty() const           { return Buf.Size <= 1; }\r\n    void                clear()                 { Buf.clear(); }\r\n    void                reserve(int capacity)   { Buf.reserve(capacity); }\r\n    const char*         c_str() const           { return Buf.Data ? Buf.Data : EmptyString; }\r\n    IMGUI_API void      append(const char* str, const char* str_end = NULL);\r\n    IMGUI_API void      appendf(const char* fmt, ...) IM_FMTARGS(2);\r\n    IMGUI_API void      appendfv(const char* fmt, va_list args) IM_FMTLIST(2);\r\n};\r\n\r\n// Helper: Key->Value storage\r\n// Typically you don't have to worry about this since a storage is held within each Window.\r\n// We use it to e.g. store collapse state for a tree (Int 0/1)\r\n// This is optimized for efficient lookup (dichotomy into a contiguous buffer) and rare insertion (typically tied to user interactions aka max once a frame)\r\n// You can use it as custom user storage for temporary values. Declare your own storage if, for example:\r\n// - You want to manipulate the open/close state of a particular sub-tree in your interface (tree node uses Int 0/1 to store their state).\r\n// - You want to store custom debug data easily without adding or editing structures in your code (probably not efficient, but convenient)\r\n// Types are NOT stored, so it is up to you to make sure your Key don't collide with different types.\r\nstruct ImGuiStorage\r\n{\r\n    // [Internal]\r\n    struct ImGuiStoragePair\r\n    {\r\n        ImGuiID key;\r\n        union { int val_i; float val_f; void* val_p; };\r\n        ImGuiStoragePair(ImGuiID _key, int _val_i)      { key = _key; val_i = _val_i; }\r\n        ImGuiStoragePair(ImGuiID _key, float _val_f)    { key = _key; val_f = _val_f; }\r\n        ImGuiStoragePair(ImGuiID _key, void* _val_p)    { key = _key; val_p = _val_p; }\r\n    };\r\n\r\n    ImVector<ImGuiStoragePair>      Data;\r\n\r\n    // - Get***() functions find pair, never add/allocate. Pairs are sorted so a query is O(log N)\r\n    // - Set***() functions find pair, insertion on demand if missing.\r\n    // - Sorted insertion is costly, paid once. A typical frame shouldn't need to insert any new pair.\r\n    void                Clear() { Data.clear(); }\r\n    IMGUI_API int       GetInt(ImGuiID key, int default_val = 0) const;\r\n    IMGUI_API void      SetInt(ImGuiID key, int val);\r\n    IMGUI_API bool      GetBool(ImGuiID key, bool default_val = false) const;\r\n    IMGUI_API void      SetBool(ImGuiID key, bool val);\r\n    IMGUI_API float     GetFloat(ImGuiID key, float default_val = 0.0f) const;\r\n    IMGUI_API void      SetFloat(ImGuiID key, float val);\r\n    IMGUI_API void*     GetVoidPtr(ImGuiID key) const; // default_val is NULL\r\n    IMGUI_API void      SetVoidPtr(ImGuiID key, void* val);\r\n\r\n    // - Get***Ref() functions finds pair, insert on demand if missing, return pointer. Useful if you intend to do Get+Set.\r\n    // - References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer.\r\n    // - A typical use case where this is convenient for quick hacking (e.g. add storage during a live Edit&Continue session if you can't modify existing struct)\r\n    //      float* pvar = ImGui::GetFloatRef(key); ImGui::SliderFloat(\"var\", pvar, 0, 100.0f); some_var += *pvar;\r\n    IMGUI_API int*      GetIntRef(ImGuiID key, int default_val = 0);\r\n    IMGUI_API bool*     GetBoolRef(ImGuiID key, bool default_val = false);\r\n    IMGUI_API float*    GetFloatRef(ImGuiID key, float default_val = 0.0f);\r\n    IMGUI_API void**    GetVoidPtrRef(ImGuiID key, void* default_val = NULL);\r\n\r\n    // Use on your own storage if you know only integer are being stored (open/close all tree nodes)\r\n    IMGUI_API void      SetAllInt(int val);\r\n\r\n    // For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.\r\n    IMGUI_API void      BuildSortByKey();\r\n};\r\n\r\n// Helper: Manually clip large list of items.\r\n// If you have lots evenly spaced items and you have a random access to the list, you can perform coarse\r\n// clipping based on visibility to only submit items that are in view.\r\n// The clipper calculates the range of visible items and advance the cursor to compensate for the non-visible items we have skipped.\r\n// (Dear ImGui already clip items based on their bounds but: it needs to first layout the item to do so, and generally\r\n//  fetching/submitting your own data incurs additional cost. Coarse clipping using ImGuiListClipper allows you to easily\r\n//  scale using lists with tens of thousands of items without a problem)\r\n// Usage:\r\n//   ImGuiListClipper clipper;\r\n//   clipper.Begin(1000);         // We have 1000 elements, evenly spaced.\r\n//   while (clipper.Step())\r\n//       for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)\r\n//           ImGui::Text(\"line number %d\", i);\r\n// Generally what happens is:\r\n// - Clipper lets you process the first element (DisplayStart = 0, DisplayEnd = 1) regardless of it being visible or not.\r\n// - User code submit that one element.\r\n// - Clipper can measure the height of the first element\r\n// - Clipper calculate the actual range of elements to display based on the current clipping rectangle, position the cursor before the first visible element.\r\n// - User code submit visible elements.\r\n// - The clipper also handles various subtleties related to keyboard/gamepad navigation, wrapping etc.\r\nstruct ImGuiListClipper\r\n{\r\n    int             DisplayStart;       // First item to display, updated by each call to Step()\r\n    int             DisplayEnd;         // End of items to display (exclusive)\r\n    int             ItemsCount;         // [Internal] Number of items\r\n    float           ItemsHeight;        // [Internal] Height of item after a first step and item submission can calculate it\r\n    float           StartPosY;          // [Internal] Cursor position at the time of Begin() or after table frozen rows are all processed\r\n    void*           TempData;           // [Internal] Internal data\r\n\r\n    // items_count: Use INT_MAX if you don't know how many items you have (in which case the cursor won't be advanced in the final step)\r\n    // items_height: Use -1.0f to be calculated automatically on first step. Otherwise pass in the distance between your items, typically GetTextLineHeightWithSpacing() or GetFrameHeightWithSpacing().\r\n    IMGUI_API ImGuiListClipper();\r\n    IMGUI_API ~ImGuiListClipper();\r\n    IMGUI_API void  Begin(int items_count, float items_height = -1.0f);\r\n    IMGUI_API void  End();             // Automatically called on the last call of Step() that returns false.\r\n    IMGUI_API bool  Step();            // Call until it returns false. The DisplayStart/DisplayEnd fields will be set and you can process/draw those items.\r\n\r\n    // Call ForceDisplayRangeByIndices() before first call to Step() if you need a range of items to be displayed regardless of visibility.\r\n    IMGUI_API void  ForceDisplayRangeByIndices(int item_min, int item_max); // item_max is exclusive e.g. use (42, 42+1) to make item 42 always visible BUT due to alignment/padding of certain items it is likely that an extra item may be included on either end of the display range.\r\n\r\n#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS\r\n    inline ImGuiListClipper(int items_count, float items_height = -1.0f) { memset(this, 0, sizeof(*this)); ItemsCount = -1; Begin(items_count, items_height); } // [removed in 1.79]\r\n#endif\r\n};\r\n\r\n// Helpers macros to generate 32-bit encoded colors\r\n#ifdef IMGUI_USE_BGRA_PACKED_COLOR\r\n#define IM_COL32_R_SHIFT    16\r\n#define IM_COL32_G_SHIFT    8\r\n#define IM_COL32_B_SHIFT    0\r\n#define IM_COL32_A_SHIFT    24\r\n#define IM_COL32_A_MASK     0xFF000000\r\n#else\r\n#define IM_COL32_R_SHIFT    0\r\n#define IM_COL32_G_SHIFT    8\r\n#define IM_COL32_B_SHIFT    16\r\n#define IM_COL32_A_SHIFT    24\r\n#define IM_COL32_A_MASK     0xFF000000\r\n#endif\r\n#define IM_COL32(R,G,B,A)    (((ImU32)(A)<<IM_COL32_A_SHIFT) | ((ImU32)(B)<<IM_COL32_B_SHIFT) | ((ImU32)(G)<<IM_COL32_G_SHIFT) | ((ImU32)(R)<<IM_COL32_R_SHIFT))\r\n#define IM_COL32_WHITE       IM_COL32(255,255,255,255)  // Opaque white = 0xFFFFFFFF\r\n#define IM_COL32_BLACK       IM_COL32(0,0,0,255)        // Opaque black\r\n#define IM_COL32_BLACK_TRANS IM_COL32(0,0,0,0)          // Transparent black = 0x00000000\r\n\r\n// Helper: ImColor() implicitly converts colors to either ImU32 (packed 4x1 byte) or ImVec4 (4x1 float)\r\n// Prefer using IM_COL32() macros if you want a guaranteed compile-time ImU32 for usage with ImDrawList API.\r\n// **Avoid storing ImColor! Store either u32 of ImVec4. This is not a full-featured color class. MAY OBSOLETE.\r\n// **None of the ImGui API are using ImColor directly but you can use it as a convenience to pass colors in either ImU32 or ImVec4 formats. Explicitly cast to ImU32 or ImVec4 if needed.\r\nstruct ImColor\r\n{\r\n    ImVec4              Value;\r\n\r\n    ImColor()                                                       { Value.x = Value.y = Value.z = Value.w = 0.0f; }\r\n    ImColor(int r, int g, int b, int a = 255)                       { float sc = 1.0f / 255.0f; Value.x = (float)r * sc; Value.y = (float)g * sc; Value.z = (float)b * sc; Value.w = (float)a * sc; }\r\n    ImColor(ImU32 rgba)                                             { float sc = 1.0f / 255.0f; Value.x = (float)((rgba >> IM_COL32_R_SHIFT) & 0xFF) * sc; Value.y = (float)((rgba >> IM_COL32_G_SHIFT) & 0xFF) * sc; Value.z = (float)((rgba >> IM_COL32_B_SHIFT) & 0xFF) * sc; Value.w = (float)((rgba >> IM_COL32_A_SHIFT) & 0xFF) * sc; }\r\n    ImColor(float r, float g, float b, float a = 1.0f)              { Value.x = r; Value.y = g; Value.z = b; Value.w = a; }\r\n    ImColor(const ImVec4& col)                                      { Value = col; }\r\n    inline operator ImU32() const                                   { return ImGui::ColorConvertFloat4ToU32(Value); }\r\n    inline operator ImVec4() const                                  { return Value; }\r\n\r\n    // FIXME-OBSOLETE: May need to obsolete/cleanup those helpers.\r\n    inline void    SetHSV(float h, float s, float v, float a = 1.0f){ ImGui::ColorConvertHSVtoRGB(h, s, v, Value.x, Value.y, Value.z); Value.w = a; }\r\n    static ImColor HSV(float h, float s, float v, float a = 1.0f)   { float r, g, b; ImGui::ColorConvertHSVtoRGB(h, s, v, r, g, b); return ImColor(r, g, b, a); }\r\n};\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Drawing API (ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawListFlags, ImDrawList, ImDrawData)\r\n// Hold a series of drawing commands. The user provides a renderer for ImDrawData which essentially contains an array of ImDrawList.\r\n//-----------------------------------------------------------------------------\r\n\r\n// The maximum line width to bake anti-aliased textures for. Build atlas with ImFontAtlasFlags_NoBakedLines to disable baking.\r\n#ifndef IM_DRAWLIST_TEX_LINES_WIDTH_MAX\r\n#define IM_DRAWLIST_TEX_LINES_WIDTH_MAX     (63)\r\n#endif\r\n\r\n// ImDrawCallback: Draw callbacks for advanced uses [configurable type: override in imconfig.h]\r\n// NB: You most likely do NOT need to use draw callbacks just to create your own widget or customized UI rendering,\r\n// you can poke into the draw list for that! Draw callback may be useful for example to:\r\n//  A) Change your GPU render state,\r\n//  B) render a complex 3D scene inside a UI element without an intermediate texture/render target, etc.\r\n// The expected behavior from your rendering function is 'if (cmd.UserCallback != NULL) { cmd.UserCallback(parent_list, cmd); } else { RenderTriangles() }'\r\n// If you want to override the signature of ImDrawCallback, you can simply use e.g. '#define ImDrawCallback MyDrawCallback' (in imconfig.h) + update rendering backend accordingly.\r\n#ifndef ImDrawCallback\r\ntypedef void (*ImDrawCallback)(const ImDrawList* parent_list, const ImDrawCmd* cmd);\r\n#endif\r\n\r\n// Special Draw callback value to request renderer backend to reset the graphics/render state.\r\n// The renderer backend needs to handle this special value, otherwise it will crash trying to call a function at this address.\r\n// This is useful for example if you submitted callbacks which you know have altered the render state and you want it to be restored.\r\n// It is not done by default because they are many perfectly useful way of altering render state for imgui contents (e.g. changing shader/blending settings before an Image call).\r\n#define ImDrawCallback_ResetRenderState     (ImDrawCallback)(-1)\r\n\r\n// Typically, 1 command = 1 GPU draw call (unless command is a callback)\r\n// - VtxOffset: When 'io.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset' is enabled,\r\n//   this fields allow us to render meshes larger than 64K vertices while keeping 16-bit indices.\r\n//   Backends made for <1.71. will typically ignore the VtxOffset fields.\r\n// - The ClipRect/TextureId/VtxOffset fields must be contiguous as we memcmp() them together (this is asserted for).\r\nstruct ImDrawCmd\r\n{\r\n    ImVec4          ClipRect;           // 4*4  // Clipping rectangle (x1, y1, x2, y2). Subtract ImDrawData->DisplayPos to get clipping rectangle in \"viewport\" coordinates\r\n    ImTextureID     TextureId;          // 4-8  // User-provided texture ID. Set by user in ImfontAtlas::SetTexID() for fonts or passed to Image*() functions. Ignore if never using images or multiple fonts atlas.\r\n    unsigned int    VtxOffset;          // 4    // Start offset in vertex buffer. ImGuiBackendFlags_RendererHasVtxOffset: always 0, otherwise may be >0 to support meshes larger than 64K vertices with 16-bit indices.\r\n    unsigned int    IdxOffset;          // 4    // Start offset in index buffer.\r\n    unsigned int    ElemCount;          // 4    // Number of indices (multiple of 3) to be rendered as triangles. Vertices are stored in the callee ImDrawList's vtx_buffer[] array, indices in idx_buffer[].\r\n    ImDrawCallback  UserCallback;       // 4-8  // If != NULL, call the function instead of rendering the vertices. clip_rect and texture_id will be set normally.\r\n    void*           UserCallbackData;   // 4-8  // The draw callback code can access this.\r\n\r\n    ImDrawCmd() { memset(this, 0, sizeof(*this)); } // Also ensure our padding fields are zeroed\r\n\r\n    // Since 1.83: returns ImTextureID associated with this draw call. Warning: DO NOT assume this is always same as 'TextureId' (we will change this function for an upcoming feature)\r\n    inline ImTextureID GetTexID() const { return TextureId; }\r\n};\r\n\r\n// Vertex layout\r\n#ifndef IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT\r\nstruct ImDrawVert\r\n{\r\n    ImVec2  pos;\r\n    ImVec2  uv;\r\n    ImU32   col;\r\n};\r\n#else\r\n// You can override the vertex format layout by defining IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT in imconfig.h\r\n// The code expect ImVec2 pos (8 bytes), ImVec2 uv (8 bytes), ImU32 col (4 bytes), but you can re-order them or add other fields as needed to simplify integration in your engine.\r\n// The type has to be described within the macro (you can either declare the struct or use a typedef). This is because ImVec2/ImU32 are likely not declared a the time you'd want to set your type up.\r\n// NOTE: IMGUI DOESN'T CLEAR THE STRUCTURE AND DOESN'T CALL A CONSTRUCTOR SO ANY CUSTOM FIELD WILL BE UNINITIALIZED. IF YOU ADD EXTRA FIELDS (SUCH AS A 'Z' COORDINATES) YOU WILL NEED TO CLEAR THEM DURING RENDER OR TO IGNORE THEM.\r\nIMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT;\r\n#endif\r\n\r\n// [Internal] For use by ImDrawList\r\nstruct ImDrawCmdHeader\r\n{\r\n    ImVec4          ClipRect;\r\n    ImTextureID     TextureId;\r\n    unsigned int    VtxOffset;\r\n};\r\n\r\n// [Internal] For use by ImDrawListSplitter\r\nstruct ImDrawChannel\r\n{\r\n    ImVector<ImDrawCmd>         _CmdBuffer;\r\n    ImVector<ImDrawIdx>         _IdxBuffer;\r\n};\r\n\r\n\r\n// Split/Merge functions are used to split the draw list into different layers which can be drawn into out of order.\r\n// This is used by the Columns/Tables API, so items of each column can be batched together in a same draw call.\r\nstruct ImDrawListSplitter\r\n{\r\n    int                         _Current;    // Current channel number (0)\r\n    int                         _Count;      // Number of active channels (1+)\r\n    ImVector<ImDrawChannel>     _Channels;   // Draw channels (not resized down so _Count might be < Channels.Size)\r\n\r\n    inline ImDrawListSplitter()  { memset(this, 0, sizeof(*this)); }\r\n    inline ~ImDrawListSplitter() { ClearFreeMemory(); }\r\n    inline void                 Clear() { _Current = 0; _Count = 1; } // Do not clear Channels[] so our allocations are reused next frame\r\n    IMGUI_API void              ClearFreeMemory();\r\n    IMGUI_API void              Split(ImDrawList* draw_list, int count);\r\n    IMGUI_API void              Merge(ImDrawList* draw_list);\r\n    IMGUI_API void              SetCurrentChannel(ImDrawList* draw_list, int channel_idx);\r\n};\r\n\r\n// Flags for ImDrawList functions\r\n// (Legacy: bit 0 must always correspond to ImDrawFlags_Closed to be backward compatible with old API using a bool. Bits 1..3 must be unused)\r\nenum ImDrawFlags_\r\n{\r\n    ImDrawFlags_None                        = 0,\r\n    ImDrawFlags_Closed                      = 1 << 0, // PathStroke(), AddPolyline(): specify that shape should be closed (Important: this is always == 1 for legacy reason)\r\n    ImDrawFlags_RoundCornersTopLeft         = 1 << 4, // AddRect(), AddRectFilled(), PathRect(): enable rounding top-left corner only (when rounding > 0.0f, we default to all corners). Was 0x01.\r\n    ImDrawFlags_RoundCornersTopRight        = 1 << 5, // AddRect(), AddRectFilled(), PathRect(): enable rounding top-right corner only (when rounding > 0.0f, we default to all corners). Was 0x02.\r\n    ImDrawFlags_RoundCornersBottomLeft      = 1 << 6, // AddRect(), AddRectFilled(), PathRect(): enable rounding bottom-left corner only (when rounding > 0.0f, we default to all corners). Was 0x04.\r\n    ImDrawFlags_RoundCornersBottomRight     = 1 << 7, // AddRect(), AddRectFilled(), PathRect(): enable rounding bottom-right corner only (when rounding > 0.0f, we default to all corners). Wax 0x08.\r\n    ImDrawFlags_RoundCornersNone            = 1 << 8, // AddRect(), AddRectFilled(), PathRect(): disable rounding on all corners (when rounding > 0.0f). This is NOT zero, NOT an implicit flag!\r\n    ImDrawFlags_RoundCornersTop             = ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersTopRight,\r\n    ImDrawFlags_RoundCornersBottom          = ImDrawFlags_RoundCornersBottomLeft | ImDrawFlags_RoundCornersBottomRight,\r\n    ImDrawFlags_RoundCornersLeft            = ImDrawFlags_RoundCornersBottomLeft | ImDrawFlags_RoundCornersTopLeft,\r\n    ImDrawFlags_RoundCornersRight           = ImDrawFlags_RoundCornersBottomRight | ImDrawFlags_RoundCornersTopRight,\r\n    ImDrawFlags_RoundCornersAll             = ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersTopRight | ImDrawFlags_RoundCornersBottomLeft | ImDrawFlags_RoundCornersBottomRight,\r\n    ImDrawFlags_RoundCornersDefault_        = ImDrawFlags_RoundCornersAll, // Default to ALL corners if none of the _RoundCornersXX flags are specified.\r\n    ImDrawFlags_RoundCornersMask_           = ImDrawFlags_RoundCornersAll | ImDrawFlags_RoundCornersNone\r\n};\r\n\r\n// Flags for ImDrawList instance. Those are set automatically by ImGui:: functions from ImGuiIO settings, and generally not manipulated directly.\r\n// It is however possible to temporarily alter flags between calls to ImDrawList:: functions.\r\nenum ImDrawListFlags_\r\n{\r\n    ImDrawListFlags_None                    = 0,\r\n    ImDrawListFlags_AntiAliasedLines        = 1 << 0,  // Enable anti-aliased lines/borders (*2 the number of triangles for 1.0f wide line or lines thin enough to be drawn using textures, otherwise *3 the number of triangles)\r\n    ImDrawListFlags_AntiAliasedLinesUseTex  = 1 << 1,  // Enable anti-aliased lines/borders using textures when possible. Require backend to render with bilinear filtering.\r\n    ImDrawListFlags_AntiAliasedFill         = 1 << 2,  // Enable anti-aliased edge around filled shapes (rounded rectangles, circles).\r\n    ImDrawListFlags_AllowVtxOffset          = 1 << 3   // Can emit 'VtxOffset > 0' to allow large meshes. Set when 'ImGuiBackendFlags_RendererHasVtxOffset' is enabled.\r\n};\r\n\r\n// Draw command list\r\n// This is the low-level list of polygons that ImGui:: functions are filling. At the end of the frame,\r\n// all command lists are passed to your ImGuiIO::RenderDrawListFn function for rendering.\r\n// Each dear imgui window contains its own ImDrawList. You can use ImGui::GetWindowDrawList() to\r\n// access the current window draw list and draw custom primitives.\r\n// You can interleave normal ImGui:: calls and adding primitives to the current draw list.\r\n// In single viewport mode, top-left is == GetMainViewport()->Pos (generally 0,0), bottom-right is == GetMainViewport()->Pos+Size (generally io.DisplaySize).\r\n// You are totally free to apply whatever transformation matrix to want to the data (depending on the use of the transformation you may want to apply it to ClipRect as well!)\r\n// Important: Primitives are always added to the list and not culled (culling is done at higher-level by ImGui:: functions), if you use this API a lot consider coarse culling your drawn objects.\r\nstruct ImDrawList\r\n{\r\n    // This is what you have to render\r\n    ImVector<ImDrawCmd>     CmdBuffer;          // Draw commands. Typically 1 command = 1 GPU draw call, unless the command is a callback.\r\n    ImVector<ImDrawIdx>     IdxBuffer;          // Index buffer. Each command consume ImDrawCmd::ElemCount of those\r\n    ImVector<ImDrawVert>    VtxBuffer;          // Vertex buffer.\r\n    ImDrawListFlags         Flags;              // Flags, you may poke into these to adjust anti-aliasing settings per-primitive.\r\n\r\n    // [Internal, used while building lists]\r\n    unsigned int            _VtxCurrentIdx;     // [Internal] generally == VtxBuffer.Size unless we are past 64K vertices, in which case this gets reset to 0.\r\n    const ImDrawListSharedData* _Data;          // Pointer to shared draw data (you can use ImGui::GetDrawListSharedData() to get the one from current ImGui context)\r\n    const char*             _OwnerName;         // Pointer to owner window's name for debugging\r\n    ImDrawVert*             _VtxWritePtr;       // [Internal] point within VtxBuffer.Data after each add command (to avoid using the ImVector<> operators too much)\r\n    ImDrawIdx*              _IdxWritePtr;       // [Internal] point within IdxBuffer.Data after each add command (to avoid using the ImVector<> operators too much)\r\n    ImVector<ImVec4>        _ClipRectStack;     // [Internal]\r\n    ImVector<ImTextureID>   _TextureIdStack;    // [Internal]\r\n    ImVector<ImVec2>        _Path;              // [Internal] current path building\r\n    ImDrawCmdHeader         _CmdHeader;         // [Internal] template of active commands. Fields should match those of CmdBuffer.back().\r\n    ImDrawListSplitter      _Splitter;          // [Internal] for channels api (note: prefer using your own persistent instance of ImDrawListSplitter!)\r\n    float                   _FringeScale;       // [Internal] anti-alias fringe is scaled by this value, this helps to keep things sharp while zooming at vertex buffer content\r\n\r\n    // If you want to create ImDrawList instances, pass them ImGui::GetDrawListSharedData() or create and use your own ImDrawListSharedData (so you can use ImDrawList without ImGui)\r\n    ImDrawList(const ImDrawListSharedData* shared_data) { memset(this, 0, sizeof(*this)); _Data = shared_data; }\r\n\r\n    ~ImDrawList() { _ClearFreeMemory(); }\r\n    IMGUI_API void  PushClipRect(ImVec2 clip_rect_min, ImVec2 clip_rect_max, bool intersect_with_current_clip_rect = false);  // Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui::PushClipRect() to affect logic (hit-testing and widget culling)\r\n    IMGUI_API void  PushClipRectFullScreen();\r\n    IMGUI_API void  PopClipRect();\r\n    IMGUI_API void  PushTextureID(ImTextureID texture_id);\r\n    IMGUI_API void  PopTextureID();\r\n    inline ImVec2   GetClipRectMin() const { const ImVec4& cr = _ClipRectStack.back(); return ImVec2(cr.x, cr.y); }\r\n    inline ImVec2   GetClipRectMax() const { const ImVec4& cr = _ClipRectStack.back(); return ImVec2(cr.z, cr.w); }\r\n\r\n    // Primitives\r\n    // - For rectangular primitives, \"p_min\" and \"p_max\" represent the upper-left and lower-right corners.\r\n    // - For circle primitives, use \"num_segments == 0\" to automatically calculate tessellation (preferred).\r\n    //   In older versions (until Dear ImGui 1.77) the AddCircle functions defaulted to num_segments == 12.\r\n    //   In future versions we will use textures to provide cheaper and higher-quality circles.\r\n    //   Use AddNgon() and AddNgonFilled() functions if you need to guaranteed a specific number of sides.\r\n    IMGUI_API void  AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float thickness = 1.0f);\r\n    IMGUI_API void  AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding = 0.0f, ImDrawFlags flags = 0, float thickness = 1.0f);   // a: upper-left, b: lower-right (== upper-left + size)\r\n    IMGUI_API void  AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding = 0.0f, ImDrawFlags flags = 0);                     // a: upper-left, b: lower-right (== upper-left + size)\r\n    IMGUI_API void  AddRectFilledMultiColor(const ImVec2& p_min, const ImVec2& p_max, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left);\r\n    IMGUI_API void  AddQuad(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness = 1.0f);\r\n    IMGUI_API void  AddQuadFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col);\r\n    IMGUI_API void  AddTriangle(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness = 1.0f);\r\n    IMGUI_API void  AddTriangleFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col);\r\n    IMGUI_API void  AddCircle(const ImVec2& center, float radius, ImU32 col, int num_segments = 0, float thickness = 1.0f);\r\n    IMGUI_API void  AddCircleFilled(const ImVec2& center, float radius, ImU32 col, int num_segments = 0);\r\n    IMGUI_API void  AddNgon(const ImVec2& center, float radius, ImU32 col, int num_segments, float thickness = 1.0f);\r\n    IMGUI_API void  AddNgonFilled(const ImVec2& center, float radius, ImU32 col, int num_segments);\r\n    IMGUI_API void  AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL);\r\n    IMGUI_API void  AddText(const ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL, float wrap_width = 0.0f, const ImVec4* cpu_fine_clip_rect = NULL);\r\n    IMGUI_API void  AddPolyline(const ImVec2* points, int num_points, ImU32 col, ImDrawFlags flags, float thickness);\r\n    IMGUI_API void  AddConvexPolyFilled(const ImVec2* points, int num_points, ImU32 col); // Note: Anti-aliased filling requires points to be in clockwise order.\r\n    IMGUI_API void  AddBezierCubic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness, int num_segments = 0); // Cubic Bezier (4 control points)\r\n    IMGUI_API void  AddBezierQuadratic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness, int num_segments = 0);               // Quadratic Bezier (3 control points)\r\n\r\n    // Image primitives\r\n    // - Read FAQ to understand what ImTextureID is.\r\n    // - \"p_min\" and \"p_max\" represent the upper-left and lower-right corners of the rectangle.\r\n    // - \"uv_min\" and \"uv_max\" represent the normalized texture coordinates to use for those corners. Using (0,0)->(1,1) texture coordinates will generally display the entire texture.\r\n    IMGUI_API void  AddImage(ImTextureID user_texture_id, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min = ImVec2(0, 0), const ImVec2& uv_max = ImVec2(1, 1), ImU32 col = IM_COL32_WHITE);\r\n    IMGUI_API void  AddImageQuad(ImTextureID user_texture_id, const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& uv1 = ImVec2(0, 0), const ImVec2& uv2 = ImVec2(1, 0), const ImVec2& uv3 = ImVec2(1, 1), const ImVec2& uv4 = ImVec2(0, 1), ImU32 col = IM_COL32_WHITE);\r\n    IMGUI_API void  AddImageRounded(ImTextureID user_texture_id, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min, const ImVec2& uv_max, ImU32 col, float rounding, ImDrawFlags flags = 0);\r\n\r\n    // Stateful path API, add points then finish with PathFillConvex() or PathStroke()\r\n    inline    void  PathClear()                                                 { _Path.Size = 0; }\r\n    inline    void  PathLineTo(const ImVec2& pos)                               { _Path.push_back(pos); }\r\n    inline    void  PathLineToMergeDuplicate(const ImVec2& pos)                 { if (_Path.Size == 0 || memcmp(&_Path.Data[_Path.Size - 1], &pos, 8) != 0) _Path.push_back(pos); }\r\n    inline    void  PathFillConvex(ImU32 col)                                   { AddConvexPolyFilled(_Path.Data, _Path.Size, col); _Path.Size = 0; }  // Note: Anti-aliased filling requires points to be in clockwise order.\r\n    inline    void  PathStroke(ImU32 col, ImDrawFlags flags = 0, float thickness = 1.0f) { AddPolyline(_Path.Data, _Path.Size, col, flags, thickness); _Path.Size = 0; }\r\n    IMGUI_API void  PathArcTo(const ImVec2& center, float radius, float a_min, float a_max, int num_segments = 0);\r\n    IMGUI_API void  PathArcToFast(const ImVec2& center, float radius, int a_min_of_12, int a_max_of_12);                // Use precomputed angles for a 12 steps circle\r\n    IMGUI_API void  PathBezierCubicCurveTo(const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, int num_segments = 0); // Cubic Bezier (4 control points)\r\n    IMGUI_API void  PathBezierQuadraticCurveTo(const ImVec2& p2, const ImVec2& p3, int num_segments = 0);               // Quadratic Bezier (3 control points)\r\n    IMGUI_API void  PathRect(const ImVec2& rect_min, const ImVec2& rect_max, float rounding = 0.0f, ImDrawFlags flags = 0);\r\n\r\n    // Advanced\r\n    IMGUI_API void  AddCallback(ImDrawCallback callback, void* callback_data);  // Your rendering function must check for 'UserCallback' in ImDrawCmd and call the function instead of rendering triangles.\r\n    IMGUI_API void  AddDrawCmd();                                               // This is useful if you need to forcefully create a new draw call (to allow for dependent rendering / blending). Otherwise primitives are merged into the same draw-call as much as possible\r\n    IMGUI_API ImDrawList* CloneOutput() const;                                  // Create a clone of the CmdBuffer/IdxBuffer/VtxBuffer.\r\n\r\n    // Advanced: Channels\r\n    // - Use to split render into layers. By switching channels to can render out-of-order (e.g. submit FG primitives before BG primitives)\r\n    // - Use to minimize draw calls (e.g. if going back-and-forth between multiple clipping rectangles, prefer to append into separate channels then merge at the end)\r\n    // - FIXME-OBSOLETE: This API shouldn't have been in ImDrawList in the first place!\r\n    //   Prefer using your own persistent instance of ImDrawListSplitter as you can stack them.\r\n    //   Using the ImDrawList::ChannelsXXXX you cannot stack a split over another.\r\n    inline void     ChannelsSplit(int count)    { _Splitter.Split(this, count); }\r\n    inline void     ChannelsMerge()             { _Splitter.Merge(this); }\r\n    inline void     ChannelsSetCurrent(int n)   { _Splitter.SetCurrentChannel(this, n); }\r\n\r\n    // Advanced: Primitives allocations\r\n    // - We render triangles (three vertices)\r\n    // - All primitives needs to be reserved via PrimReserve() beforehand.\r\n    IMGUI_API void  PrimReserve(int idx_count, int vtx_count);\r\n    IMGUI_API void  PrimUnreserve(int idx_count, int vtx_count);\r\n    IMGUI_API void  PrimRect(const ImVec2& a, const ImVec2& b, ImU32 col);      // Axis aligned rectangle (composed of two triangles)\r\n    IMGUI_API void  PrimRectUV(const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col);\r\n    IMGUI_API void  PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a, const ImVec2& uv_b, const ImVec2& uv_c, const ImVec2& uv_d, ImU32 col);\r\n    inline    void  PrimWriteVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col)    { _VtxWritePtr->pos = pos; _VtxWritePtr->uv = uv; _VtxWritePtr->col = col; _VtxWritePtr++; _VtxCurrentIdx++; }\r\n    inline    void  PrimWriteIdx(ImDrawIdx idx)                                     { *_IdxWritePtr = idx; _IdxWritePtr++; }\r\n    inline    void  PrimVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col)         { PrimWriteIdx((ImDrawIdx)_VtxCurrentIdx); PrimWriteVtx(pos, uv, col); } // Write vertex with unique index\r\n\r\n#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS\r\n    inline    void  AddBezierCurve(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness, int num_segments = 0) { AddBezierCubic(p1, p2, p3, p4, col, thickness, num_segments); } // OBSOLETED in 1.80 (Jan 2021)\r\n    inline    void  PathBezierCurveTo(const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, int num_segments = 0) { PathBezierCubicCurveTo(p2, p3, p4, num_segments); } // OBSOLETED in 1.80 (Jan 2021)\r\n#endif\r\n\r\n    // [Internal helpers]\r\n    IMGUI_API void  _ResetForNewFrame();\r\n    IMGUI_API void  _ClearFreeMemory();\r\n    IMGUI_API void  _PopUnusedDrawCmd();\r\n    IMGUI_API void  _TryMergeDrawCmds();\r\n    IMGUI_API void  _OnChangedClipRect();\r\n    IMGUI_API void  _OnChangedTextureID();\r\n    IMGUI_API void  _OnChangedVtxOffset();\r\n    IMGUI_API int   _CalcCircleAutoSegmentCount(float radius) const;\r\n    IMGUI_API void  _PathArcToFastEx(const ImVec2& center, float radius, int a_min_sample, int a_max_sample, int a_step);\r\n    IMGUI_API void  _PathArcToN(const ImVec2& center, float radius, float a_min, float a_max, int num_segments);\r\n};\r\n\r\n// All draw data to render a Dear ImGui frame\r\n// (NB: the style and the naming convention here is a little inconsistent, we currently preserve them for backward compatibility purpose,\r\n// as this is one of the oldest structure exposed by the library! Basically, ImDrawList == CmdList)\r\nstruct ImDrawData\r\n{\r\n    bool            Valid;                  // Only valid after Render() is called and before the next NewFrame() is called.\r\n    int             CmdListsCount;          // Number of ImDrawList* to render\r\n    int             TotalIdxCount;          // For convenience, sum of all ImDrawList's IdxBuffer.Size\r\n    int             TotalVtxCount;          // For convenience, sum of all ImDrawList's VtxBuffer.Size\r\n    ImDrawList**    CmdLists;               // Array of ImDrawList* to render. The ImDrawList are owned by ImGuiContext and only pointed to from here.\r\n    ImVec2          DisplayPos;             // Top-left position of the viewport to render (== top-left of the orthogonal projection matrix to use) (== GetMainViewport()->Pos for the main viewport, == (0.0) in most single-viewport applications)\r\n    ImVec2          DisplaySize;            // Size of the viewport to render (== GetMainViewport()->Size for the main viewport, == io.DisplaySize in most single-viewport applications)\r\n    ImVec2          FramebufferScale;       // Amount of pixels for each unit of DisplaySize. Based on io.DisplayFramebufferScale. Generally (1,1) on normal display, (2,2) on OSX with Retina display.\r\n\r\n    // Functions\r\n    ImDrawData()    { Clear(); }\r\n    void Clear()    { memset(this, 0, sizeof(*this)); }     // The ImDrawList are owned by ImGuiContext!\r\n    IMGUI_API void  DeIndexAllBuffers();                    // Helper to convert all buffers from indexed to non-indexed, in case you cannot render indexed. Note: this is slow and most likely a waste of resources. Always prefer indexed rendering!\r\n    IMGUI_API void  ScaleClipRects(const ImVec2& fb_scale); // Helper to scale the ClipRect field of each ImDrawCmd. Use if your final output buffer is at a different scale than Dear ImGui expects, or if there is a difference between your window resolution and framebuffer resolution.\r\n};\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontAtlasFlags, ImFontAtlas, ImFontGlyphRangesBuilder, ImFont)\r\n//-----------------------------------------------------------------------------\r\n\r\nstruct ImFontConfig\r\n{\r\n    void*           FontData;               //          // TTF/OTF data\r\n    int             FontDataSize;           //          // TTF/OTF data size\r\n    bool            FontDataOwnedByAtlas;   // true     // TTF/OTF data ownership taken by the container ImFontAtlas (will delete memory itself).\r\n    int             FontNo;                 // 0        // Index of font within TTF/OTF file\r\n    float           SizePixels;             //          // Size in pixels for rasterizer (more or less maps to the resulting font height).\r\n    int             OversampleH;            // 3        // Rasterize at higher quality for sub-pixel positioning. Note the difference between 2 and 3 is minimal so you can reduce this to 2 to save memory. Read https://github.com/nothings/stb/blob/master/tests/oversample/README.md for details.\r\n    int             OversampleV;            // 1        // Rasterize at higher quality for sub-pixel positioning. This is not really useful as we don't use sub-pixel positions on the Y axis.\r\n    bool            PixelSnapH;             // false    // Align every glyph to pixel boundary. Useful e.g. if you are merging a non-pixel aligned font with the default font. If enabled, you can set OversampleH/V to 1.\r\n    ImVec2          GlyphExtraSpacing;      // 0, 0     // Extra spacing (in pixels) between glyphs. Only X axis is supported for now.\r\n    ImVec2          GlyphOffset;            // 0, 0     // Offset all glyphs from this font input.\r\n    const ImWchar*  GlyphRanges;            // NULL     // Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE.\r\n    float           GlyphMinAdvanceX;       // 0        // Minimum AdvanceX for glyphs, set Min to align font icons, set both Min/Max to enforce mono-space font\r\n    float           GlyphMaxAdvanceX;       // FLT_MAX  // Maximum AdvanceX for glyphs\r\n    bool            MergeMode;              // false    // Merge into previous ImFont, so you can combine multiple inputs font into one ImFont (e.g. ASCII font + icons + Japanese glyphs). You may want to use GlyphOffset.y when merge font of different heights.\r\n    unsigned int    FontBuilderFlags;       // 0        // Settings for custom font builder. THIS IS BUILDER IMPLEMENTATION DEPENDENT. Leave as zero if unsure.\r\n    float           RasterizerMultiply;     // 1.0f     // Brighten (>1.0f) or darken (<1.0f) font output. Brightening small fonts may be a good workaround to make them more readable.\r\n    ImWchar         EllipsisChar;           // -1       // Explicitly specify unicode codepoint of ellipsis character. When fonts are being merged first specified ellipsis will be used.\r\n\r\n    // [Internal]\r\n    char            Name[40];               // Name (strictly to ease debugging)\r\n    ImFont*         DstFont;\r\n\r\n    IMGUI_API ImFontConfig();\r\n};\r\n\r\n// Hold rendering data for one glyph.\r\n// (Note: some language parsers may fail to convert the 31+1 bitfield members, in this case maybe drop store a single u32 or we can rework this)\r\nstruct ImFontGlyph\r\n{\r\n    unsigned int    Colored : 1;        // Flag to indicate glyph is colored and should generally ignore tinting (make it usable with no shift on little-endian as this is used in loops)\r\n    unsigned int    Visible : 1;        // Flag to indicate glyph has no visible pixels (e.g. space). Allow early out when rendering.\r\n    unsigned int    Codepoint : 30;     // 0x0000..0x10FFFF\r\n    float           AdvanceX;           // Distance to next character (= data from font + ImFontConfig::GlyphExtraSpacing.x baked in)\r\n    float           X0, Y0, X1, Y1;     // Glyph corners\r\n    float           U0, V0, U1, V1;     // Texture coordinates\r\n};\r\n\r\n// Helper to build glyph ranges from text/string data. Feed your application strings/characters to it then call BuildRanges().\r\n// This is essentially a tightly packed of vector of 64k booleans = 8KB storage.\r\nstruct ImFontGlyphRangesBuilder\r\n{\r\n    ImVector<ImU32> UsedChars;            // Store 1-bit per Unicode code point (0=unused, 1=used)\r\n\r\n    ImFontGlyphRangesBuilder()              { Clear(); }\r\n    inline void     Clear()                 { int size_in_bytes = (IM_UNICODE_CODEPOINT_MAX + 1) / 8; UsedChars.resize(size_in_bytes / (int)sizeof(ImU32)); memset(UsedChars.Data, 0, (size_t)size_in_bytes); }\r\n    inline bool     GetBit(size_t n) const  { int off = (int)(n >> 5); ImU32 mask = 1u << (n & 31); return (UsedChars[off] & mask) != 0; }  // Get bit n in the array\r\n    inline void     SetBit(size_t n)        { int off = (int)(n >> 5); ImU32 mask = 1u << (n & 31); UsedChars[off] |= mask; }               // Set bit n in the array\r\n    inline void     AddChar(ImWchar c)      { SetBit(c); }                      // Add character\r\n    IMGUI_API void  AddText(const char* text, const char* text_end = NULL);     // Add string (each character of the UTF-8 string are added)\r\n    IMGUI_API void  AddRanges(const ImWchar* ranges);                           // Add ranges, e.g. builder.AddRanges(ImFontAtlas::GetGlyphRangesDefault()) to force add all of ASCII/Latin+Ext\r\n    IMGUI_API void  BuildRanges(ImVector<ImWchar>* out_ranges);                 // Output new ranges\r\n};\r\n\r\n// See ImFontAtlas::AddCustomRectXXX functions.\r\nstruct ImFontAtlasCustomRect\r\n{\r\n    unsigned short  Width, Height;  // Input    // Desired rectangle dimension\r\n    unsigned short  X, Y;           // Output   // Packed position in Atlas\r\n    unsigned int    GlyphID;        // Input    // For custom font glyphs only (ID < 0x110000)\r\n    float           GlyphAdvanceX;  // Input    // For custom font glyphs only: glyph xadvance\r\n    ImVec2          GlyphOffset;    // Input    // For custom font glyphs only: glyph display offset\r\n    ImFont*         Font;           // Input    // For custom font glyphs only: target font\r\n    ImFontAtlasCustomRect()         { Width = Height = 0; X = Y = 0xFFFF; GlyphID = 0; GlyphAdvanceX = 0.0f; GlyphOffset = ImVec2(0, 0); Font = NULL; }\r\n    bool IsPacked() const           { return X != 0xFFFF; }\r\n};\r\n\r\n// Flags for ImFontAtlas build\r\nenum ImFontAtlasFlags_\r\n{\r\n    ImFontAtlasFlags_None               = 0,\r\n    ImFontAtlasFlags_NoPowerOfTwoHeight = 1 << 0,   // Don't round the height to next power of two\r\n    ImFontAtlasFlags_NoMouseCursors     = 1 << 1,   // Don't build software mouse cursors into the atlas (save a little texture memory)\r\n    ImFontAtlasFlags_NoBakedLines       = 1 << 2    // Don't build thick line textures into the atlas (save a little texture memory). The AntiAliasedLinesUseTex features uses them, otherwise they will be rendered using polygons (more expensive for CPU/GPU).\r\n};\r\n\r\n// Load and rasterize multiple TTF/OTF fonts into a same texture. The font atlas will build a single texture holding:\r\n//  - One or more fonts.\r\n//  - Custom graphics data needed to render the shapes needed by Dear ImGui.\r\n//  - Mouse cursor shapes for software cursor rendering (unless setting 'Flags |= ImFontAtlasFlags_NoMouseCursors' in the font atlas).\r\n// It is the user-code responsibility to setup/build the atlas, then upload the pixel data into a texture accessible by your graphics api.\r\n//  - Optionally, call any of the AddFont*** functions. If you don't call any, the default font embedded in the code will be loaded for you.\r\n//  - Call GetTexDataAsAlpha8() or GetTexDataAsRGBA32() to build and retrieve pixels data.\r\n//  - Upload the pixels data into a texture within your graphics system (see imgui_impl_xxxx.cpp examples)\r\n//  - Call SetTexID(my_tex_id); and pass the pointer/identifier to your texture in a format natural to your graphics API.\r\n//    This value will be passed back to you during rendering to identify the texture. Read FAQ entry about ImTextureID for more details.\r\n// Common pitfalls:\r\n// - If you pass a 'glyph_ranges' array to AddFont*** functions, you need to make sure that your array persist up until the\r\n//   atlas is build (when calling GetTexData*** or Build()). We only copy the pointer, not the data.\r\n// - Important: By default, AddFontFromMemoryTTF() takes ownership of the data. Even though we are not writing to it, we will free the pointer on destruction.\r\n//   You can set font_cfg->FontDataOwnedByAtlas=false to keep ownership of your data and it won't be freed,\r\n// - Even though many functions are suffixed with \"TTF\", OTF data is supported just as well.\r\n// - This is an old API and it is currently awkward for those and and various other reasons! We will address them in the future!\r\nstruct ImFontAtlas\r\n{\r\n    IMGUI_API ImFontAtlas();\r\n    IMGUI_API ~ImFontAtlas();\r\n    IMGUI_API ImFont*           AddFont(const ImFontConfig* font_cfg);\r\n    IMGUI_API ImFont*           AddFontDefault(const ImFontConfig* font_cfg = NULL);\r\n    IMGUI_API ImFont*           AddFontFromFileTTF(const char* filename, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL);\r\n    IMGUI_API ImFont*           AddFontFromMemoryTTF(void* font_data, int font_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // Note: Transfer ownership of 'ttf_data' to ImFontAtlas! Will be deleted after destruction of the atlas. Set font_cfg->FontDataOwnedByAtlas=false to keep ownership of your data and it won't be freed.\r\n    IMGUI_API ImFont*           AddFontFromMemoryCompressedTTF(const void* compressed_font_data, int compressed_font_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_font_data' still owned by caller. Compress with binary_to_compressed_c.cpp.\r\n    IMGUI_API ImFont*           AddFontFromMemoryCompressedBase85TTF(const char* compressed_font_data_base85, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL);              // 'compressed_font_data_base85' still owned by caller. Compress with binary_to_compressed_c.cpp with -base85 parameter.\r\n    IMGUI_API void              ClearInputData();           // Clear input data (all ImFontConfig structures including sizes, TTF data, glyph ranges, etc.) = all the data used to build the texture and fonts.\r\n    IMGUI_API void              ClearTexData();             // Clear output texture data (CPU side). Saves RAM once the texture has been copied to graphics memory.\r\n    IMGUI_API void              ClearFonts();               // Clear output font data (glyphs storage, UV coordinates).\r\n    IMGUI_API void              Clear();                    // Clear all input and output.\r\n\r\n    // Build atlas, retrieve pixel data.\r\n    // User is in charge of copying the pixels into graphics memory (e.g. create a texture with your engine). Then store your texture handle with SetTexID().\r\n    // The pitch is always = Width * BytesPerPixels (1 or 4)\r\n    // Building in RGBA32 format is provided for convenience and compatibility, but note that unless you manually manipulate or copy color data into\r\n    // the texture (e.g. when using the AddCustomRect*** api), then the RGB pixels emitted will always be white (~75% of memory/bandwidth waste.\r\n    IMGUI_API bool              Build();                    // Build pixels data. This is called automatically for you by the GetTexData*** functions.\r\n    IMGUI_API void              GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL);  // 1 byte per-pixel\r\n    IMGUI_API void              GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL);  // 4 bytes-per-pixel\r\n    bool                        IsBuilt() const             { return Fonts.Size > 0 && TexReady; } // Bit ambiguous: used to detect when user didn't built texture but effectively we should check TexID != 0 except that would be backend dependent...\r\n    void                        SetTexID(ImTextureID id)    { TexID = id; }\r\n\r\n    //-------------------------------------------\r\n    // Glyph Ranges\r\n    //-------------------------------------------\r\n\r\n    // Helpers to retrieve list of common Unicode ranges (2 value per range, values are inclusive, zero-terminated list)\r\n    // NB: Make sure that your string are UTF-8 and NOT in your local code page. In C++11, you can create UTF-8 string literal using the u8\"Hello world\" syntax. See FAQ for details.\r\n    // NB: Consider using ImFontGlyphRangesBuilder to build glyph ranges from textual data.\r\n    IMGUI_API const ImWchar*    GetGlyphRangesDefault();                // Basic Latin, Extended Latin\r\n    IMGUI_API const ImWchar*    GetGlyphRangesKorean();                 // Default + Korean characters\r\n    IMGUI_API const ImWchar*    GetGlyphRangesJapanese();               // Default + Hiragana, Katakana, Half-Width, Selection of 2999 Ideographs\r\n    IMGUI_API const ImWchar*    GetGlyphRangesChineseFull();            // Default + Half-Width + Japanese Hiragana/Katakana + full set of about 21000 CJK Unified Ideographs\r\n    IMGUI_API const ImWchar*    GetGlyphRangesChineseSimplifiedCommon();// Default + Half-Width + Japanese Hiragana/Katakana + set of 2500 CJK Unified Ideographs for common simplified Chinese\r\n    IMGUI_API const ImWchar*    GetGlyphRangesCyrillic();               // Default + about 400 Cyrillic characters\r\n    IMGUI_API const ImWchar*    GetGlyphRangesThai();                   // Default + Thai characters\r\n    IMGUI_API const ImWchar*    GetGlyphRangesVietnamese();             // Default + Vietnamese characters\r\n\r\n    //-------------------------------------------\r\n    // [BETA] Custom Rectangles/Glyphs API\r\n    //-------------------------------------------\r\n\r\n    // You can request arbitrary rectangles to be packed into the atlas, for your own purposes.\r\n    // - After calling Build(), you can query the rectangle position and render your pixels.\r\n    // - If you render colored output, set 'atlas->TexPixelsUseColors = true' as this may help some backends decide of prefered texture format.\r\n    // - You can also request your rectangles to be mapped as font glyph (given a font + Unicode point),\r\n    //   so you can render e.g. custom colorful icons and use them as regular glyphs.\r\n    // - Read docs/FONTS.md for more details about using colorful icons.\r\n    // - Note: this API may be redesigned later in order to support multi-monitor varying DPI settings.\r\n    IMGUI_API int               AddCustomRectRegular(int width, int height);\r\n    IMGUI_API int               AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0, 0));\r\n    ImFontAtlasCustomRect*      GetCustomRectByIndex(int index) { IM_ASSERT(index >= 0); return &CustomRects[index]; }\r\n\r\n    // [Internal]\r\n    IMGUI_API void              CalcCustomRectUV(const ImFontAtlasCustomRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max) const;\r\n    IMGUI_API bool              GetMouseCursorTexData(ImGuiMouseCursor cursor, ImVec2* out_offset, ImVec2* out_size, ImVec2 out_uv_border[2], ImVec2 out_uv_fill[2]);\r\n\r\n    //-------------------------------------------\r\n    // Members\r\n    //-------------------------------------------\r\n\r\n    ImFontAtlasFlags            Flags;              // Build flags (see ImFontAtlasFlags_)\r\n    ImTextureID                 TexID;              // User data to refer to the texture once it has been uploaded to user's graphic systems. It is passed back to you during rendering via the ImDrawCmd structure.\r\n    int                         TexDesiredWidth;    // Texture width desired by user before Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height.\r\n    int                         TexGlyphPadding;    // Padding between glyphs within texture in pixels. Defaults to 1. If your rendering method doesn't rely on bilinear filtering you may set this to 0.\r\n    bool                        Locked;             // Marked as Locked by ImGui::NewFrame() so attempt to modify the atlas will assert.\r\n\r\n    // [Internal]\r\n    // NB: Access texture data via GetTexData*() calls! Which will setup a default font for you.\r\n    bool                        TexReady;           // Set when texture was built matching current font input\r\n    bool                        TexPixelsUseColors; // Tell whether our texture data is known to use colors (rather than just alpha channel), in order to help backend select a format.\r\n    unsigned char*              TexPixelsAlpha8;    // 1 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight\r\n    unsigned int*               TexPixelsRGBA32;    // 4 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight * 4\r\n    int                         TexWidth;           // Texture width calculated during Build().\r\n    int                         TexHeight;          // Texture height calculated during Build().\r\n    ImVec2                      TexUvScale;         // = (1.0f/TexWidth, 1.0f/TexHeight)\r\n    ImVec2                      TexUvWhitePixel;    // Texture coordinates to a white pixel\r\n    ImVector<ImFont*>           Fonts;              // Hold all the fonts returned by AddFont*. Fonts[0] is the default font upon calling ImGui::NewFrame(), use ImGui::PushFont()/PopFont() to change the current font.\r\n    ImVector<ImFontAtlasCustomRect> CustomRects;    // Rectangles for packing custom texture data into the atlas.\r\n    ImVector<ImFontConfig>      ConfigData;         // Configuration data\r\n    ImVec4                      TexUvLines[IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1];  // UVs for baked anti-aliased lines\r\n\r\n    // [Internal] Font builder\r\n    const ImFontBuilderIO*      FontBuilderIO;      // Opaque interface to a font builder (default to stb_truetype, can be changed to use FreeType by defining IMGUI_ENABLE_FREETYPE).\r\n    unsigned int                FontBuilderFlags;   // Shared flags (for all fonts) for custom font builder. THIS IS BUILD IMPLEMENTATION DEPENDENT. Per-font override is also available in ImFontConfig.\r\n\r\n    // [Internal] Packing data\r\n    int                         PackIdMouseCursors; // Custom texture rectangle ID for white pixel and mouse cursors\r\n    int                         PackIdLines;        // Custom texture rectangle ID for baked anti-aliased lines\r\n\r\n    // [Obsolete]\r\n    //typedef ImFontAtlasCustomRect    CustomRect;         // OBSOLETED in 1.72+\r\n    //typedef ImFontGlyphRangesBuilder GlyphRangesBuilder; // OBSOLETED in 1.67+\r\n};\r\n\r\n// Font runtime data and rendering\r\n// ImFontAtlas automatically loads a default embedded font for you when you call GetTexDataAsAlpha8() or GetTexDataAsRGBA32().\r\nstruct ImFont\r\n{\r\n    // Members: Hot ~20/24 bytes (for CalcTextSize)\r\n    ImVector<float>             IndexAdvanceX;      // 12-16 // out //            // Sparse. Glyphs->AdvanceX in a directly indexable way (cache-friendly for CalcTextSize functions which only this this info, and are often bottleneck in large UI).\r\n    float                       FallbackAdvanceX;   // 4     // out // = FallbackGlyph->AdvanceX\r\n    float                       FontSize;           // 4     // in  //            // Height of characters/line, set during loading (don't change after loading)\r\n\r\n    // Members: Hot ~28/40 bytes (for CalcTextSize + render loop)\r\n    ImVector<ImWchar>           IndexLookup;        // 12-16 // out //            // Sparse. Index glyphs by Unicode code-point.\r\n    ImVector<ImFontGlyph>       Glyphs;             // 12-16 // out //            // All glyphs.\r\n    const ImFontGlyph*          FallbackGlyph;      // 4-8   // out // = FindGlyph(FontFallbackChar)\r\n\r\n    // Members: Cold ~32/40 bytes\r\n    ImFontAtlas*                ContainerAtlas;     // 4-8   // out //            // What we has been loaded into\r\n    const ImFontConfig*         ConfigData;         // 4-8   // in  //            // Pointer within ContainerAtlas->ConfigData\r\n    short                       ConfigDataCount;    // 2     // in  // ~ 1        // Number of ImFontConfig involved in creating this font. Bigger than 1 when merging multiple font sources into one ImFont.\r\n    ImWchar                     FallbackChar;       // 2     // out // = FFFD/'?' // Character used if a glyph isn't found.\r\n    ImWchar                     EllipsisChar;       // 2     // out // = '...'    // Character used for ellipsis rendering.\r\n    ImWchar                     DotChar;            // 2     // out // = '.'      // Character used for ellipsis rendering (if a single '...' character isn't found)\r\n    bool                        DirtyLookupTables;  // 1     // out //\r\n    float                       Scale;              // 4     // in  // = 1.f      // Base font scale, multiplied by the per-window font scale which you can adjust with SetWindowFontScale()\r\n    float                       Ascent, Descent;    // 4+4   // out //            // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize]\r\n    int                         MetricsTotalSurface;// 4     // out //            // Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding between glyphs)\r\n    ImU8                        Used4kPagesMap[(IM_UNICODE_CODEPOINT_MAX+1)/4096/8]; // 2 bytes if ImWchar=ImWchar16, 34 bytes if ImWchar==ImWchar32. Store 1-bit for each block of 4K codepoints that has one active glyph. This is mainly used to facilitate iterations across all used codepoints.\r\n\r\n    // Methods\r\n    IMGUI_API ImFont();\r\n    IMGUI_API ~ImFont();\r\n    IMGUI_API const ImFontGlyph*FindGlyph(ImWchar c) const;\r\n    IMGUI_API const ImFontGlyph*FindGlyphNoFallback(ImWchar c) const;\r\n    float                       GetCharAdvance(ImWchar c) const     { return ((int)c < IndexAdvanceX.Size) ? IndexAdvanceX[(int)c] : FallbackAdvanceX; }\r\n    bool                        IsLoaded() const                    { return ContainerAtlas != NULL; }\r\n    const char*                 GetDebugName() const                { return ConfigData ? ConfigData->Name : \"<unknown>\"; }\r\n\r\n    // 'max_width' stops rendering after a certain width (could be turned into a 2d size). FLT_MAX to disable.\r\n    // 'wrap_width' enable automatic word-wrapping across multiple lines to fit into given width. 0.0f to disable.\r\n    IMGUI_API ImVec2            CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end = NULL, const char** remaining = NULL) const; // utf8\r\n    IMGUI_API const char*       CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) const;\r\n    IMGUI_API void              RenderChar(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, ImWchar c) const;\r\n    IMGUI_API void              RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width = 0.0f, bool cpu_fine_clip = false) const;\r\n\r\n    // [Internal] Don't use!\r\n    IMGUI_API void              BuildLookupTable();\r\n    IMGUI_API void              ClearOutputData();\r\n    IMGUI_API void              GrowIndex(int new_size);\r\n    IMGUI_API void              AddGlyph(const ImFontConfig* src_cfg, ImWchar c, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1, float advance_x);\r\n    IMGUI_API void              AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst = true); // Makes 'dst' character/glyph points to 'src' character/glyph. Currently needs to be called AFTER fonts have been built.\r\n    IMGUI_API void              SetGlyphVisible(ImWchar c, bool visible);\r\n    IMGUI_API bool              IsGlyphRangeUnused(unsigned int c_begin, unsigned int c_last);\r\n};\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Viewports\r\n//-----------------------------------------------------------------------------\r\n\r\n// Flags stored in ImGuiViewport::Flags, giving indications to the platform backends.\r\nenum ImGuiViewportFlags_\r\n{\r\n    ImGuiViewportFlags_None                     = 0,\r\n    ImGuiViewportFlags_IsPlatformWindow         = 1 << 0,   // Represent a Platform Window\r\n    ImGuiViewportFlags_IsPlatformMonitor        = 1 << 1,   // Represent a Platform Monitor (unused yet)\r\n    ImGuiViewportFlags_OwnedByApp               = 1 << 2    // Platform Window: is created/managed by the application (rather than a dear imgui backend)\r\n};\r\n\r\n// - Currently represents the Platform Window created by the application which is hosting our Dear ImGui windows.\r\n// - In 'docking' branch with multi-viewport enabled, we extend this concept to have multiple active viewports.\r\n// - In the future we will extend this concept further to also represent Platform Monitor and support a \"no main platform window\" operation mode.\r\n// - About Main Area vs Work Area:\r\n//   - Main Area = entire viewport.\r\n//   - Work Area = entire viewport minus sections used by main menu bars (for platform windows), or by task bar (for platform monitor).\r\n//   - Windows are generally trying to stay within the Work Area of their host viewport.\r\nstruct ImGuiViewport\r\n{\r\n    ImGuiViewportFlags  Flags;                  // See ImGuiViewportFlags_\r\n    ImVec2              Pos;                    // Main Area: Position of the viewport (Dear ImGui coordinates are the same as OS desktop/native coordinates)\r\n    ImVec2              Size;                   // Main Area: Size of the viewport.\r\n    ImVec2              WorkPos;                // Work Area: Position of the viewport minus task bars, menus bars, status bars (>= Pos)\r\n    ImVec2              WorkSize;               // Work Area: Size of the viewport minus task bars, menu bars, status bars (<= Size)\r\n\r\n    // Platform/Backend Dependent Data\r\n    void*               PlatformHandleRaw;      // void* to hold lower-level, platform-native window handle (under Win32 this is expected to be a HWND, unused for other platforms)\r\n\r\n    ImGuiViewport()     { memset(this, 0, sizeof(*this)); }\r\n\r\n    // Helpers\r\n    ImVec2              GetCenter() const       { return ImVec2(Pos.x + Size.x * 0.5f, Pos.y + Size.y * 0.5f); }\r\n    ImVec2              GetWorkCenter() const   { return ImVec2(WorkPos.x + WorkSize.x * 0.5f, WorkPos.y + WorkSize.y * 0.5f); }\r\n};\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Platform Dependent Interfaces\r\n//-----------------------------------------------------------------------------\r\n\r\n// (Optional) Support for IME (Input Method Editor) via the io.SetPlatformImeDataFn() function.\r\nstruct ImGuiPlatformImeData\r\n{\r\n    bool    WantVisible;        // A widget wants the IME to be visible\r\n    ImVec2  InputPos;           // Position of the input cursor\r\n    float   InputLineHeight;    // Line height\r\n\r\n    ImGuiPlatformImeData() { memset(this, 0, sizeof(*this)); }\r\n};\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Obsolete functions and types\r\n// (Will be removed! Read 'API BREAKING CHANGES' section in imgui.cpp for details)\r\n// Please keep your copy of dear imgui up to date! Occasionally set '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in imconfig.h to stay ahead.\r\n//-----------------------------------------------------------------------------\r\n\r\nnamespace ImGui\r\n{\r\n#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO\r\n    IMGUI_API int       GetKeyIndex(ImGuiKey key);  // map ImGuiKey_* values into legacy native key index. == io.KeyMap[key]\r\n#else\r\n    static inline int   GetKeyIndex(ImGuiKey key)   { IM_ASSERT(key >= ImGuiKey_NamedKey_BEGIN && key < ImGuiKey_NamedKey_END && \"ImGuiKey and native_index was merged together and native_index is disabled by IMGUI_DISABLE_OBSOLETE_KEYIO. Please switch to ImGuiKey.\"); return key; }\r\n#endif\r\n}\r\n\r\n#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS\r\nnamespace ImGui\r\n{\r\n    // OBSOLETED in 1.86 (from November 2021)\r\n    IMGUI_API void      CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end); // Calculate coarse clipping for large list of evenly sized items. Prefer using ImGuiListClipper.\r\n    // OBSOLETED in 1.85 (from August 2021)\r\n    static inline float GetWindowContentRegionWidth() { return GetWindowContentRegionMax().x - GetWindowContentRegionMin().x; }\r\n    // OBSOLETED in 1.81 (from February 2021)\r\n    IMGUI_API bool      ListBoxHeader(const char* label, int items_count, int height_in_items = -1); // Helper to calculate size from items_count and height_in_items\r\n    static inline bool  ListBoxHeader(const char* label, const ImVec2& size = ImVec2(0, 0)) { return BeginListBox(label, size); }\r\n    static inline void  ListBoxFooter() { EndListBox(); }\r\n    // OBSOLETED in 1.79 (from August 2020)\r\n    static inline void  OpenPopupContextItem(const char* str_id = NULL, ImGuiMouseButton mb = 1) { OpenPopupOnItemClick(str_id, mb); } // Bool return value removed. Use IsWindowAppearing() in BeginPopup() instead. Renamed in 1.77, renamed back in 1.79. Sorry!\r\n    // OBSOLETED in 1.78 (from June 2020)\r\n    // Old drag/sliders functions that took a 'float power = 1.0' argument instead of flags.\r\n    // For shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`.\r\n    IMGUI_API bool      DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, float power);\r\n    IMGUI_API bool      DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, float power);\r\n    static inline bool  DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, float power)    { return DragScalar(label, ImGuiDataType_Float, v, v_speed, &v_min, &v_max, format, power); }\r\n    static inline bool  DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, float power) { return DragScalarN(label, ImGuiDataType_Float, v, 2, v_speed, &v_min, &v_max, format, power); }\r\n    static inline bool  DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, float power) { return DragScalarN(label, ImGuiDataType_Float, v, 3, v_speed, &v_min, &v_max, format, power); }\r\n    static inline bool  DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, float power) { return DragScalarN(label, ImGuiDataType_Float, v, 4, v_speed, &v_min, &v_max, format, power); }\r\n    IMGUI_API bool      SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power);\r\n    IMGUI_API bool      SliderScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_min, const void* p_max, const char* format, float power);\r\n    static inline bool  SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, float power)                 { return SliderScalar(label, ImGuiDataType_Float, v, &v_min, &v_max, format, power); }\r\n    static inline bool  SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, float power)              { return SliderScalarN(label, ImGuiDataType_Float, v, 2, &v_min, &v_max, format, power); }\r\n    static inline bool  SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, float power)              { return SliderScalarN(label, ImGuiDataType_Float, v, 3, &v_min, &v_max, format, power); }\r\n    static inline bool  SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, float power)              { return SliderScalarN(label, ImGuiDataType_Float, v, 4, &v_min, &v_max, format, power); }\r\n    // OBSOLETED in 1.77 (from June 2020)\r\n    static inline bool  BeginPopupContextWindow(const char* str_id, ImGuiMouseButton mb, bool over_items) { return BeginPopupContextWindow(str_id, mb | (over_items ? 0 : ImGuiPopupFlags_NoOpenOverItems)); }\r\n\r\n    // Some of the older obsolete names along with their replacement (commented out so they are not reported in IDE)\r\n    //static inline void  TreeAdvanceToLabelPos()               { SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()); }   // OBSOLETED in 1.72 (from July 2019)\r\n    //static inline void  SetNextTreeNodeOpen(bool open, ImGuiCond cond = 0) { SetNextItemOpen(open, cond); }                       // OBSOLETED in 1.71 (from June 2019)\r\n    //static inline float GetContentRegionAvailWidth()          { return GetContentRegionAvail().x; }                               // OBSOLETED in 1.70 (from May 2019)\r\n    //static inline ImDrawList* GetOverlayDrawList()            { return GetForegroundDrawList(); }                                 // OBSOLETED in 1.69 (from Mar 2019)\r\n    //static inline void  SetScrollHere(float ratio = 0.5f)     { SetScrollHereY(ratio); }                                          // OBSOLETED in 1.66 (from Nov 2018)\r\n    //static inline bool  IsItemDeactivatedAfterChange()        { return IsItemDeactivatedAfterEdit(); }                            // OBSOLETED in 1.63 (from Aug 2018)\r\n    //static inline bool  IsAnyWindowFocused()                  { return IsWindowFocused(ImGuiFocusedFlags_AnyWindow); }            // OBSOLETED in 1.60 (from Apr 2018)\r\n    //static inline bool  IsAnyWindowHovered()                  { return IsWindowHovered(ImGuiHoveredFlags_AnyWindow); }            // OBSOLETED in 1.60 (between Dec 2017 and Apr 2018)\r\n    //static inline void  ShowTestWindow()                      { return ShowDemoWindow(); }                                        // OBSOLETED in 1.53 (between Oct 2017 and Dec 2017)\r\n    //static inline bool  IsRootWindowFocused()                 { return IsWindowFocused(ImGuiFocusedFlags_RootWindow); }           // OBSOLETED in 1.53 (between Oct 2017 and Dec 2017)\r\n    //static inline bool  IsRootWindowOrAnyChildFocused()       { return IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows); }  // OBSOLETED in 1.53 (between Oct 2017 and Dec 2017)\r\n    //static inline void  SetNextWindowContentWidth(float w)    { SetNextWindowContentSize(ImVec2(w, 0.0f)); }                      // OBSOLETED in 1.53 (between Oct 2017 and Dec 2017)\r\n    //static inline float GetItemsLineHeightWithSpacing()       { return GetFrameHeightWithSpacing(); }                             // OBSOLETED in 1.53 (between Oct 2017 and Dec 2017)\r\n}\r\n\r\n// OBSOLETED in 1.82 (from Mars 2021): flags for AddRect(), AddRectFilled(), AddImageRounded(), PathRect()\r\ntypedef ImDrawFlags ImDrawCornerFlags;\r\nenum ImDrawCornerFlags_\r\n{\r\n    ImDrawCornerFlags_None      = ImDrawFlags_RoundCornersNone,         // Was == 0 prior to 1.82, this is now == ImDrawFlags_RoundCornersNone which is != 0 and not implicit\r\n    ImDrawCornerFlags_TopLeft   = ImDrawFlags_RoundCornersTopLeft,      // Was == 0x01 (1 << 0) prior to 1.82. Order matches ImDrawFlags_NoRoundCorner* flag (we exploit this internally).\r\n    ImDrawCornerFlags_TopRight  = ImDrawFlags_RoundCornersTopRight,     // Was == 0x02 (1 << 1) prior to 1.82.\r\n    ImDrawCornerFlags_BotLeft   = ImDrawFlags_RoundCornersBottomLeft,   // Was == 0x04 (1 << 2) prior to 1.82.\r\n    ImDrawCornerFlags_BotRight  = ImDrawFlags_RoundCornersBottomRight,  // Was == 0x08 (1 << 3) prior to 1.82.\r\n    ImDrawCornerFlags_All       = ImDrawFlags_RoundCornersAll,          // Was == 0x0F prior to 1.82\r\n    ImDrawCornerFlags_Top       = ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_TopRight,\r\n    ImDrawCornerFlags_Bot       = ImDrawCornerFlags_BotLeft | ImDrawCornerFlags_BotRight,\r\n    ImDrawCornerFlags_Left      = ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_BotLeft,\r\n    ImDrawCornerFlags_Right     = ImDrawCornerFlags_TopRight | ImDrawCornerFlags_BotRight\r\n};\r\n\r\n#endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS\r\n\r\n//-----------------------------------------------------------------------------\r\n\r\n#if defined(__clang__)\r\n#pragma clang diagnostic pop\r\n#elif defined(__GNUC__)\r\n#pragma GCC diagnostic pop\r\n#endif\r\n\r\n#ifdef _MSC_VER\r\n#pragma warning (pop)\r\n#endif\r\n\r\n// Include imgui_user.h at the end of imgui.h (convenient for user to only explicitly include vanilla imgui.h)\r\n#ifdef IMGUI_INCLUDE_IMGUI_USER_H\r\n#include \"imgui_user.h\"\r\n#endif\r\n\r\n#endif // #ifndef IMGUI_DISABLE\r\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/imgui/imgui_demo.cpp",
    "content": "// dear imgui, v1.87 WIP\r\n// (demo code)\r\n\r\n// Help:\r\n// - Read FAQ at http://dearimgui.org/faq\r\n// - Newcomers, read 'Programmer guide' in imgui.cpp for notes on how to setup Dear ImGui in your codebase.\r\n// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that.\r\n// Read imgui.cpp for more details, documentation and comments.\r\n// Get the latest version at https://github.com/ocornut/imgui\r\n\r\n// Message to the person tempted to delete this file when integrating Dear ImGui into their codebase:\r\n// Do NOT remove this file from your project! Think again! It is the most useful reference code that you and other\r\n// coders will want to refer to and call. Have the ImGui::ShowDemoWindow() function wired in an always-available\r\n// debug menu of your game/app! Removing this file from your project is hindering access to documentation for everyone\r\n// in your team, likely leading you to poorer usage of the library.\r\n// Everything in this file will be stripped out by the linker if you don't call ImGui::ShowDemoWindow().\r\n// If you want to link core Dear ImGui in your shipped builds but want a thorough guarantee that the demo will not be\r\n// linked, you can setup your imconfig.h with #define IMGUI_DISABLE_DEMO_WINDOWS and those functions will be empty.\r\n// In another situation, whenever you have Dear ImGui available you probably want this to be available for reference.\r\n// Thank you,\r\n// -Your beloved friend, imgui_demo.cpp (which you won't delete)\r\n\r\n// Message to beginner C/C++ programmers about the meaning of the 'static' keyword:\r\n// In this demo code, we frequently use 'static' variables inside functions. A static variable persists across calls,\r\n// so it is essentially like a global variable but declared inside the scope of the function. We do this as a way to\r\n// gather code and data in the same place, to make the demo source code faster to read, faster to write, and smaller\r\n// in size. It also happens to be a convenient way of storing simple UI related information as long as your function\r\n// doesn't need to be reentrant or used in multiple threads. This might be a pattern you will want to use in your code,\r\n// but most of the real data you would be editing is likely going to be stored outside your functions.\r\n\r\n// The Demo code in this file is designed to be easy to copy-and-paste into your application!\r\n// Because of this:\r\n// - We never omit the ImGui:: prefix when calling functions, even though most code here is in the same namespace.\r\n// - We try to declare static variables in the local scope, as close as possible to the code using them.\r\n// - We never use any of the helpers/facilities used internally by Dear ImGui, unless available in the public API.\r\n// - We never use maths operators on ImVec2/ImVec4. For our other sources files we use them, and they are provided\r\n//   by imgui_internal.h using the IMGUI_DEFINE_MATH_OPERATORS define. For your own sources file they are optional\r\n//   and require you either enable those, either provide your own via IM_VEC2_CLASS_EXTRA in imconfig.h.\r\n//   Because we can't assume anything about your support of maths operators, we cannot use them in imgui_demo.cpp.\r\n\r\n// Navigating this file:\r\n// - In Visual Studio IDE: CTRL+comma (\"Edit.NavigateTo\") can follow symbols in comments, whereas CTRL+F12 (\"Edit.GoToImplementation\") cannot.\r\n// - With Visual Assist installed: ALT+G (\"VAssistX.GoToImplementation\") can also follow symbols in comments.\r\n\r\n/*\r\n\r\nIndex of this file:\r\n\r\n// [SECTION] Forward Declarations, Helpers\r\n// [SECTION] Demo Window / ShowDemoWindow()\r\n// - sub section: ShowDemoWindowWidgets()\r\n// - sub section: ShowDemoWindowLayout()\r\n// - sub section: ShowDemoWindowPopups()\r\n// - sub section: ShowDemoWindowTables()\r\n// - sub section: ShowDemoWindowMisc()\r\n// [SECTION] About Window / ShowAboutWindow()\r\n// [SECTION] Style Editor / ShowStyleEditor()\r\n// [SECTION] Example App: Main Menu Bar / ShowExampleAppMainMenuBar()\r\n// [SECTION] Example App: Debug Console / ShowExampleAppConsole()\r\n// [SECTION] Example App: Debug Log / ShowExampleAppLog()\r\n// [SECTION] Example App: Simple Layout / ShowExampleAppLayout()\r\n// [SECTION] Example App: Property Editor / ShowExampleAppPropertyEditor()\r\n// [SECTION] Example App: Long Text / ShowExampleAppLongText()\r\n// [SECTION] Example App: Auto Resize / ShowExampleAppAutoResize()\r\n// [SECTION] Example App: Constrained Resize / ShowExampleAppConstrainedResize()\r\n// [SECTION] Example App: Simple overlay / ShowExampleAppSimpleOverlay()\r\n// [SECTION] Example App: Fullscreen window / ShowExampleAppFullscreen()\r\n// [SECTION] Example App: Manipulating window titles / ShowExampleAppWindowTitles()\r\n// [SECTION] Example App: Custom Rendering using ImDrawList API / ShowExampleAppCustomRendering()\r\n// [SECTION] Example App: Documents Handling / ShowExampleAppDocuments()\r\n\r\n*/\r\n\r\n#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)\r\n#define _CRT_SECURE_NO_WARNINGS\r\n#endif\r\n\r\n#include \"imgui.h\"\r\n#ifndef IMGUI_DISABLE\r\n\r\n// System includes\r\n#include <ctype.h>          // toupper\r\n#include <limits.h>         // INT_MIN, INT_MAX\r\n#include <math.h>           // sqrtf, powf, cosf, sinf, floorf, ceilf\r\n#include <stdio.h>          // vsnprintf, sscanf, printf\r\n#include <stdlib.h>         // NULL, malloc, free, atoi\r\n#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier\r\n#include <stddef.h>         // intptr_t\r\n#else\r\n#include <stdint.h>         // intptr_t\r\n#endif\r\n\r\n// Visual Studio warnings\r\n#ifdef _MSC_VER\r\n#pragma warning (disable: 4127)     // condition expression is constant\r\n#pragma warning (disable: 4996)     // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen\r\n#pragma warning (disable: 26451)    // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to a 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2).\r\n#endif\r\n\r\n// Clang/GCC warnings with -Weverything\r\n#if defined(__clang__)\r\n#if __has_warning(\"-Wunknown-warning-option\")\r\n#pragma clang diagnostic ignored \"-Wunknown-warning-option\"         // warning: unknown warning group 'xxx'                     // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great!\r\n#endif\r\n#pragma clang diagnostic ignored \"-Wunknown-pragmas\"                // warning: unknown warning group 'xxx'\r\n#pragma clang diagnostic ignored \"-Wold-style-cast\"                 // warning: use of old-style cast                           // yes, they are more terse.\r\n#pragma clang diagnostic ignored \"-Wdeprecated-declarations\"        // warning: 'xx' is deprecated: The POSIX name for this..   // for strdup used in demo code (so user can copy & paste the code)\r\n#pragma clang diagnostic ignored \"-Wint-to-void-pointer-cast\"       // warning: cast to 'void *' from smaller integer type\r\n#pragma clang diagnostic ignored \"-Wformat-security\"                // warning: format string is not a string literal\r\n#pragma clang diagnostic ignored \"-Wexit-time-destructors\"          // warning: declaration requires an exit-time destructor    // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals.\r\n#pragma clang diagnostic ignored \"-Wunused-macros\"                  // warning: macro is not used                               // we define snprintf/vsnprintf on Windows so they are available, but not always used.\r\n#pragma clang diagnostic ignored \"-Wzero-as-null-pointer-constant\"  // warning: zero as null pointer constant                   // some standard header variations use #define NULL 0\r\n#pragma clang diagnostic ignored \"-Wdouble-promotion\"               // warning: implicit conversion from 'float' to 'double' when passing argument to function  // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.\r\n#pragma clang diagnostic ignored \"-Wreserved-id-macro\"              // warning: macro name is a reserved identifier\r\n#pragma clang diagnostic ignored \"-Wimplicit-int-float-conversion\"  // warning: implicit conversion from 'xxx' to 'float' may lose precision\r\n#elif defined(__GNUC__)\r\n#pragma GCC diagnostic ignored \"-Wpragmas\"                  // warning: unknown option after '#pragma GCC diagnostic' kind\r\n#pragma GCC diagnostic ignored \"-Wint-to-pointer-cast\"      // warning: cast to pointer from integer of different size\r\n#pragma GCC diagnostic ignored \"-Wformat-security\"          // warning: format string is not a string literal (potentially insecure)\r\n#pragma GCC diagnostic ignored \"-Wdouble-promotion\"         // warning: implicit conversion from 'float' to 'double' when passing argument to function\r\n#pragma GCC diagnostic ignored \"-Wconversion\"               // warning: conversion to 'xxxx' from 'xxxx' may alter its value\r\n#pragma GCC diagnostic ignored \"-Wmisleading-indentation\"   // [__GNUC__ >= 6] warning: this 'if' clause does not guard this statement      // GCC 6.0+ only. See #883 on GitHub.\r\n#endif\r\n\r\n// Play it nice with Windows users (Update: May 2018, Notepad now supports Unix-style carriage returns!)\r\n#ifdef _WIN32\r\n#define IM_NEWLINE  \"\\r\\n\"\r\n#else\r\n#define IM_NEWLINE  \"\\n\"\r\n#endif\r\n\r\n// Helpers\r\n#if defined(_MSC_VER) && !defined(snprintf)\r\n#define snprintf    _snprintf\r\n#endif\r\n#if defined(_MSC_VER) && !defined(vsnprintf)\r\n#define vsnprintf   _vsnprintf\r\n#endif\r\n\r\n// Format specifiers, printing 64-bit hasn't been decently standardized...\r\n// In a real application you should be using PRId64 and PRIu64 from <inttypes.h> (non-windows) and on Windows define them yourself.\r\n#ifdef _MSC_VER\r\n#define IM_PRId64   \"I64d\"\r\n#define IM_PRIu64   \"I64u\"\r\n#else\r\n#define IM_PRId64   \"lld\"\r\n#define IM_PRIu64   \"llu\"\r\n#endif\r\n\r\n// Helpers macros\r\n// We normally try to not use many helpers in imgui_demo.cpp in order to make code easier to copy and paste,\r\n// but making an exception here as those are largely simplifying code...\r\n// In other imgui sources we can use nicer internal functions from imgui_internal.h (ImMin/ImMax) but not in the demo.\r\n#define IM_MIN(A, B)            (((A) < (B)) ? (A) : (B))\r\n#define IM_MAX(A, B)            (((A) >= (B)) ? (A) : (B))\r\n#define IM_CLAMP(V, MN, MX)     ((V) < (MN) ? (MN) : (V) > (MX) ? (MX) : (V))\r\n\r\n// Enforce cdecl calling convention for functions called by the standard library, in case compilation settings changed the default to e.g. __vectorcall\r\n#ifndef IMGUI_CDECL\r\n#ifdef _MSC_VER\r\n#define IMGUI_CDECL __cdecl\r\n#else\r\n#define IMGUI_CDECL\r\n#endif\r\n#endif\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Forward Declarations, Helpers\r\n//-----------------------------------------------------------------------------\r\n\r\n#if !defined(IMGUI_DISABLE_DEMO_WINDOWS)\r\n\r\n// Forward Declarations\r\nstatic void ShowExampleAppDocuments(bool* p_open);\r\nstatic void ShowExampleAppMainMenuBar();\r\nstatic void ShowExampleAppConsole(bool* p_open);\r\nstatic void ShowExampleAppLog(bool* p_open);\r\nstatic void ShowExampleAppLayout(bool* p_open);\r\nstatic void ShowExampleAppPropertyEditor(bool* p_open);\r\nstatic void ShowExampleAppLongText(bool* p_open);\r\nstatic void ShowExampleAppAutoResize(bool* p_open);\r\nstatic void ShowExampleAppConstrainedResize(bool* p_open);\r\nstatic void ShowExampleAppSimpleOverlay(bool* p_open);\r\nstatic void ShowExampleAppFullscreen(bool* p_open);\r\nstatic void ShowExampleAppWindowTitles(bool* p_open);\r\nstatic void ShowExampleAppCustomRendering(bool* p_open);\r\nstatic void ShowExampleMenuFile();\r\n\r\n// Helper to display a little (?) mark which shows a tooltip when hovered.\r\n// In your own code you may want to display an actual icon if you are using a merged icon fonts (see docs/FONTS.md)\r\nstatic void HelpMarker(const char* desc)\r\n{\r\n    ImGui::TextDisabled(\"(?)\");\r\n    if (ImGui::IsItemHovered())\r\n    {\r\n        ImGui::BeginTooltip();\r\n        ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);\r\n        ImGui::TextUnformatted(desc);\r\n        ImGui::PopTextWrapPos();\r\n        ImGui::EndTooltip();\r\n    }\r\n}\r\n\r\n// Helper to wire demo markers located in code to a interactive browser\r\ntypedef void (*ImGuiDemoMarkerCallback)(const char* file, int line, const char* section, void* user_data);\r\nextern ImGuiDemoMarkerCallback  GImGuiDemoMarkerCallback;\r\nextern void*                    GImGuiDemoMarkerCallbackUserData;\r\nImGuiDemoMarkerCallback         GImGuiDemoMarkerCallback = NULL;\r\nvoid*                           GImGuiDemoMarkerCallbackUserData = NULL;\r\n#define IMGUI_DEMO_MARKER(section)  do { if (GImGuiDemoMarkerCallback != NULL) GImGuiDemoMarkerCallback(__FILE__, __LINE__, section, GImGuiDemoMarkerCallbackUserData); } while (0)\r\n\r\n// Helper to display basic user controls.\r\nvoid ImGui::ShowUserGuide()\r\n{\r\n    ImGuiIO& io = ImGui::GetIO();\r\n    ImGui::BulletText(\"Double-click on title bar to collapse window.\");\r\n    ImGui::BulletText(\r\n        \"Click and drag on lower corner to resize window\\n\"\r\n        \"(double-click to auto fit window to its contents).\");\r\n    ImGui::BulletText(\"CTRL+Click on a slider or drag box to input value as text.\");\r\n    ImGui::BulletText(\"TAB/SHIFT+TAB to cycle through keyboard editable fields.\");\r\n\tImGui::BulletText(\"CTRL+Tab to select a window.\");\r\n\tif (io.FontAllowUserScaling)\r\n        ImGui::BulletText(\"CTRL+Mouse Wheel to zoom window contents.\");\r\n    ImGui::BulletText(\"While inputing text:\\n\");\r\n    ImGui::Indent();\r\n    ImGui::BulletText(\"CTRL+Left/Right to word jump.\");\r\n    ImGui::BulletText(\"CTRL+A or double-click to select all.\");\r\n    ImGui::BulletText(\"CTRL+X/C/V to use clipboard cut/copy/paste.\");\r\n    ImGui::BulletText(\"CTRL+Z,CTRL+Y to undo/redo.\");\r\n    ImGui::BulletText(\"ESCAPE to revert.\");\r\n    ImGui::Unindent();\r\n    ImGui::BulletText(\"With keyboard navigation enabled:\");\r\n    ImGui::Indent();\r\n    ImGui::BulletText(\"Arrow keys to navigate.\");\r\n    ImGui::BulletText(\"Space to activate a widget.\");\r\n    ImGui::BulletText(\"Return to input text into a widget.\");\r\n    ImGui::BulletText(\"Escape to deactivate a widget, close popup, exit child window.\");\r\n    ImGui::BulletText(\"Alt to jump to the menu layer of a window.\");\r\n    ImGui::Unindent();\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Demo Window / ShowDemoWindow()\r\n//-----------------------------------------------------------------------------\r\n// - ShowDemoWindowWidgets()\r\n// - ShowDemoWindowLayout()\r\n// - ShowDemoWindowPopups()\r\n// - ShowDemoWindowTables()\r\n// - ShowDemoWindowColumns()\r\n// - ShowDemoWindowMisc()\r\n//-----------------------------------------------------------------------------\r\n\r\n// We split the contents of the big ShowDemoWindow() function into smaller functions\r\n// (because the link time of very large functions grow non-linearly)\r\nstatic void ShowDemoWindowWidgets();\r\nstatic void ShowDemoWindowLayout();\r\nstatic void ShowDemoWindowPopups();\r\nstatic void ShowDemoWindowTables();\r\nstatic void ShowDemoWindowColumns();\r\nstatic void ShowDemoWindowMisc();\r\n\r\n// Demonstrate most Dear ImGui features (this is big function!)\r\n// You may execute this function to experiment with the UI and understand what it does.\r\n// You may then search for keywords in the code when you are interested by a specific feature.\r\nvoid ImGui::ShowDemoWindow(bool* p_open)\r\n{\r\n    // Exceptionally add an extra assert here for people confused about initial Dear ImGui setup\r\n    // Most ImGui functions would normally just crash if the context is missing.\r\n    IM_ASSERT(ImGui::GetCurrentContext() != NULL && \"Missing dear imgui context. Refer to examples app!\");\r\n\r\n    // Examples Apps (accessible from the \"Examples\" menu)\r\n    static bool show_app_main_menu_bar = false;\r\n    static bool show_app_documents = false;\r\n\r\n    static bool show_app_console = false;\r\n    static bool show_app_log = false;\r\n    static bool show_app_layout = false;\r\n    static bool show_app_property_editor = false;\r\n    static bool show_app_long_text = false;\r\n    static bool show_app_auto_resize = false;\r\n    static bool show_app_constrained_resize = false;\r\n    static bool show_app_simple_overlay = false;\r\n    static bool show_app_fullscreen = false;\r\n    static bool show_app_window_titles = false;\r\n    static bool show_app_custom_rendering = false;\r\n\r\n    if (show_app_main_menu_bar)       ShowExampleAppMainMenuBar();\r\n    if (show_app_documents)           ShowExampleAppDocuments(&show_app_documents);\r\n\r\n    if (show_app_console)             ShowExampleAppConsole(&show_app_console);\r\n    if (show_app_log)                 ShowExampleAppLog(&show_app_log);\r\n    if (show_app_layout)              ShowExampleAppLayout(&show_app_layout);\r\n    if (show_app_property_editor)     ShowExampleAppPropertyEditor(&show_app_property_editor);\r\n    if (show_app_long_text)           ShowExampleAppLongText(&show_app_long_text);\r\n    if (show_app_auto_resize)         ShowExampleAppAutoResize(&show_app_auto_resize);\r\n    if (show_app_constrained_resize)  ShowExampleAppConstrainedResize(&show_app_constrained_resize);\r\n    if (show_app_simple_overlay)      ShowExampleAppSimpleOverlay(&show_app_simple_overlay);\r\n    if (show_app_fullscreen)          ShowExampleAppFullscreen(&show_app_fullscreen);\r\n    if (show_app_window_titles)       ShowExampleAppWindowTitles(&show_app_window_titles);\r\n    if (show_app_custom_rendering)    ShowExampleAppCustomRendering(&show_app_custom_rendering);\r\n\r\n    // Dear ImGui Apps (accessible from the \"Tools\" menu)\r\n    static bool show_app_metrics = false;\r\n    static bool show_app_stack_tool = false;\r\n    static bool show_app_style_editor = false;\r\n    static bool show_app_about = false;\r\n\r\n    if (show_app_metrics)       { ImGui::ShowMetricsWindow(&show_app_metrics); }\r\n    if (show_app_stack_tool)    { ImGui::ShowStackToolWindow(&show_app_stack_tool); }\r\n    if (show_app_about)         { ImGui::ShowAboutWindow(&show_app_about); }\r\n    if (show_app_style_editor)\r\n    {\r\n        ImGui::Begin(\"Dear ImGui Style Editor\", &show_app_style_editor);\r\n        ImGui::ShowStyleEditor();\r\n        ImGui::End();\r\n    }\r\n\r\n    // Demonstrate the various window flags. Typically you would just use the default!\r\n    static bool no_titlebar = false;\r\n    static bool no_scrollbar = false;\r\n    static bool no_menu = false;\r\n    static bool no_move = false;\r\n    static bool no_resize = false;\r\n    static bool no_collapse = false;\r\n    static bool no_close = false;\r\n    static bool no_nav = false;\r\n    static bool no_background = false;\r\n    static bool no_bring_to_front = false;\r\n    static bool unsaved_document = false;\r\n\r\n    ImGuiWindowFlags window_flags = 0;\r\n    if (no_titlebar)        window_flags |= ImGuiWindowFlags_NoTitleBar;\r\n    if (no_scrollbar)       window_flags |= ImGuiWindowFlags_NoScrollbar;\r\n    if (!no_menu)           window_flags |= ImGuiWindowFlags_MenuBar;\r\n    if (no_move)            window_flags |= ImGuiWindowFlags_NoMove;\r\n    if (no_resize)          window_flags |= ImGuiWindowFlags_NoResize;\r\n    if (no_collapse)        window_flags |= ImGuiWindowFlags_NoCollapse;\r\n    if (no_nav)             window_flags |= ImGuiWindowFlags_NoNav;\r\n    if (no_background)      window_flags |= ImGuiWindowFlags_NoBackground;\r\n    if (no_bring_to_front)  window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus;\r\n    if (unsaved_document)   window_flags |= ImGuiWindowFlags_UnsavedDocument;\r\n    if (no_close)           p_open = NULL; // Don't pass our bool* to Begin\r\n\r\n    // We specify a default position/size in case there's no data in the .ini file.\r\n    // We only do it to make the demo applications a little more welcoming, but typically this isn't required.\r\n    const ImGuiViewport* main_viewport = ImGui::GetMainViewport();\r\n    ImGui::SetNextWindowPos(ImVec2(main_viewport->WorkPos.x + 650, main_viewport->WorkPos.y + 20), ImGuiCond_FirstUseEver);\r\n    ImGui::SetNextWindowSize(ImVec2(550, 680), ImGuiCond_FirstUseEver);\r\n\r\n    // Main body of the Demo window starts here.\r\n    if (!ImGui::Begin(\"Dear ImGui Demo\", p_open, window_flags))\r\n    {\r\n        // Early out if the window is collapsed, as an optimization.\r\n        ImGui::End();\r\n        return;\r\n    }\r\n\r\n    // Most \"big\" widgets share a common width settings by default. See 'Demo->Layout->Widgets Width' for details.\r\n\r\n    // e.g. Use 2/3 of the space for widgets and 1/3 for labels (right align)\r\n    //ImGui::PushItemWidth(-ImGui::GetWindowWidth() * 0.35f);\r\n\r\n    // e.g. Leave a fixed amount of width for labels (by passing a negative value), the rest goes to widgets.\r\n    ImGui::PushItemWidth(ImGui::GetFontSize() * -12);\r\n\r\n    // Menu Bar\r\n    if (ImGui::BeginMenuBar())\r\n    {\r\n        if (ImGui::BeginMenu(\"Menu\"))\r\n        {\r\n            IMGUI_DEMO_MARKER(\"Menu/File\");\r\n            ShowExampleMenuFile();\r\n            ImGui::EndMenu();\r\n        }\r\n        if (ImGui::BeginMenu(\"Examples\"))\r\n        {\r\n            IMGUI_DEMO_MARKER(\"Menu/Examples\");\r\n            ImGui::MenuItem(\"Main menu bar\", NULL, &show_app_main_menu_bar);\r\n            ImGui::MenuItem(\"Console\", NULL, &show_app_console);\r\n            ImGui::MenuItem(\"Log\", NULL, &show_app_log);\r\n            ImGui::MenuItem(\"Simple layout\", NULL, &show_app_layout);\r\n            ImGui::MenuItem(\"Property editor\", NULL, &show_app_property_editor);\r\n            ImGui::MenuItem(\"Long text display\", NULL, &show_app_long_text);\r\n            ImGui::MenuItem(\"Auto-resizing window\", NULL, &show_app_auto_resize);\r\n            ImGui::MenuItem(\"Constrained-resizing window\", NULL, &show_app_constrained_resize);\r\n            ImGui::MenuItem(\"Simple overlay\", NULL, &show_app_simple_overlay);\r\n            ImGui::MenuItem(\"Fullscreen window\", NULL, &show_app_fullscreen);\r\n            ImGui::MenuItem(\"Manipulating window titles\", NULL, &show_app_window_titles);\r\n            ImGui::MenuItem(\"Custom rendering\", NULL, &show_app_custom_rendering);\r\n            ImGui::MenuItem(\"Documents\", NULL, &show_app_documents);\r\n            ImGui::EndMenu();\r\n        }\r\n        //if (ImGui::MenuItem(\"MenuItem\")) {} // You can also use MenuItem() inside a menu bar!\r\n        if (ImGui::BeginMenu(\"Tools\"))\r\n        {\r\n            IMGUI_DEMO_MARKER(\"Menu/Tools\");\r\n#ifndef IMGUI_DISABLE_METRICS_WINDOW\r\n            ImGui::MenuItem(\"Metrics/Debugger\", NULL, &show_app_metrics);\r\n            ImGui::MenuItem(\"Stack Tool\", NULL, &show_app_stack_tool);\r\n#endif\r\n            ImGui::MenuItem(\"Style Editor\", NULL, &show_app_style_editor);\r\n            ImGui::MenuItem(\"About Dear ImGui\", NULL, &show_app_about);\r\n            ImGui::EndMenu();\r\n        }\r\n        ImGui::EndMenuBar();\r\n    }\r\n\r\n    ImGui::Text(\"dear imgui says hello. (%s)\", IMGUI_VERSION);\r\n    ImGui::Spacing();\r\n\r\n    IMGUI_DEMO_MARKER(\"Help\");\r\n    if (ImGui::CollapsingHeader(\"Help\"))\r\n    {\r\n        ImGui::Text(\"ABOUT THIS DEMO:\");\r\n        ImGui::BulletText(\"Sections below are demonstrating many aspects of the library.\");\r\n        ImGui::BulletText(\"The \\\"Examples\\\" menu above leads to more demo contents.\");\r\n        ImGui::BulletText(\"The \\\"Tools\\\" menu above gives access to: About Box, Style Editor,\\n\"\r\n                          \"and Metrics/Debugger (general purpose Dear ImGui debugging tool).\");\r\n        ImGui::Separator();\r\n\r\n        ImGui::Text(\"PROGRAMMER GUIDE:\");\r\n        ImGui::BulletText(\"See the ShowDemoWindow() code in imgui_demo.cpp. <- you are here!\");\r\n        ImGui::BulletText(\"See comments in imgui.cpp.\");\r\n        ImGui::BulletText(\"See example applications in the examples/ folder.\");\r\n        ImGui::BulletText(\"Read the FAQ at http://www.dearimgui.org/faq/\");\r\n        ImGui::BulletText(\"Set 'io.ConfigFlags |= NavEnableKeyboard' for keyboard controls.\");\r\n        ImGui::BulletText(\"Set 'io.ConfigFlags |= NavEnableGamepad' for gamepad controls.\");\r\n        ImGui::Separator();\r\n\r\n        ImGui::Text(\"USER GUIDE:\");\r\n        ImGui::ShowUserGuide();\r\n    }\r\n\r\n    IMGUI_DEMO_MARKER(\"Configuration\");\r\n    if (ImGui::CollapsingHeader(\"Configuration\"))\r\n    {\r\n        ImGuiIO& io = ImGui::GetIO();\r\n\r\n        if (ImGui::TreeNode(\"Configuration##2\"))\r\n        {\r\n            ImGui::CheckboxFlags(\"io.ConfigFlags: NavEnableKeyboard\",    &io.ConfigFlags, ImGuiConfigFlags_NavEnableKeyboard);\r\n            ImGui::SameLine(); HelpMarker(\"Enable keyboard controls.\");\r\n            ImGui::CheckboxFlags(\"io.ConfigFlags: NavEnableGamepad\",     &io.ConfigFlags, ImGuiConfigFlags_NavEnableGamepad);\r\n            ImGui::SameLine(); HelpMarker(\"Enable gamepad controls. Require backend to set io.BackendFlags |= ImGuiBackendFlags_HasGamepad.\\n\\nRead instructions in imgui.cpp for details.\");\r\n            ImGui::CheckboxFlags(\"io.ConfigFlags: NavEnableSetMousePos\", &io.ConfigFlags, ImGuiConfigFlags_NavEnableSetMousePos);\r\n            ImGui::SameLine(); HelpMarker(\"Instruct navigation to move the mouse cursor. See comment for ImGuiConfigFlags_NavEnableSetMousePos.\");\r\n            ImGui::CheckboxFlags(\"io.ConfigFlags: NoMouse\",              &io.ConfigFlags, ImGuiConfigFlags_NoMouse);\r\n            if (io.ConfigFlags & ImGuiConfigFlags_NoMouse)\r\n            {\r\n                // The \"NoMouse\" option can get us stuck with a disabled mouse! Let's provide an alternative way to fix it:\r\n                if (fmodf((float)ImGui::GetTime(), 0.40f) < 0.20f)\r\n                {\r\n                    ImGui::SameLine();\r\n                    ImGui::Text(\"<<PRESS SPACE TO DISABLE>>\");\r\n                }\r\n                if (ImGui::IsKeyPressed(ImGuiKey_Space))\r\n                    io.ConfigFlags &= ~ImGuiConfigFlags_NoMouse;\r\n            }\r\n            ImGui::CheckboxFlags(\"io.ConfigFlags: NoMouseCursorChange\", &io.ConfigFlags, ImGuiConfigFlags_NoMouseCursorChange);\r\n            ImGui::SameLine(); HelpMarker(\"Instruct backend to not alter mouse cursor shape and visibility.\");\r\n            ImGui::Checkbox(\"io.ConfigInputTrickleEventQueue\", &io.ConfigInputTrickleEventQueue);\r\n            ImGui::SameLine(); HelpMarker(\"Enable input queue trickling: some types of events submitted during the same frame (e.g. button down + up) will be spread over multiple frames, improving interactions with low framerates.\");\r\n            ImGui::Checkbox(\"io.ConfigInputTextCursorBlink\", &io.ConfigInputTextCursorBlink);\r\n            ImGui::SameLine(); HelpMarker(\"Enable blinking cursor (optional as some users consider it to be distracting).\");\r\n            ImGui::Checkbox(\"io.ConfigDragClickToInputText\", &io.ConfigDragClickToInputText);\r\n            ImGui::SameLine(); HelpMarker(\"Enable turning DragXXX widgets into text input with a simple mouse click-release (without moving).\");\r\n            ImGui::Checkbox(\"io.ConfigWindowsResizeFromEdges\", &io.ConfigWindowsResizeFromEdges);\r\n            ImGui::SameLine(); HelpMarker(\"Enable resizing of windows from their edges and from the lower-left corner.\\nThis requires (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) because it needs mouse cursor feedback.\");\r\n            ImGui::Checkbox(\"io.ConfigWindowsMoveFromTitleBarOnly\", &io.ConfigWindowsMoveFromTitleBarOnly);\r\n            ImGui::Checkbox(\"io.MouseDrawCursor\", &io.MouseDrawCursor);\r\n            ImGui::SameLine(); HelpMarker(\"Instruct Dear ImGui to render a mouse cursor itself. Note that a mouse cursor rendered via your application GPU rendering path will feel more laggy than hardware cursor, but will be more in sync with your other visuals.\\n\\nSome desktop applications may use both kinds of cursors (e.g. enable software cursor only when resizing/dragging something).\");\r\n            ImGui::Text(\"Also see Style->Rendering for rendering options.\");\r\n            ImGui::TreePop();\r\n            ImGui::Separator();\r\n        }\r\n\r\n        IMGUI_DEMO_MARKER(\"Configuration/Backend Flags\");\r\n        if (ImGui::TreeNode(\"Backend Flags\"))\r\n        {\r\n            HelpMarker(\r\n                \"Those flags are set by the backends (imgui_impl_xxx files) to specify their capabilities.\\n\"\r\n                \"Here we expose them as read-only fields to avoid breaking interactions with your backend.\");\r\n\r\n            // Make a local copy to avoid modifying actual backend flags.\r\n            // FIXME: We don't use BeginDisabled() to keep label bright, maybe we need a BeginReadonly() equivalent..\r\n            ImGuiBackendFlags backend_flags = io.BackendFlags;\r\n            ImGui::CheckboxFlags(\"io.BackendFlags: HasGamepad\",           &backend_flags, ImGuiBackendFlags_HasGamepad);\r\n            ImGui::CheckboxFlags(\"io.BackendFlags: HasMouseCursors\",      &backend_flags, ImGuiBackendFlags_HasMouseCursors);\r\n            ImGui::CheckboxFlags(\"io.BackendFlags: HasSetMousePos\",       &backend_flags, ImGuiBackendFlags_HasSetMousePos);\r\n            ImGui::CheckboxFlags(\"io.BackendFlags: RendererHasVtxOffset\", &backend_flags, ImGuiBackendFlags_RendererHasVtxOffset);\r\n            ImGui::TreePop();\r\n            ImGui::Separator();\r\n        }\r\n\r\n        IMGUI_DEMO_MARKER(\"Configuration/Style\");\r\n        if (ImGui::TreeNode(\"Style\"))\r\n        {\r\n            HelpMarker(\"The same contents can be accessed in 'Tools->Style Editor' or by calling the ShowStyleEditor() function.\");\r\n            ImGui::ShowStyleEditor();\r\n            ImGui::TreePop();\r\n            ImGui::Separator();\r\n        }\r\n\r\n        IMGUI_DEMO_MARKER(\"Configuration/Capture, Logging\");\r\n        if (ImGui::TreeNode(\"Capture/Logging\"))\r\n        {\r\n            HelpMarker(\r\n                \"The logging API redirects all text output so you can easily capture the content of \"\r\n                \"a window or a block. Tree nodes can be automatically expanded.\\n\"\r\n                \"Try opening any of the contents below in this window and then click one of the \\\"Log To\\\" button.\");\r\n            ImGui::LogButtons();\r\n\r\n            HelpMarker(\"You can also call ImGui::LogText() to output directly to the log without a visual output.\");\r\n            if (ImGui::Button(\"Copy \\\"Hello, world!\\\" to clipboard\"))\r\n            {\r\n                ImGui::LogToClipboard();\r\n                ImGui::LogText(\"Hello, world!\");\r\n                ImGui::LogFinish();\r\n            }\r\n            ImGui::TreePop();\r\n        }\r\n    }\r\n\r\n    IMGUI_DEMO_MARKER(\"Window options\");\r\n    if (ImGui::CollapsingHeader(\"Window options\"))\r\n    {\r\n        if (ImGui::BeginTable(\"split\", 3))\r\n        {\r\n            ImGui::TableNextColumn(); ImGui::Checkbox(\"No titlebar\", &no_titlebar);\r\n            ImGui::TableNextColumn(); ImGui::Checkbox(\"No scrollbar\", &no_scrollbar);\r\n            ImGui::TableNextColumn(); ImGui::Checkbox(\"No menu\", &no_menu);\r\n            ImGui::TableNextColumn(); ImGui::Checkbox(\"No move\", &no_move);\r\n            ImGui::TableNextColumn(); ImGui::Checkbox(\"No resize\", &no_resize);\r\n            ImGui::TableNextColumn(); ImGui::Checkbox(\"No collapse\", &no_collapse);\r\n            ImGui::TableNextColumn(); ImGui::Checkbox(\"No close\", &no_close);\r\n            ImGui::TableNextColumn(); ImGui::Checkbox(\"No nav\", &no_nav);\r\n            ImGui::TableNextColumn(); ImGui::Checkbox(\"No background\", &no_background);\r\n            ImGui::TableNextColumn(); ImGui::Checkbox(\"No bring to front\", &no_bring_to_front);\r\n            ImGui::TableNextColumn(); ImGui::Checkbox(\"Unsaved document\", &unsaved_document);\r\n            ImGui::EndTable();\r\n        }\r\n    }\r\n\r\n    // All demo contents\r\n    ShowDemoWindowWidgets();\r\n    ShowDemoWindowLayout();\r\n    ShowDemoWindowPopups();\r\n    ShowDemoWindowTables();\r\n    ShowDemoWindowMisc();\r\n\r\n    // End of ShowDemoWindow()\r\n    ImGui::PopItemWidth();\r\n    ImGui::End();\r\n}\r\n\r\nstatic void ShowDemoWindowWidgets()\r\n{\r\n    IMGUI_DEMO_MARKER(\"Widgets\");\r\n    if (!ImGui::CollapsingHeader(\"Widgets\"))\r\n        return;\r\n\r\n    static bool disable_all = false; // The Checkbox for that is inside the \"Disabled\" section at the bottom\r\n    if (disable_all)\r\n        ImGui::BeginDisabled();\r\n\r\n    IMGUI_DEMO_MARKER(\"Widgets/Basic\");\r\n    if (ImGui::TreeNode(\"Basic\"))\r\n    {\r\n        IMGUI_DEMO_MARKER(\"Widgets/Basic/Button\");\r\n        static int clicked = 0;\r\n        if (ImGui::Button(\"Button\"))\r\n            clicked++;\r\n        if (clicked & 1)\r\n        {\r\n            ImGui::SameLine();\r\n            ImGui::Text(\"Thanks for clicking me!\");\r\n        }\r\n\r\n        IMGUI_DEMO_MARKER(\"Widgets/Basic/Checkbox\");\r\n        static bool check = true;\r\n        ImGui::Checkbox(\"checkbox\", &check);\r\n\r\n        IMGUI_DEMO_MARKER(\"Widgets/Basic/RadioButton\");\r\n        static int e = 0;\r\n        ImGui::RadioButton(\"radio a\", &e, 0); ImGui::SameLine();\r\n        ImGui::RadioButton(\"radio b\", &e, 1); ImGui::SameLine();\r\n        ImGui::RadioButton(\"radio c\", &e, 2);\r\n\r\n        // Color buttons, demonstrate using PushID() to add unique identifier in the ID stack, and changing style.\r\n        IMGUI_DEMO_MARKER(\"Widgets/Basic/Buttons (Colored)\");\r\n        for (int i = 0; i < 7; i++)\r\n        {\r\n            if (i > 0)\r\n                ImGui::SameLine();\r\n            ImGui::PushID(i);\r\n            ImGui::PushStyleColor(ImGuiCol_Button, (ImVec4)ImColor::HSV(i / 7.0f, 0.6f, 0.6f));\r\n            ImGui::PushStyleColor(ImGuiCol_ButtonHovered, (ImVec4)ImColor::HSV(i / 7.0f, 0.7f, 0.7f));\r\n            ImGui::PushStyleColor(ImGuiCol_ButtonActive, (ImVec4)ImColor::HSV(i / 7.0f, 0.8f, 0.8f));\r\n            ImGui::Button(\"Click\");\r\n            ImGui::PopStyleColor(3);\r\n            ImGui::PopID();\r\n        }\r\n\r\n        // Use AlignTextToFramePadding() to align text baseline to the baseline of framed widgets elements\r\n        // (otherwise a Text+SameLine+Button sequence will have the text a little too high by default!)\r\n        // See 'Demo->Layout->Text Baseline Alignment' for details.\r\n        ImGui::AlignTextToFramePadding();\r\n        ImGui::Text(\"Hold to repeat:\");\r\n        ImGui::SameLine();\r\n\r\n        // Arrow buttons with Repeater\r\n        IMGUI_DEMO_MARKER(\"Widgets/Basic/Buttons (Repeating)\");\r\n        static int counter = 0;\r\n        float spacing = ImGui::GetStyle().ItemInnerSpacing.x;\r\n        ImGui::PushButtonRepeat(true);\r\n        if (ImGui::ArrowButton(\"##left\", ImGuiDir_Left)) { counter--; }\r\n        ImGui::SameLine(0.0f, spacing);\r\n        if (ImGui::ArrowButton(\"##right\", ImGuiDir_Right)) { counter++; }\r\n        ImGui::PopButtonRepeat();\r\n        ImGui::SameLine();\r\n        ImGui::Text(\"%d\", counter);\r\n\r\n        IMGUI_DEMO_MARKER(\"Widgets/Basic/Tooltips\");\r\n        ImGui::Text(\"Hover over me\");\r\n        if (ImGui::IsItemHovered())\r\n            ImGui::SetTooltip(\"I am a tooltip\");\r\n\r\n        ImGui::SameLine();\r\n        ImGui::Text(\"- or me\");\r\n        if (ImGui::IsItemHovered())\r\n        {\r\n            ImGui::BeginTooltip();\r\n            ImGui::Text(\"I am a fancy tooltip\");\r\n            static float arr[] = { 0.6f, 0.1f, 1.0f, 0.5f, 0.92f, 0.1f, 0.2f };\r\n            ImGui::PlotLines(\"Curve\", arr, IM_ARRAYSIZE(arr));\r\n            ImGui::EndTooltip();\r\n        }\r\n\r\n        ImGui::Separator();\r\n        ImGui::LabelText(\"label\", \"Value\");\r\n\r\n        {\r\n            // Using the _simplified_ one-liner Combo() api here\r\n            // See \"Combo\" section for examples of how to use the more flexible BeginCombo()/EndCombo() api.\r\n            IMGUI_DEMO_MARKER(\"Widgets/Basic/Combo\");\r\n            const char* items[] = { \"AAAA\", \"BBBB\", \"CCCC\", \"DDDD\", \"EEEE\", \"FFFF\", \"GGGG\", \"HHHH\", \"IIIIIII\", \"JJJJ\", \"KKKKKKK\" };\r\n            static int item_current = 0;\r\n            ImGui::Combo(\"combo\", &item_current, items, IM_ARRAYSIZE(items));\r\n            ImGui::SameLine(); HelpMarker(\r\n                \"Using the simplified one-liner Combo API here.\\nRefer to the \\\"Combo\\\" section below for an explanation of how to use the more flexible and general BeginCombo/EndCombo API.\");\r\n        }\r\n\r\n        {\r\n            // To wire InputText() with std::string or any other custom string type,\r\n            // see the \"Text Input > Resize Callback\" section of this demo, and the misc/cpp/imgui_stdlib.h file.\r\n            IMGUI_DEMO_MARKER(\"Widgets/Basic/InputText\");\r\n            static char str0[128] = \"Hello, world!\";\r\n            ImGui::InputText(\"input text\", str0, IM_ARRAYSIZE(str0));\r\n            ImGui::SameLine(); HelpMarker(\r\n                \"USER:\\n\"\r\n                \"Hold SHIFT or use mouse to select text.\\n\"\r\n                \"CTRL+Left/Right to word jump.\\n\"\r\n                \"CTRL+A or double-click to select all.\\n\"\r\n                \"CTRL+X,CTRL+C,CTRL+V clipboard.\\n\"\r\n                \"CTRL+Z,CTRL+Y undo/redo.\\n\"\r\n                \"ESCAPE to revert.\\n\\n\"\r\n                \"PROGRAMMER:\\n\"\r\n                \"You can use the ImGuiInputTextFlags_CallbackResize facility if you need to wire InputText() \"\r\n                \"to a dynamic string type. See misc/cpp/imgui_stdlib.h for an example (this is not demonstrated \"\r\n                \"in imgui_demo.cpp).\");\r\n\r\n            static char str1[128] = \"\";\r\n            ImGui::InputTextWithHint(\"input text (w/ hint)\", \"enter text here\", str1, IM_ARRAYSIZE(str1));\r\n\r\n            IMGUI_DEMO_MARKER(\"Widgets/Basic/InputInt, InputFloat\");\r\n            static int i0 = 123;\r\n            ImGui::InputInt(\"input int\", &i0);\r\n\r\n            static float f0 = 0.001f;\r\n            ImGui::InputFloat(\"input float\", &f0, 0.01f, 1.0f, \"%.3f\");\r\n\r\n            static double d0 = 999999.00000001;\r\n            ImGui::InputDouble(\"input double\", &d0, 0.01f, 1.0f, \"%.8f\");\r\n\r\n            static float f1 = 1.e10f;\r\n            ImGui::InputFloat(\"input scientific\", &f1, 0.0f, 0.0f, \"%e\");\r\n            ImGui::SameLine(); HelpMarker(\r\n                \"You can input value using the scientific notation,\\n\"\r\n                \"  e.g. \\\"1e+8\\\" becomes \\\"100000000\\\".\");\r\n\r\n            static float vec4a[4] = { 0.10f, 0.20f, 0.30f, 0.44f };\r\n            ImGui::InputFloat3(\"input float3\", vec4a);\r\n        }\r\n\r\n        {\r\n            IMGUI_DEMO_MARKER(\"Widgets/Basic/DragInt, DragFloat\");\r\n            static int i1 = 50, i2 = 42;\r\n            ImGui::DragInt(\"drag int\", &i1, 1);\r\n            ImGui::SameLine(); HelpMarker(\r\n                \"Click and drag to edit value.\\n\"\r\n                \"Hold SHIFT/ALT for faster/slower edit.\\n\"\r\n                \"Double-click or CTRL+click to input value.\");\r\n\r\n            ImGui::DragInt(\"drag int 0..100\", &i2, 1, 0, 100, \"%d%%\", ImGuiSliderFlags_AlwaysClamp);\r\n\r\n            static float f1 = 1.00f, f2 = 0.0067f;\r\n            ImGui::DragFloat(\"drag float\", &f1, 0.005f);\r\n            ImGui::DragFloat(\"drag small float\", &f2, 0.0001f, 0.0f, 0.0f, \"%.06f ns\");\r\n        }\r\n\r\n        {\r\n            IMGUI_DEMO_MARKER(\"Widgets/Basic/SliderInt, SliderFloat\");\r\n            static int i1 = 0;\r\n            ImGui::SliderInt(\"slider int\", &i1, -1, 3);\r\n            ImGui::SameLine(); HelpMarker(\"CTRL+click to input value.\");\r\n\r\n            static float f1 = 0.123f, f2 = 0.0f;\r\n            ImGui::SliderFloat(\"slider float\", &f1, 0.0f, 1.0f, \"ratio = %.3f\");\r\n            ImGui::SliderFloat(\"slider float (log)\", &f2, -10.0f, 10.0f, \"%.4f\", ImGuiSliderFlags_Logarithmic);\r\n\r\n            IMGUI_DEMO_MARKER(\"Widgets/Basic/SliderAngle\");\r\n            static float angle = 0.0f;\r\n            ImGui::SliderAngle(\"slider angle\", &angle);\r\n\r\n            // Using the format string to display a name instead of an integer.\r\n            // Here we completely omit '%d' from the format string, so it'll only display a name.\r\n            // This technique can also be used with DragInt().\r\n            IMGUI_DEMO_MARKER(\"Widgets/Basic/Slider (enum)\");\r\n            enum Element { Element_Fire, Element_Earth, Element_Air, Element_Water, Element_COUNT };\r\n            static int elem = Element_Fire;\r\n            const char* elems_names[Element_COUNT] = { \"Fire\", \"Earth\", \"Air\", \"Water\" };\r\n            const char* elem_name = (elem >= 0 && elem < Element_COUNT) ? elems_names[elem] : \"Unknown\";\r\n            ImGui::SliderInt(\"slider enum\", &elem, 0, Element_COUNT - 1, elem_name);\r\n            ImGui::SameLine(); HelpMarker(\"Using the format string parameter to display a name instead of the underlying integer.\");\r\n        }\r\n\r\n        {\r\n            IMGUI_DEMO_MARKER(\"Widgets/Basic/ColorEdit3, ColorEdit4\");\r\n            static float col1[3] = { 1.0f, 0.0f, 0.2f };\r\n            static float col2[4] = { 0.4f, 0.7f, 0.0f, 0.5f };\r\n            ImGui::ColorEdit3(\"color 1\", col1);\r\n            ImGui::SameLine(); HelpMarker(\r\n                \"Click on the color square to open a color picker.\\n\"\r\n                \"Click and hold to use drag and drop.\\n\"\r\n                \"Right-click on the color square to show options.\\n\"\r\n                \"CTRL+click on individual component to input value.\\n\");\r\n\r\n            ImGui::ColorEdit4(\"color 2\", col2);\r\n        }\r\n\r\n        {\r\n            // Using the _simplified_ one-liner ListBox() api here\r\n            // See \"List boxes\" section for examples of how to use the more flexible BeginListBox()/EndListBox() api.\r\n            IMGUI_DEMO_MARKER(\"Widgets/Basic/ListBox\");\r\n            const char* items[] = { \"Apple\", \"Banana\", \"Cherry\", \"Kiwi\", \"Mango\", \"Orange\", \"Pineapple\", \"Strawberry\", \"Watermelon\" };\r\n            static int item_current = 1;\r\n            ImGui::ListBox(\"listbox\", &item_current, items, IM_ARRAYSIZE(items), 4);\r\n            ImGui::SameLine(); HelpMarker(\r\n                \"Using the simplified one-liner ListBox API here.\\nRefer to the \\\"List boxes\\\" section below for an explanation of how to use the more flexible and general BeginListBox/EndListBox API.\");\r\n        }\r\n\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    // Testing ImGuiOnceUponAFrame helper.\r\n    //static ImGuiOnceUponAFrame once;\r\n    //for (int i = 0; i < 5; i++)\r\n    //    if (once)\r\n    //        ImGui::Text(\"This will be displayed only once.\");\r\n\r\n    IMGUI_DEMO_MARKER(\"Widgets/Trees\");\r\n    if (ImGui::TreeNode(\"Trees\"))\r\n    {\r\n        IMGUI_DEMO_MARKER(\"Widgets/Trees/Basic trees\");\r\n        if (ImGui::TreeNode(\"Basic trees\"))\r\n        {\r\n            for (int i = 0; i < 5; i++)\r\n            {\r\n                // Use SetNextItemOpen() so set the default state of a node to be open. We could\r\n                // also use TreeNodeEx() with the ImGuiTreeNodeFlags_DefaultOpen flag to achieve the same thing!\r\n                if (i == 0)\r\n                    ImGui::SetNextItemOpen(true, ImGuiCond_Once);\r\n\r\n                if (ImGui::TreeNode((void*)(intptr_t)i, \"Child %d\", i))\r\n                {\r\n                    ImGui::Text(\"blah blah\");\r\n                    ImGui::SameLine();\r\n                    if (ImGui::SmallButton(\"button\")) {}\r\n                    ImGui::TreePop();\r\n                }\r\n            }\r\n            ImGui::TreePop();\r\n        }\r\n\r\n        IMGUI_DEMO_MARKER(\"Widgets/Trees/Advanced, with Selectable nodes\");\r\n        if (ImGui::TreeNode(\"Advanced, with Selectable nodes\"))\r\n        {\r\n            HelpMarker(\r\n                \"This is a more typical looking tree with selectable nodes.\\n\"\r\n                \"Click to select, CTRL+Click to toggle, click on arrows or double-click to open.\");\r\n            static ImGuiTreeNodeFlags base_flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_SpanAvailWidth;\r\n            static bool align_label_with_current_x_position = false;\r\n            static bool test_drag_and_drop = false;\r\n            ImGui::CheckboxFlags(\"ImGuiTreeNodeFlags_OpenOnArrow\",       &base_flags, ImGuiTreeNodeFlags_OpenOnArrow);\r\n            ImGui::CheckboxFlags(\"ImGuiTreeNodeFlags_OpenOnDoubleClick\", &base_flags, ImGuiTreeNodeFlags_OpenOnDoubleClick);\r\n            ImGui::CheckboxFlags(\"ImGuiTreeNodeFlags_SpanAvailWidth\",    &base_flags, ImGuiTreeNodeFlags_SpanAvailWidth); ImGui::SameLine(); HelpMarker(\"Extend hit area to all available width instead of allowing more items to be laid out after the node.\");\r\n            ImGui::CheckboxFlags(\"ImGuiTreeNodeFlags_SpanFullWidth\",     &base_flags, ImGuiTreeNodeFlags_SpanFullWidth);\r\n            ImGui::Checkbox(\"Align label with current X position\", &align_label_with_current_x_position);\r\n            ImGui::Checkbox(\"Test tree node as drag source\", &test_drag_and_drop);\r\n            ImGui::Text(\"Hello!\");\r\n            if (align_label_with_current_x_position)\r\n                ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing());\r\n\r\n            // 'selection_mask' is dumb representation of what may be user-side selection state.\r\n            //  You may retain selection state inside or outside your objects in whatever format you see fit.\r\n            // 'node_clicked' is temporary storage of what node we have clicked to process selection at the end\r\n            /// of the loop. May be a pointer to your own node type, etc.\r\n            static int selection_mask = (1 << 2);\r\n            int node_clicked = -1;\r\n            for (int i = 0; i < 6; i++)\r\n            {\r\n                // Disable the default \"open on single-click behavior\" + set Selected flag according to our selection.\r\n                // To alter selection we use IsItemClicked() && !IsItemToggledOpen(), so clicking on an arrow doesn't alter selection.\r\n                ImGuiTreeNodeFlags node_flags = base_flags;\r\n                const bool is_selected = (selection_mask & (1 << i)) != 0;\r\n                if (is_selected)\r\n                    node_flags |= ImGuiTreeNodeFlags_Selected;\r\n                if (i < 3)\r\n                {\r\n                    // Items 0..2 are Tree Node\r\n                    bool node_open = ImGui::TreeNodeEx((void*)(intptr_t)i, node_flags, \"Selectable Node %d\", i);\r\n                    if (ImGui::IsItemClicked() && !ImGui::IsItemToggledOpen())\r\n                        node_clicked = i;\r\n                    if (test_drag_and_drop && ImGui::BeginDragDropSource())\r\n                    {\r\n                        ImGui::SetDragDropPayload(\"_TREENODE\", NULL, 0);\r\n                        ImGui::Text(\"This is a drag and drop source\");\r\n                        ImGui::EndDragDropSource();\r\n                    }\r\n                    if (node_open)\r\n                    {\r\n                        ImGui::BulletText(\"Blah blah\\nBlah Blah\");\r\n                        ImGui::TreePop();\r\n                    }\r\n                }\r\n                else\r\n                {\r\n                    // Items 3..5 are Tree Leaves\r\n                    // The only reason we use TreeNode at all is to allow selection of the leaf. Otherwise we can\r\n                    // use BulletText() or advance the cursor by GetTreeNodeToLabelSpacing() and call Text().\r\n                    node_flags |= ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen; // ImGuiTreeNodeFlags_Bullet\r\n                    ImGui::TreeNodeEx((void*)(intptr_t)i, node_flags, \"Selectable Leaf %d\", i);\r\n                    if (ImGui::IsItemClicked() && !ImGui::IsItemToggledOpen())\r\n                        node_clicked = i;\r\n                    if (test_drag_and_drop && ImGui::BeginDragDropSource())\r\n                    {\r\n                        ImGui::SetDragDropPayload(\"_TREENODE\", NULL, 0);\r\n                        ImGui::Text(\"This is a drag and drop source\");\r\n                        ImGui::EndDragDropSource();\r\n                    }\r\n                }\r\n            }\r\n            if (node_clicked != -1)\r\n            {\r\n                // Update selection state\r\n                // (process outside of tree loop to avoid visual inconsistencies during the clicking frame)\r\n                if (ImGui::GetIO().KeyCtrl)\r\n                    selection_mask ^= (1 << node_clicked);          // CTRL+click to toggle\r\n                else //if (!(selection_mask & (1 << node_clicked))) // Depending on selection behavior you want, may want to preserve selection when clicking on item that is part of the selection\r\n                    selection_mask = (1 << node_clicked);           // Click to single-select\r\n            }\r\n            if (align_label_with_current_x_position)\r\n                ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing());\r\n            ImGui::TreePop();\r\n        }\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    IMGUI_DEMO_MARKER(\"Widgets/Collapsing Headers\");\r\n    if (ImGui::TreeNode(\"Collapsing Headers\"))\r\n    {\r\n        static bool closable_group = true;\r\n        ImGui::Checkbox(\"Show 2nd header\", &closable_group);\r\n        if (ImGui::CollapsingHeader(\"Header\", ImGuiTreeNodeFlags_None))\r\n        {\r\n            ImGui::Text(\"IsItemHovered: %d\", ImGui::IsItemHovered());\r\n            for (int i = 0; i < 5; i++)\r\n                ImGui::Text(\"Some content %d\", i);\r\n        }\r\n        if (ImGui::CollapsingHeader(\"Header with a close button\", &closable_group))\r\n        {\r\n            ImGui::Text(\"IsItemHovered: %d\", ImGui::IsItemHovered());\r\n            for (int i = 0; i < 5; i++)\r\n                ImGui::Text(\"More content %d\", i);\r\n        }\r\n        /*\r\n        if (ImGui::CollapsingHeader(\"Header with a bullet\", ImGuiTreeNodeFlags_Bullet))\r\n            ImGui::Text(\"IsItemHovered: %d\", ImGui::IsItemHovered());\r\n        */\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    IMGUI_DEMO_MARKER(\"Widgets/Bullets\");\r\n    if (ImGui::TreeNode(\"Bullets\"))\r\n    {\r\n        ImGui::BulletText(\"Bullet point 1\");\r\n        ImGui::BulletText(\"Bullet point 2\\nOn multiple lines\");\r\n        if (ImGui::TreeNode(\"Tree node\"))\r\n        {\r\n            ImGui::BulletText(\"Another bullet point\");\r\n            ImGui::TreePop();\r\n        }\r\n        ImGui::Bullet(); ImGui::Text(\"Bullet point 3 (two calls)\");\r\n        ImGui::Bullet(); ImGui::SmallButton(\"Button\");\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    IMGUI_DEMO_MARKER(\"Widgets/Text\");\r\n    if (ImGui::TreeNode(\"Text\"))\r\n    {\r\n        IMGUI_DEMO_MARKER(\"Widgets/Text/Colored Text\");\r\n        if (ImGui::TreeNode(\"Colorful Text\"))\r\n        {\r\n            // Using shortcut. You can use PushStyleColor()/PopStyleColor() for more flexibility.\r\n            ImGui::TextColored(ImVec4(1.0f, 0.0f, 1.0f, 1.0f), \"Pink\");\r\n            ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), \"Yellow\");\r\n            ImGui::TextDisabled(\"Disabled\");\r\n            ImGui::SameLine(); HelpMarker(\"The TextDisabled color is stored in ImGuiStyle.\");\r\n            ImGui::TreePop();\r\n        }\r\n\r\n        IMGUI_DEMO_MARKER(\"Widgets/Text/Word Wrapping\");\r\n        if (ImGui::TreeNode(\"Word Wrapping\"))\r\n        {\r\n            // Using shortcut. You can use PushTextWrapPos()/PopTextWrapPos() for more flexibility.\r\n            ImGui::TextWrapped(\r\n                \"This text should automatically wrap on the edge of the window. The current implementation \"\r\n                \"for text wrapping follows simple rules suitable for English and possibly other languages.\");\r\n            ImGui::Spacing();\r\n\r\n            static float wrap_width = 200.0f;\r\n            ImGui::SliderFloat(\"Wrap width\", &wrap_width, -20, 600, \"%.0f\");\r\n\r\n            ImDrawList* draw_list = ImGui::GetWindowDrawList();\r\n            for (int n = 0; n < 2; n++)\r\n            {\r\n                ImGui::Text(\"Test paragraph %d:\", n);\r\n                ImVec2 pos = ImGui::GetCursorScreenPos();\r\n                ImVec2 marker_min = ImVec2(pos.x + wrap_width, pos.y);\r\n                ImVec2 marker_max = ImVec2(pos.x + wrap_width + 10, pos.y + ImGui::GetTextLineHeight());\r\n                ImGui::PushTextWrapPos(ImGui::GetCursorPos().x + wrap_width);\r\n                if (n == 0)\r\n                    ImGui::Text(\"The lazy dog is a good dog. This paragraph should fit within %.0f pixels. Testing a 1 character word. The quick brown fox jumps over the lazy dog.\", wrap_width);\r\n                else\r\n                    ImGui::Text(\"aaaaaaaa bbbbbbbb, c cccccccc,dddddddd. d eeeeeeee   ffffffff. gggggggg!hhhhhhhh\");\r\n\r\n                // Draw actual text bounding box, following by marker of our expected limit (should not overlap!)\r\n                draw_list->AddRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), IM_COL32(255, 255, 0, 255));\r\n                draw_list->AddRectFilled(marker_min, marker_max, IM_COL32(255, 0, 255, 255));\r\n                ImGui::PopTextWrapPos();\r\n            }\r\n\r\n            ImGui::TreePop();\r\n        }\r\n\r\n        IMGUI_DEMO_MARKER(\"Widgets/Text/UTF-8 Text\");\r\n        if (ImGui::TreeNode(\"UTF-8 Text\"))\r\n        {\r\n            // UTF-8 test with Japanese characters\r\n            // (Needs a suitable font? Try \"Google Noto\" or \"Arial Unicode\". See docs/FONTS.md for details.)\r\n            // - From C++11 you can use the u8\"my text\" syntax to encode literal strings as UTF-8\r\n            // - For earlier compiler, you may be able to encode your sources as UTF-8 (e.g. in Visual Studio, you\r\n            //   can save your source files as 'UTF-8 without signature').\r\n            // - FOR THIS DEMO FILE ONLY, BECAUSE WE WANT TO SUPPORT OLD COMPILERS, WE ARE *NOT* INCLUDING RAW UTF-8\r\n            //   CHARACTERS IN THIS SOURCE FILE. Instead we are encoding a few strings with hexadecimal constants.\r\n            //   Don't do this in your application! Please use u8\"text in any language\" in your application!\r\n            // Note that characters values are preserved even by InputText() if the font cannot be displayed,\r\n            // so you can safely copy & paste garbled characters into another application.\r\n            ImGui::TextWrapped(\r\n                \"CJK text will only appears if the font was loaded with the appropriate CJK character ranges. \"\r\n                \"Call io.Fonts->AddFontFromFileTTF() manually to load extra character ranges. \"\r\n                \"Read docs/FONTS.md for details.\");\r\n            ImGui::Text(\"Hiragana: \\xe3\\x81\\x8b\\xe3\\x81\\x8d\\xe3\\x81\\x8f\\xe3\\x81\\x91\\xe3\\x81\\x93 (kakikukeko)\"); // Normally we would use u8\"blah blah\" with the proper characters directly in the string.\r\n            ImGui::Text(\"Kanjis: \\xe6\\x97\\xa5\\xe6\\x9c\\xac\\xe8\\xaa\\x9e (nihongo)\");\r\n            static char buf[32] = \"\\xe6\\x97\\xa5\\xe6\\x9c\\xac\\xe8\\xaa\\x9e\";\r\n            //static char buf[32] = u8\"NIHONGO\"; // <- this is how you would write it with C++11, using real kanjis\r\n            ImGui::InputText(\"UTF-8 input\", buf, IM_ARRAYSIZE(buf));\r\n            ImGui::TreePop();\r\n        }\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    IMGUI_DEMO_MARKER(\"Widgets/Images\");\r\n    if (ImGui::TreeNode(\"Images\"))\r\n    {\r\n        ImGuiIO& io = ImGui::GetIO();\r\n        ImGui::TextWrapped(\r\n            \"Below we are displaying the font texture (which is the only texture we have access to in this demo). \"\r\n            \"Use the 'ImTextureID' type as storage to pass pointers or identifier to your own texture data. \"\r\n            \"Hover the texture for a zoomed view!\");\r\n\r\n        // Below we are displaying the font texture because it is the only texture we have access to inside the demo!\r\n        // Remember that ImTextureID is just storage for whatever you want it to be. It is essentially a value that\r\n        // will be passed to the rendering backend via the ImDrawCmd structure.\r\n        // If you use one of the default imgui_impl_XXXX.cpp rendering backend, they all have comments at the top\r\n        // of their respective source file to specify what they expect to be stored in ImTextureID, for example:\r\n        // - The imgui_impl_dx11.cpp renderer expect a 'ID3D11ShaderResourceView*' pointer\r\n        // - The imgui_impl_opengl3.cpp renderer expect a GLuint OpenGL texture identifier, etc.\r\n        // More:\r\n        // - If you decided that ImTextureID = MyEngineTexture*, then you can pass your MyEngineTexture* pointers\r\n        //   to ImGui::Image(), and gather width/height through your own functions, etc.\r\n        // - You can use ShowMetricsWindow() to inspect the draw data that are being passed to your renderer,\r\n        //   it will help you debug issues if you are confused about it.\r\n        // - Consider using the lower-level ImDrawList::AddImage() API, via ImGui::GetWindowDrawList()->AddImage().\r\n        // - Read https://github.com/ocornut/imgui/blob/master/docs/FAQ.md\r\n        // - Read https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples\r\n        ImTextureID my_tex_id = io.Fonts->TexID;\r\n        float my_tex_w = (float)io.Fonts->TexWidth;\r\n        float my_tex_h = (float)io.Fonts->TexHeight;\r\n        {\r\n            ImGui::Text(\"%.0fx%.0f\", my_tex_w, my_tex_h);\r\n            ImVec2 pos = ImGui::GetCursorScreenPos();\r\n            ImVec2 uv_min = ImVec2(0.0f, 0.0f);                 // Top-left\r\n            ImVec2 uv_max = ImVec2(1.0f, 1.0f);                 // Lower-right\r\n            ImVec4 tint_col = ImVec4(1.0f, 1.0f, 1.0f, 1.0f);   // No tint\r\n            ImVec4 border_col = ImVec4(1.0f, 1.0f, 1.0f, 0.5f); // 50% opaque white\r\n            ImGui::Image(my_tex_id, ImVec2(my_tex_w, my_tex_h), uv_min, uv_max, tint_col, border_col);\r\n            if (ImGui::IsItemHovered())\r\n            {\r\n                ImGui::BeginTooltip();\r\n                float region_sz = 32.0f;\r\n                float region_x = io.MousePos.x - pos.x - region_sz * 0.5f;\r\n                float region_y = io.MousePos.y - pos.y - region_sz * 0.5f;\r\n                float zoom = 4.0f;\r\n                if (region_x < 0.0f) { region_x = 0.0f; }\r\n                else if (region_x > my_tex_w - region_sz) { region_x = my_tex_w - region_sz; }\r\n                if (region_y < 0.0f) { region_y = 0.0f; }\r\n                else if (region_y > my_tex_h - region_sz) { region_y = my_tex_h - region_sz; }\r\n                ImGui::Text(\"Min: (%.2f, %.2f)\", region_x, region_y);\r\n                ImGui::Text(\"Max: (%.2f, %.2f)\", region_x + region_sz, region_y + region_sz);\r\n                ImVec2 uv0 = ImVec2((region_x) / my_tex_w, (region_y) / my_tex_h);\r\n                ImVec2 uv1 = ImVec2((region_x + region_sz) / my_tex_w, (region_y + region_sz) / my_tex_h);\r\n                ImGui::Image(my_tex_id, ImVec2(region_sz * zoom, region_sz * zoom), uv0, uv1, tint_col, border_col);\r\n                ImGui::EndTooltip();\r\n            }\r\n        }\r\n\r\n        IMGUI_DEMO_MARKER(\"Widgets/Images/Textured buttons\");\r\n        ImGui::TextWrapped(\"And now some textured buttons..\");\r\n        static int pressed_count = 0;\r\n        for (int i = 0; i < 8; i++)\r\n        {\r\n            ImGui::PushID(i);\r\n            int frame_padding = -1 + i;                             // -1 == uses default padding (style.FramePadding)\r\n            ImVec2 size = ImVec2(32.0f, 32.0f);                     // Size of the image we want to make visible\r\n            ImVec2 uv0 = ImVec2(0.0f, 0.0f);                        // UV coordinates for lower-left\r\n            ImVec2 uv1 = ImVec2(32.0f / my_tex_w, 32.0f / my_tex_h);// UV coordinates for (32,32) in our texture\r\n            ImVec4 bg_col = ImVec4(0.0f, 0.0f, 0.0f, 1.0f);         // Black background\r\n            ImVec4 tint_col = ImVec4(1.0f, 1.0f, 1.0f, 1.0f);       // No tint\r\n            if (ImGui::ImageButton(my_tex_id, size, uv0, uv1, frame_padding, bg_col, tint_col))\r\n                pressed_count += 1;\r\n            ImGui::PopID();\r\n            ImGui::SameLine();\r\n        }\r\n        ImGui::NewLine();\r\n        ImGui::Text(\"Pressed %d times.\", pressed_count);\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    IMGUI_DEMO_MARKER(\"Widgets/Combo\");\r\n    if (ImGui::TreeNode(\"Combo\"))\r\n    {\r\n        // Expose flags as checkbox for the demo\r\n        static ImGuiComboFlags flags = 0;\r\n        ImGui::CheckboxFlags(\"ImGuiComboFlags_PopupAlignLeft\", &flags, ImGuiComboFlags_PopupAlignLeft);\r\n        ImGui::SameLine(); HelpMarker(\"Only makes a difference if the popup is larger than the combo\");\r\n        if (ImGui::CheckboxFlags(\"ImGuiComboFlags_NoArrowButton\", &flags, ImGuiComboFlags_NoArrowButton))\r\n            flags &= ~ImGuiComboFlags_NoPreview;     // Clear the other flag, as we cannot combine both\r\n        if (ImGui::CheckboxFlags(\"ImGuiComboFlags_NoPreview\", &flags, ImGuiComboFlags_NoPreview))\r\n            flags &= ~ImGuiComboFlags_NoArrowButton; // Clear the other flag, as we cannot combine both\r\n\r\n        // Using the generic BeginCombo() API, you have full control over how to display the combo contents.\r\n        // (your selection data could be an index, a pointer to the object, an id for the object, a flag intrusively\r\n        // stored in the object itself, etc.)\r\n        const char* items[] = { \"AAAA\", \"BBBB\", \"CCCC\", \"DDDD\", \"EEEE\", \"FFFF\", \"GGGG\", \"HHHH\", \"IIII\", \"JJJJ\", \"KKKK\", \"LLLLLLL\", \"MMMM\", \"OOOOOOO\" };\r\n        static int item_current_idx = 0; // Here we store our selection data as an index.\r\n        const char* combo_preview_value = items[item_current_idx];  // Pass in the preview value visible before opening the combo (it could be anything)\r\n        if (ImGui::BeginCombo(\"combo 1\", combo_preview_value, flags))\r\n        {\r\n            for (int n = 0; n < IM_ARRAYSIZE(items); n++)\r\n            {\r\n                const bool is_selected = (item_current_idx == n);\r\n                if (ImGui::Selectable(items[n], is_selected))\r\n                    item_current_idx = n;\r\n\r\n                // Set the initial focus when opening the combo (scrolling + keyboard navigation focus)\r\n                if (is_selected)\r\n                    ImGui::SetItemDefaultFocus();\r\n            }\r\n            ImGui::EndCombo();\r\n        }\r\n\r\n        // Simplified one-liner Combo() API, using values packed in a single constant string\r\n        // This is a convenience for when the selection set is small and known at compile-time.\r\n        static int item_current_2 = 0;\r\n        ImGui::Combo(\"combo 2 (one-liner)\", &item_current_2, \"aaaa\\0bbbb\\0cccc\\0dddd\\0eeee\\0\\0\");\r\n\r\n        // Simplified one-liner Combo() using an array of const char*\r\n        // This is not very useful (may obsolete): prefer using BeginCombo()/EndCombo() for full control.\r\n        static int item_current_3 = -1; // If the selection isn't within 0..count, Combo won't display a preview\r\n        ImGui::Combo(\"combo 3 (array)\", &item_current_3, items, IM_ARRAYSIZE(items));\r\n\r\n        // Simplified one-liner Combo() using an accessor function\r\n        struct Funcs { static bool ItemGetter(void* data, int n, const char** out_str) { *out_str = ((const char**)data)[n]; return true; } };\r\n        static int item_current_4 = 0;\r\n        ImGui::Combo(\"combo 4 (function)\", &item_current_4, &Funcs::ItemGetter, items, IM_ARRAYSIZE(items));\r\n\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    IMGUI_DEMO_MARKER(\"Widgets/List Boxes\");\r\n    if (ImGui::TreeNode(\"List boxes\"))\r\n    {\r\n        // Using the generic BeginListBox() API, you have full control over how to display the combo contents.\r\n        // (your selection data could be an index, a pointer to the object, an id for the object, a flag intrusively\r\n        // stored in the object itself, etc.)\r\n        const char* items[] = { \"AAAA\", \"BBBB\", \"CCCC\", \"DDDD\", \"EEEE\", \"FFFF\", \"GGGG\", \"HHHH\", \"IIII\", \"JJJJ\", \"KKKK\", \"LLLLLLL\", \"MMMM\", \"OOOOOOO\" };\r\n        static int item_current_idx = 0; // Here we store our selection data as an index.\r\n        if (ImGui::BeginListBox(\"listbox 1\"))\r\n        {\r\n            for (int n = 0; n < IM_ARRAYSIZE(items); n++)\r\n            {\r\n                const bool is_selected = (item_current_idx == n);\r\n                if (ImGui::Selectable(items[n], is_selected))\r\n                    item_current_idx = n;\r\n\r\n                // Set the initial focus when opening the combo (scrolling + keyboard navigation focus)\r\n                if (is_selected)\r\n                    ImGui::SetItemDefaultFocus();\r\n            }\r\n            ImGui::EndListBox();\r\n        }\r\n\r\n        // Custom size: use all width, 5 items tall\r\n        ImGui::Text(\"Full-width:\");\r\n        if (ImGui::BeginListBox(\"##listbox 2\", ImVec2(-FLT_MIN, 5 * ImGui::GetTextLineHeightWithSpacing())))\r\n        {\r\n            for (int n = 0; n < IM_ARRAYSIZE(items); n++)\r\n            {\r\n                const bool is_selected = (item_current_idx == n);\r\n                if (ImGui::Selectable(items[n], is_selected))\r\n                    item_current_idx = n;\r\n\r\n                // Set the initial focus when opening the combo (scrolling + keyboard navigation focus)\r\n                if (is_selected)\r\n                    ImGui::SetItemDefaultFocus();\r\n            }\r\n            ImGui::EndListBox();\r\n        }\r\n\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    IMGUI_DEMO_MARKER(\"Widgets/Selectables\");\r\n    if (ImGui::TreeNode(\"Selectables\"))\r\n    {\r\n        // Selectable() has 2 overloads:\r\n        // - The one taking \"bool selected\" as a read-only selection information.\r\n        //   When Selectable() has been clicked it returns true and you can alter selection state accordingly.\r\n        // - The one taking \"bool* p_selected\" as a read-write selection information (convenient in some cases)\r\n        // The earlier is more flexible, as in real application your selection may be stored in many different ways\r\n        // and not necessarily inside a bool value (e.g. in flags within objects, as an external list, etc).\r\n        IMGUI_DEMO_MARKER(\"Widgets/Selectables/Basic\");\r\n        if (ImGui::TreeNode(\"Basic\"))\r\n        {\r\n            static bool selection[5] = { false, true, false, false, false };\r\n            ImGui::Selectable(\"1. I am selectable\", &selection[0]);\r\n            ImGui::Selectable(\"2. I am selectable\", &selection[1]);\r\n            ImGui::Text(\"(I am not selectable)\");\r\n            ImGui::Selectable(\"4. I am selectable\", &selection[3]);\r\n            if (ImGui::Selectable(\"5. I am double clickable\", selection[4], ImGuiSelectableFlags_AllowDoubleClick))\r\n                if (ImGui::IsMouseDoubleClicked(0))\r\n                    selection[4] = !selection[4];\r\n            ImGui::TreePop();\r\n        }\r\n        IMGUI_DEMO_MARKER(\"Widgets/Selectables/Single Selection\");\r\n        if (ImGui::TreeNode(\"Selection State: Single Selection\"))\r\n        {\r\n            static int selected = -1;\r\n            for (int n = 0; n < 5; n++)\r\n            {\r\n                char buf[32];\r\n                sprintf(buf, \"Object %d\", n);\r\n                if (ImGui::Selectable(buf, selected == n))\r\n                    selected = n;\r\n            }\r\n            ImGui::TreePop();\r\n        }\r\n        IMGUI_DEMO_MARKER(\"Widgets/Selectables/Multiple Selection\");\r\n        if (ImGui::TreeNode(\"Selection State: Multiple Selection\"))\r\n        {\r\n            HelpMarker(\"Hold CTRL and click to select multiple items.\");\r\n            static bool selection[5] = { false, false, false, false, false };\r\n            for (int n = 0; n < 5; n++)\r\n            {\r\n                char buf[32];\r\n                sprintf(buf, \"Object %d\", n);\r\n                if (ImGui::Selectable(buf, selection[n]))\r\n                {\r\n                    if (!ImGui::GetIO().KeyCtrl)    // Clear selection when CTRL is not held\r\n                        memset(selection, 0, sizeof(selection));\r\n                    selection[n] ^= 1;\r\n                }\r\n            }\r\n            ImGui::TreePop();\r\n        }\r\n        IMGUI_DEMO_MARKER(\"Widgets/Selectables/Rendering more text into the same line\");\r\n        if (ImGui::TreeNode(\"Rendering more text into the same line\"))\r\n        {\r\n            // Using the Selectable() override that takes \"bool* p_selected\" parameter,\r\n            // this function toggle your bool value automatically.\r\n            static bool selected[3] = { false, false, false };\r\n            ImGui::Selectable(\"main.c\",    &selected[0]); ImGui::SameLine(300); ImGui::Text(\" 2,345 bytes\");\r\n            ImGui::Selectable(\"Hello.cpp\", &selected[1]); ImGui::SameLine(300); ImGui::Text(\"12,345 bytes\");\r\n            ImGui::Selectable(\"Hello.h\",   &selected[2]); ImGui::SameLine(300); ImGui::Text(\" 2,345 bytes\");\r\n            ImGui::TreePop();\r\n        }\r\n        IMGUI_DEMO_MARKER(\"Widgets/Selectables/In columns\");\r\n        if (ImGui::TreeNode(\"In columns\"))\r\n        {\r\n            static bool selected[10] = {};\r\n\r\n            if (ImGui::BeginTable(\"split1\", 3, ImGuiTableFlags_Resizable | ImGuiTableFlags_NoSavedSettings | ImGuiTableFlags_Borders))\r\n            {\r\n                for (int i = 0; i < 10; i++)\r\n                {\r\n                    char label[32];\r\n                    sprintf(label, \"Item %d\", i);\r\n                    ImGui::TableNextColumn();\r\n                    ImGui::Selectable(label, &selected[i]); // FIXME-TABLE: Selection overlap\r\n                }\r\n                ImGui::EndTable();\r\n            }\r\n            ImGui::Spacing();\r\n            if (ImGui::BeginTable(\"split2\", 3, ImGuiTableFlags_Resizable | ImGuiTableFlags_NoSavedSettings | ImGuiTableFlags_Borders))\r\n            {\r\n                for (int i = 0; i < 10; i++)\r\n                {\r\n                    char label[32];\r\n                    sprintf(label, \"Item %d\", i);\r\n                    ImGui::TableNextRow();\r\n                    ImGui::TableNextColumn();\r\n                    ImGui::Selectable(label, &selected[i], ImGuiSelectableFlags_SpanAllColumns);\r\n                    ImGui::TableNextColumn();\r\n                    ImGui::Text(\"Some other contents\");\r\n                    ImGui::TableNextColumn();\r\n                    ImGui::Text(\"123456\");\r\n                }\r\n                ImGui::EndTable();\r\n            }\r\n            ImGui::TreePop();\r\n        }\r\n        IMGUI_DEMO_MARKER(\"Widgets/Selectables/Grid\");\r\n        if (ImGui::TreeNode(\"Grid\"))\r\n        {\r\n            static char selected[4][4] = { { 1, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 0, 1, 0 }, { 0, 0, 0, 1 } };\r\n\r\n            // Add in a bit of silly fun...\r\n            const float time = (float)ImGui::GetTime();\r\n            const bool winning_state = memchr(selected, 0, sizeof(selected)) == NULL; // If all cells are selected...\r\n            if (winning_state)\r\n                ImGui::PushStyleVar(ImGuiStyleVar_SelectableTextAlign, ImVec2(0.5f + 0.5f * cosf(time * 2.0f), 0.5f + 0.5f * sinf(time * 3.0f)));\r\n\r\n            for (int y = 0; y < 4; y++)\r\n                for (int x = 0; x < 4; x++)\r\n                {\r\n                    if (x > 0)\r\n                        ImGui::SameLine();\r\n                    ImGui::PushID(y * 4 + x);\r\n                    if (ImGui::Selectable(\"Sailor\", selected[y][x] != 0, 0, ImVec2(50, 50)))\r\n                    {\r\n                        // Toggle clicked cell + toggle neighbors\r\n                        selected[y][x] ^= 1;\r\n                        if (x > 0) { selected[y][x - 1] ^= 1; }\r\n                        if (x < 3) { selected[y][x + 1] ^= 1; }\r\n                        if (y > 0) { selected[y - 1][x] ^= 1; }\r\n                        if (y < 3) { selected[y + 1][x] ^= 1; }\r\n                    }\r\n                    ImGui::PopID();\r\n                }\r\n\r\n            if (winning_state)\r\n                ImGui::PopStyleVar();\r\n            ImGui::TreePop();\r\n        }\r\n        IMGUI_DEMO_MARKER(\"Widgets/Selectables/Alignment\");\r\n        if (ImGui::TreeNode(\"Alignment\"))\r\n        {\r\n            HelpMarker(\r\n                \"By default, Selectables uses style.SelectableTextAlign but it can be overridden on a per-item \"\r\n                \"basis using PushStyleVar(). You'll probably want to always keep your default situation to \"\r\n                \"left-align otherwise it becomes difficult to layout multiple items on a same line\");\r\n            static bool selected[3 * 3] = { true, false, true, false, true, false, true, false, true };\r\n            for (int y = 0; y < 3; y++)\r\n            {\r\n                for (int x = 0; x < 3; x++)\r\n                {\r\n                    ImVec2 alignment = ImVec2((float)x / 2.0f, (float)y / 2.0f);\r\n                    char name[32];\r\n                    sprintf(name, \"(%.1f,%.1f)\", alignment.x, alignment.y);\r\n                    if (x > 0) ImGui::SameLine();\r\n                    ImGui::PushStyleVar(ImGuiStyleVar_SelectableTextAlign, alignment);\r\n                    ImGui::Selectable(name, &selected[3 * y + x], ImGuiSelectableFlags_None, ImVec2(80, 80));\r\n                    ImGui::PopStyleVar();\r\n                }\r\n            }\r\n            ImGui::TreePop();\r\n        }\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    // To wire InputText() with std::string or any other custom string type,\r\n    // see the \"Text Input > Resize Callback\" section of this demo, and the misc/cpp/imgui_stdlib.h file.\r\n    IMGUI_DEMO_MARKER(\"Widgets/Text Input\");\r\n    if (ImGui::TreeNode(\"Text Input\"))\r\n    {\r\n        IMGUI_DEMO_MARKER(\"Widgets/Text Input/Multi-line Text Input\");\r\n        if (ImGui::TreeNode(\"Multi-line Text Input\"))\r\n        {\r\n            // Note: we are using a fixed-sized buffer for simplicity here. See ImGuiInputTextFlags_CallbackResize\r\n            // and the code in misc/cpp/imgui_stdlib.h for how to setup InputText() for dynamically resizing strings.\r\n            static char text[1024 * 16] =\r\n                \"/*\\n\"\r\n                \" The Pentium F00F bug, shorthand for F0 0F C7 C8,\\n\"\r\n                \" the hexadecimal encoding of one offending instruction,\\n\"\r\n                \" more formally, the invalid operand with locked CMPXCHG8B\\n\"\r\n                \" instruction bug, is a design flaw in the majority of\\n\"\r\n                \" Intel Pentium, Pentium MMX, and Pentium OverDrive\\n\"\r\n                \" processors (all in the P5 microarchitecture).\\n\"\r\n                \"*/\\n\\n\"\r\n                \"label:\\n\"\r\n                \"\\tlock cmpxchg8b eax\\n\";\r\n\r\n            static ImGuiInputTextFlags flags = ImGuiInputTextFlags_AllowTabInput;\r\n            HelpMarker(\"You can use the ImGuiInputTextFlags_CallbackResize facility if you need to wire InputTextMultiline() to a dynamic string type. See misc/cpp/imgui_stdlib.h for an example. (This is not demonstrated in imgui_demo.cpp because we don't want to include <string> in here)\");\r\n            ImGui::CheckboxFlags(\"ImGuiInputTextFlags_ReadOnly\", &flags, ImGuiInputTextFlags_ReadOnly);\r\n            ImGui::CheckboxFlags(\"ImGuiInputTextFlags_AllowTabInput\", &flags, ImGuiInputTextFlags_AllowTabInput);\r\n            ImGui::CheckboxFlags(\"ImGuiInputTextFlags_CtrlEnterForNewLine\", &flags, ImGuiInputTextFlags_CtrlEnterForNewLine);\r\n            ImGui::InputTextMultiline(\"##source\", text, IM_ARRAYSIZE(text), ImVec2(-FLT_MIN, ImGui::GetTextLineHeight() * 16), flags);\r\n            ImGui::TreePop();\r\n        }\r\n\r\n        IMGUI_DEMO_MARKER(\"Widgets/Text Input/Filtered Text Input\");\r\n        if (ImGui::TreeNode(\"Filtered Text Input\"))\r\n        {\r\n            struct TextFilters\r\n            {\r\n                // Return 0 (pass) if the character is 'i' or 'm' or 'g' or 'u' or 'i'\r\n                static int FilterImGuiLetters(ImGuiInputTextCallbackData* data)\r\n                {\r\n                    if (data->EventChar < 256 && strchr(\"imgui\", (char)data->EventChar))\r\n                        return 0;\r\n                    return 1;\r\n                }\r\n            };\r\n\r\n            static char buf1[64] = \"\"; ImGui::InputText(\"default\",     buf1, 64);\r\n            static char buf2[64] = \"\"; ImGui::InputText(\"decimal\",     buf2, 64, ImGuiInputTextFlags_CharsDecimal);\r\n            static char buf3[64] = \"\"; ImGui::InputText(\"hexadecimal\", buf3, 64, ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase);\r\n            static char buf4[64] = \"\"; ImGui::InputText(\"uppercase\",   buf4, 64, ImGuiInputTextFlags_CharsUppercase);\r\n            static char buf5[64] = \"\"; ImGui::InputText(\"no blank\",    buf5, 64, ImGuiInputTextFlags_CharsNoBlank);\r\n            static char buf6[64] = \"\"; ImGui::InputText(\"\\\"imgui\\\" letters\", buf6, 64, ImGuiInputTextFlags_CallbackCharFilter, TextFilters::FilterImGuiLetters);\r\n            ImGui::TreePop();\r\n        }\r\n\r\n        IMGUI_DEMO_MARKER(\"Widgets/Text Input/Password input\");\r\n        if (ImGui::TreeNode(\"Password Input\"))\r\n        {\r\n            static char password[64] = \"password123\";\r\n            ImGui::InputText(\"password\", password, IM_ARRAYSIZE(password), ImGuiInputTextFlags_Password);\r\n            ImGui::SameLine(); HelpMarker(\"Display all characters as '*'.\\nDisable clipboard cut and copy.\\nDisable logging.\\n\");\r\n            ImGui::InputTextWithHint(\"password (w/ hint)\", \"<password>\", password, IM_ARRAYSIZE(password), ImGuiInputTextFlags_Password);\r\n            ImGui::InputText(\"password (clear)\", password, IM_ARRAYSIZE(password));\r\n            ImGui::TreePop();\r\n        }\r\n\r\n        if (ImGui::TreeNode(\"Completion, History, Edit Callbacks\"))\r\n        {\r\n            struct Funcs\r\n            {\r\n                static int MyCallback(ImGuiInputTextCallbackData* data)\r\n                {\r\n                    if (data->EventFlag == ImGuiInputTextFlags_CallbackCompletion)\r\n                    {\r\n                        data->InsertChars(data->CursorPos, \"..\");\r\n                    }\r\n                    else if (data->EventFlag == ImGuiInputTextFlags_CallbackHistory)\r\n                    {\r\n                        if (data->EventKey == ImGuiKey_UpArrow)\r\n                        {\r\n                            data->DeleteChars(0, data->BufTextLen);\r\n                            data->InsertChars(0, \"Pressed Up!\");\r\n                            data->SelectAll();\r\n                        }\r\n                        else if (data->EventKey == ImGuiKey_DownArrow)\r\n                        {\r\n                            data->DeleteChars(0, data->BufTextLen);\r\n                            data->InsertChars(0, \"Pressed Down!\");\r\n                            data->SelectAll();\r\n                        }\r\n                    }\r\n                    else if (data->EventFlag == ImGuiInputTextFlags_CallbackEdit)\r\n                    {\r\n                        // Toggle casing of first character\r\n                        char c = data->Buf[0];\r\n                        if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) data->Buf[0] ^= 32;\r\n                        data->BufDirty = true;\r\n\r\n                        // Increment a counter\r\n                        int* p_int = (int*)data->UserData;\r\n                        *p_int = *p_int + 1;\r\n                    }\r\n                    return 0;\r\n                }\r\n            };\r\n            static char buf1[64];\r\n            ImGui::InputText(\"Completion\", buf1, 64, ImGuiInputTextFlags_CallbackCompletion, Funcs::MyCallback);\r\n            ImGui::SameLine(); HelpMarker(\"Here we append \\\"..\\\" each time Tab is pressed. See 'Examples>Console' for a more meaningful demonstration of using this callback.\");\r\n\r\n            static char buf2[64];\r\n            ImGui::InputText(\"History\", buf2, 64, ImGuiInputTextFlags_CallbackHistory, Funcs::MyCallback);\r\n            ImGui::SameLine(); HelpMarker(\"Here we replace and select text each time Up/Down are pressed. See 'Examples>Console' for a more meaningful demonstration of using this callback.\");\r\n\r\n            static char buf3[64];\r\n            static int edit_count = 0;\r\n            ImGui::InputText(\"Edit\", buf3, 64, ImGuiInputTextFlags_CallbackEdit, Funcs::MyCallback, (void*)&edit_count);\r\n            ImGui::SameLine(); HelpMarker(\"Here we toggle the casing of the first character on every edits + count edits.\");\r\n            ImGui::SameLine(); ImGui::Text(\"(%d)\", edit_count);\r\n\r\n            ImGui::TreePop();\r\n        }\r\n\r\n        IMGUI_DEMO_MARKER(\"Widgets/Text Input/Resize Callback\");\r\n        if (ImGui::TreeNode(\"Resize Callback\"))\r\n        {\r\n            // To wire InputText() with std::string or any other custom string type,\r\n            // you can use the ImGuiInputTextFlags_CallbackResize flag + create a custom ImGui::InputText() wrapper\r\n            // using your preferred type. See misc/cpp/imgui_stdlib.h for an implementation of this using std::string.\r\n            HelpMarker(\r\n                \"Using ImGuiInputTextFlags_CallbackResize to wire your custom string type to InputText().\\n\\n\"\r\n                \"See misc/cpp/imgui_stdlib.h for an implementation of this for std::string.\");\r\n            struct Funcs\r\n            {\r\n                static int MyResizeCallback(ImGuiInputTextCallbackData* data)\r\n                {\r\n                    if (data->EventFlag == ImGuiInputTextFlags_CallbackResize)\r\n                    {\r\n                        ImVector<char>* my_str = (ImVector<char>*)data->UserData;\r\n                        IM_ASSERT(my_str->begin() == data->Buf);\r\n                        my_str->resize(data->BufSize); // NB: On resizing calls, generally data->BufSize == data->BufTextLen + 1\r\n                        data->Buf = my_str->begin();\r\n                    }\r\n                    return 0;\r\n                }\r\n\r\n                // Note: Because ImGui:: is a namespace you would typically add your own function into the namespace.\r\n                // For example, you code may declare a function 'ImGui::InputText(const char* label, MyString* my_str)'\r\n                static bool MyInputTextMultiline(const char* label, ImVector<char>* my_str, const ImVec2& size = ImVec2(0, 0), ImGuiInputTextFlags flags = 0)\r\n                {\r\n                    IM_ASSERT((flags & ImGuiInputTextFlags_CallbackResize) == 0);\r\n                    return ImGui::InputTextMultiline(label, my_str->begin(), (size_t)my_str->size(), size, flags | ImGuiInputTextFlags_CallbackResize, Funcs::MyResizeCallback, (void*)my_str);\r\n                }\r\n            };\r\n\r\n            // For this demo we are using ImVector as a string container.\r\n            // Note that because we need to store a terminating zero character, our size/capacity are 1 more\r\n            // than usually reported by a typical string class.\r\n            static ImVector<char> my_str;\r\n            if (my_str.empty())\r\n                my_str.push_back(0);\r\n            Funcs::MyInputTextMultiline(\"##MyStr\", &my_str, ImVec2(-FLT_MIN, ImGui::GetTextLineHeight() * 16));\r\n            ImGui::Text(\"Data: %p\\nSize: %d\\nCapacity: %d\", (void*)my_str.begin(), my_str.size(), my_str.capacity());\r\n            ImGui::TreePop();\r\n        }\r\n\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    // Tabs\r\n    IMGUI_DEMO_MARKER(\"Widgets/Tabs\");\r\n    if (ImGui::TreeNode(\"Tabs\"))\r\n    {\r\n        IMGUI_DEMO_MARKER(\"Widgets/Tabs/Basic\");\r\n        if (ImGui::TreeNode(\"Basic\"))\r\n        {\r\n            ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_None;\r\n            if (ImGui::BeginTabBar(\"MyTabBar\", tab_bar_flags))\r\n            {\r\n                if (ImGui::BeginTabItem(\"Avocado\"))\r\n                {\r\n                    ImGui::Text(\"This is the Avocado tab!\\nblah blah blah blah blah\");\r\n                    ImGui::EndTabItem();\r\n                }\r\n                if (ImGui::BeginTabItem(\"Broccoli\"))\r\n                {\r\n                    ImGui::Text(\"This is the Broccoli tab!\\nblah blah blah blah blah\");\r\n                    ImGui::EndTabItem();\r\n                }\r\n                if (ImGui::BeginTabItem(\"Cucumber\"))\r\n                {\r\n                    ImGui::Text(\"This is the Cucumber tab!\\nblah blah blah blah blah\");\r\n                    ImGui::EndTabItem();\r\n                }\r\n                ImGui::EndTabBar();\r\n            }\r\n            ImGui::Separator();\r\n            ImGui::TreePop();\r\n        }\r\n\r\n        IMGUI_DEMO_MARKER(\"Widgets/Tabs/Advanced & Close Button\");\r\n        if (ImGui::TreeNode(\"Advanced & Close Button\"))\r\n        {\r\n            // Expose a couple of the available flags. In most cases you may just call BeginTabBar() with no flags (0).\r\n            static ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable;\r\n            ImGui::CheckboxFlags(\"ImGuiTabBarFlags_Reorderable\", &tab_bar_flags, ImGuiTabBarFlags_Reorderable);\r\n            ImGui::CheckboxFlags(\"ImGuiTabBarFlags_AutoSelectNewTabs\", &tab_bar_flags, ImGuiTabBarFlags_AutoSelectNewTabs);\r\n            ImGui::CheckboxFlags(\"ImGuiTabBarFlags_TabListPopupButton\", &tab_bar_flags, ImGuiTabBarFlags_TabListPopupButton);\r\n            ImGui::CheckboxFlags(\"ImGuiTabBarFlags_NoCloseWithMiddleMouseButton\", &tab_bar_flags, ImGuiTabBarFlags_NoCloseWithMiddleMouseButton);\r\n            if ((tab_bar_flags & ImGuiTabBarFlags_FittingPolicyMask_) == 0)\r\n                tab_bar_flags |= ImGuiTabBarFlags_FittingPolicyDefault_;\r\n            if (ImGui::CheckboxFlags(\"ImGuiTabBarFlags_FittingPolicyResizeDown\", &tab_bar_flags, ImGuiTabBarFlags_FittingPolicyResizeDown))\r\n                tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyResizeDown);\r\n            if (ImGui::CheckboxFlags(\"ImGuiTabBarFlags_FittingPolicyScroll\", &tab_bar_flags, ImGuiTabBarFlags_FittingPolicyScroll))\r\n                tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyScroll);\r\n\r\n            // Tab Bar\r\n            const char* names[4] = { \"Artichoke\", \"Beetroot\", \"Celery\", \"Daikon\" };\r\n            static bool opened[4] = { true, true, true, true }; // Persistent user state\r\n            for (int n = 0; n < IM_ARRAYSIZE(opened); n++)\r\n            {\r\n                if (n > 0) { ImGui::SameLine(); }\r\n                ImGui::Checkbox(names[n], &opened[n]);\r\n            }\r\n\r\n            // Passing a bool* to BeginTabItem() is similar to passing one to Begin():\r\n            // the underlying bool will be set to false when the tab is closed.\r\n            if (ImGui::BeginTabBar(\"MyTabBar\", tab_bar_flags))\r\n            {\r\n                for (int n = 0; n < IM_ARRAYSIZE(opened); n++)\r\n                    if (opened[n] && ImGui::BeginTabItem(names[n], &opened[n], ImGuiTabItemFlags_None))\r\n                    {\r\n                        ImGui::Text(\"This is the %s tab!\", names[n]);\r\n                        if (n & 1)\r\n                            ImGui::Text(\"I am an odd tab.\");\r\n                        ImGui::EndTabItem();\r\n                    }\r\n                ImGui::EndTabBar();\r\n            }\r\n            ImGui::Separator();\r\n            ImGui::TreePop();\r\n        }\r\n\r\n        IMGUI_DEMO_MARKER(\"Widgets/Tabs/TabItemButton & Leading-Trailing flags\");\r\n        if (ImGui::TreeNode(\"TabItemButton & Leading/Trailing flags\"))\r\n        {\r\n            static ImVector<int> active_tabs;\r\n            static int next_tab_id = 0;\r\n            if (next_tab_id == 0) // Initialize with some default tabs\r\n                for (int i = 0; i < 3; i++)\r\n                    active_tabs.push_back(next_tab_id++);\r\n\r\n            // TabItemButton() and Leading/Trailing flags are distinct features which we will demo together.\r\n            // (It is possible to submit regular tabs with Leading/Trailing flags, or TabItemButton tabs without Leading/Trailing flags...\r\n            // but they tend to make more sense together)\r\n            static bool show_leading_button = true;\r\n            static bool show_trailing_button = true;\r\n            ImGui::Checkbox(\"Show Leading TabItemButton()\", &show_leading_button);\r\n            ImGui::Checkbox(\"Show Trailing TabItemButton()\", &show_trailing_button);\r\n\r\n            // Expose some other flags which are useful to showcase how they interact with Leading/Trailing tabs\r\n            static ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_AutoSelectNewTabs | ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_FittingPolicyResizeDown;\r\n            ImGui::CheckboxFlags(\"ImGuiTabBarFlags_TabListPopupButton\", &tab_bar_flags, ImGuiTabBarFlags_TabListPopupButton);\r\n            if (ImGui::CheckboxFlags(\"ImGuiTabBarFlags_FittingPolicyResizeDown\", &tab_bar_flags, ImGuiTabBarFlags_FittingPolicyResizeDown))\r\n                tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyResizeDown);\r\n            if (ImGui::CheckboxFlags(\"ImGuiTabBarFlags_FittingPolicyScroll\", &tab_bar_flags, ImGuiTabBarFlags_FittingPolicyScroll))\r\n                tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyScroll);\r\n\r\n            if (ImGui::BeginTabBar(\"MyTabBar\", tab_bar_flags))\r\n            {\r\n                // Demo a Leading TabItemButton(): click the \"?\" button to open a menu\r\n                if (show_leading_button)\r\n                    if (ImGui::TabItemButton(\"?\", ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_NoTooltip))\r\n                        ImGui::OpenPopup(\"MyHelpMenu\");\r\n                if (ImGui::BeginPopup(\"MyHelpMenu\"))\r\n                {\r\n                    ImGui::Selectable(\"Hello!\");\r\n                    ImGui::EndPopup();\r\n                }\r\n\r\n                // Demo Trailing Tabs: click the \"+\" button to add a new tab (in your app you may want to use a font icon instead of the \"+\")\r\n                // Note that we submit it before the regular tabs, but because of the ImGuiTabItemFlags_Trailing flag it will always appear at the end.\r\n                if (show_trailing_button)\r\n                    if (ImGui::TabItemButton(\"+\", ImGuiTabItemFlags_Trailing | ImGuiTabItemFlags_NoTooltip))\r\n                        active_tabs.push_back(next_tab_id++); // Add new tab\r\n\r\n                // Submit our regular tabs\r\n                for (int n = 0; n < active_tabs.Size; )\r\n                {\r\n                    bool open = true;\r\n                    char name[16];\r\n                    snprintf(name, IM_ARRAYSIZE(name), \"%04d\", active_tabs[n]);\r\n                    if (ImGui::BeginTabItem(name, &open, ImGuiTabItemFlags_None))\r\n                    {\r\n                        ImGui::Text(\"This is the %s tab!\", name);\r\n                        ImGui::EndTabItem();\r\n                    }\r\n\r\n                    if (!open)\r\n                        active_tabs.erase(active_tabs.Data + n);\r\n                    else\r\n                        n++;\r\n                }\r\n\r\n                ImGui::EndTabBar();\r\n            }\r\n            ImGui::Separator();\r\n            ImGui::TreePop();\r\n        }\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    // Plot/Graph widgets are not very good.\r\n    // Consider using a third-party library such as ImPlot: https://github.com/epezent/implot\r\n    // (see others https://github.com/ocornut/imgui/wiki/Useful-Extensions)\r\n    IMGUI_DEMO_MARKER(\"Widgets/Plotting\");\r\n    if (ImGui::TreeNode(\"Plotting\"))\r\n    {\r\n        static bool animate = true;\r\n        ImGui::Checkbox(\"Animate\", &animate);\r\n\r\n        // Plot as lines and plot as histogram\r\n        IMGUI_DEMO_MARKER(\"Widgets/Plotting/PlotLines, PlotHistogram\");\r\n        static float arr[] = { 0.6f, 0.1f, 1.0f, 0.5f, 0.92f, 0.1f, 0.2f };\r\n        ImGui::PlotLines(\"Frame Times\", arr, IM_ARRAYSIZE(arr));\r\n        ImGui::PlotHistogram(\"Histogram\", arr, IM_ARRAYSIZE(arr), 0, NULL, 0.0f, 1.0f, ImVec2(0, 80.0f));\r\n\r\n        // Fill an array of contiguous float values to plot\r\n        // Tip: If your float aren't contiguous but part of a structure, you can pass a pointer to your first float\r\n        // and the sizeof() of your structure in the \"stride\" parameter.\r\n        static float values[90] = {};\r\n        static int values_offset = 0;\r\n        static double refresh_time = 0.0;\r\n        if (!animate || refresh_time == 0.0)\r\n            refresh_time = ImGui::GetTime();\r\n        while (refresh_time < ImGui::GetTime()) // Create data at fixed 60 Hz rate for the demo\r\n        {\r\n            static float phase = 0.0f;\r\n            values[values_offset] = cosf(phase);\r\n            values_offset = (values_offset + 1) % IM_ARRAYSIZE(values);\r\n            phase += 0.10f * values_offset;\r\n            refresh_time += 1.0f / 60.0f;\r\n        }\r\n\r\n        // Plots can display overlay texts\r\n        // (in this example, we will display an average value)\r\n        {\r\n            float average = 0.0f;\r\n            for (int n = 0; n < IM_ARRAYSIZE(values); n++)\r\n                average += values[n];\r\n            average /= (float)IM_ARRAYSIZE(values);\r\n            char overlay[32];\r\n            sprintf(overlay, \"avg %f\", average);\r\n            ImGui::PlotLines(\"Lines\", values, IM_ARRAYSIZE(values), values_offset, overlay, -1.0f, 1.0f, ImVec2(0, 80.0f));\r\n        }\r\n\r\n        // Use functions to generate output\r\n        // FIXME: This is rather awkward because current plot API only pass in indices.\r\n        // We probably want an API passing floats and user provide sample rate/count.\r\n        struct Funcs\r\n        {\r\n            static float Sin(void*, int i) { return sinf(i * 0.1f); }\r\n            static float Saw(void*, int i) { return (i & 1) ? 1.0f : -1.0f; }\r\n        };\r\n        static int func_type = 0, display_count = 70;\r\n        ImGui::Separator();\r\n        ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8);\r\n        ImGui::Combo(\"func\", &func_type, \"Sin\\0Saw\\0\");\r\n        ImGui::SameLine();\r\n        ImGui::SliderInt(\"Sample count\", &display_count, 1, 400);\r\n        float (*func)(void*, int) = (func_type == 0) ? Funcs::Sin : Funcs::Saw;\r\n        ImGui::PlotLines(\"Lines\", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0, 80));\r\n        ImGui::PlotHistogram(\"Histogram\", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0, 80));\r\n        ImGui::Separator();\r\n\r\n        // Animate a simple progress bar\r\n        IMGUI_DEMO_MARKER(\"Widgets/Plotting/ProgressBar\");\r\n        static float progress = 0.0f, progress_dir = 1.0f;\r\n        if (animate)\r\n        {\r\n            progress += progress_dir * 0.4f * ImGui::GetIO().DeltaTime;\r\n            if (progress >= +1.1f) { progress = +1.1f; progress_dir *= -1.0f; }\r\n            if (progress <= -0.1f) { progress = -0.1f; progress_dir *= -1.0f; }\r\n        }\r\n\r\n        // Typically we would use ImVec2(-1.0f,0.0f) or ImVec2(-FLT_MIN,0.0f) to use all available width,\r\n        // or ImVec2(width,0.0f) for a specified width. ImVec2(0.0f,0.0f) uses ItemWidth.\r\n        ImGui::ProgressBar(progress, ImVec2(0.0f, 0.0f));\r\n        ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x);\r\n        ImGui::Text(\"Progress Bar\");\r\n\r\n        float progress_saturated = IM_CLAMP(progress, 0.0f, 1.0f);\r\n        char buf[32];\r\n        sprintf(buf, \"%d/%d\", (int)(progress_saturated * 1753), 1753);\r\n        ImGui::ProgressBar(progress, ImVec2(0.f, 0.f), buf);\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    IMGUI_DEMO_MARKER(\"Widgets/Color\");\r\n    if (ImGui::TreeNode(\"Color/Picker Widgets\"))\r\n    {\r\n        static ImVec4 color = ImVec4(114.0f / 255.0f, 144.0f / 255.0f, 154.0f / 255.0f, 200.0f / 255.0f);\r\n\r\n        static bool alpha_preview = true;\r\n        static bool alpha_half_preview = false;\r\n        static bool drag_and_drop = true;\r\n        static bool options_menu = true;\r\n        static bool hdr = false;\r\n        ImGui::Checkbox(\"With Alpha Preview\", &alpha_preview);\r\n        ImGui::Checkbox(\"With Half Alpha Preview\", &alpha_half_preview);\r\n        ImGui::Checkbox(\"With Drag and Drop\", &drag_and_drop);\r\n        ImGui::Checkbox(\"With Options Menu\", &options_menu); ImGui::SameLine(); HelpMarker(\"Right-click on the individual color widget to show options.\");\r\n        ImGui::Checkbox(\"With HDR\", &hdr); ImGui::SameLine(); HelpMarker(\"Currently all this does is to lift the 0..1 limits on dragging widgets.\");\r\n        ImGuiColorEditFlags misc_flags = (hdr ? ImGuiColorEditFlags_HDR : 0) | (drag_and_drop ? 0 : ImGuiColorEditFlags_NoDragDrop) | (alpha_half_preview ? ImGuiColorEditFlags_AlphaPreviewHalf : (alpha_preview ? ImGuiColorEditFlags_AlphaPreview : 0)) | (options_menu ? 0 : ImGuiColorEditFlags_NoOptions);\r\n\r\n        IMGUI_DEMO_MARKER(\"Widgets/Color/ColorEdit\");\r\n        ImGui::Text(\"Color widget:\");\r\n        ImGui::SameLine(); HelpMarker(\r\n            \"Click on the color square to open a color picker.\\n\"\r\n            \"CTRL+click on individual component to input value.\\n\");\r\n        ImGui::ColorEdit3(\"MyColor##1\", (float*)&color, misc_flags);\r\n\r\n        IMGUI_DEMO_MARKER(\"Widgets/Color/ColorEdit (HSV, with Alpha)\");\r\n        ImGui::Text(\"Color widget HSV with Alpha:\");\r\n        ImGui::ColorEdit4(\"MyColor##2\", (float*)&color, ImGuiColorEditFlags_DisplayHSV | misc_flags);\r\n\r\n        IMGUI_DEMO_MARKER(\"Widgets/Color/ColorEdit (float display)\");\r\n        ImGui::Text(\"Color widget with Float Display:\");\r\n        ImGui::ColorEdit4(\"MyColor##2f\", (float*)&color, ImGuiColorEditFlags_Float | misc_flags);\r\n\r\n        IMGUI_DEMO_MARKER(\"Widgets/Color/ColorButton (with Picker)\");\r\n        ImGui::Text(\"Color button with Picker:\");\r\n        ImGui::SameLine(); HelpMarker(\r\n            \"With the ImGuiColorEditFlags_NoInputs flag you can hide all the slider/text inputs.\\n\"\r\n            \"With the ImGuiColorEditFlags_NoLabel flag you can pass a non-empty label which will only \"\r\n            \"be used for the tooltip and picker popup.\");\r\n        ImGui::ColorEdit4(\"MyColor##3\", (float*)&color, ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | misc_flags);\r\n\r\n        IMGUI_DEMO_MARKER(\"Widgets/Color/ColorButton (with custom Picker popup)\");\r\n        ImGui::Text(\"Color button with Custom Picker Popup:\");\r\n\r\n        // Generate a default palette. The palette will persist and can be edited.\r\n        static bool saved_palette_init = true;\r\n        static ImVec4 saved_palette[32] = {};\r\n        if (saved_palette_init)\r\n        {\r\n            for (int n = 0; n < IM_ARRAYSIZE(saved_palette); n++)\r\n            {\r\n                ImGui::ColorConvertHSVtoRGB(n / 31.0f, 0.8f, 0.8f,\r\n                    saved_palette[n].x, saved_palette[n].y, saved_palette[n].z);\r\n                saved_palette[n].w = 1.0f; // Alpha\r\n            }\r\n            saved_palette_init = false;\r\n        }\r\n\r\n        static ImVec4 backup_color;\r\n        bool open_popup = ImGui::ColorButton(\"MyColor##3b\", color, misc_flags);\r\n        ImGui::SameLine(0, ImGui::GetStyle().ItemInnerSpacing.x);\r\n        open_popup |= ImGui::Button(\"Palette\");\r\n        if (open_popup)\r\n        {\r\n            ImGui::OpenPopup(\"mypicker\");\r\n            backup_color = color;\r\n        }\r\n        if (ImGui::BeginPopup(\"mypicker\"))\r\n        {\r\n            ImGui::Text(\"MY CUSTOM COLOR PICKER WITH AN AMAZING PALETTE!\");\r\n            ImGui::Separator();\r\n            ImGui::ColorPicker4(\"##picker\", (float*)&color, misc_flags | ImGuiColorEditFlags_NoSidePreview | ImGuiColorEditFlags_NoSmallPreview);\r\n            ImGui::SameLine();\r\n\r\n            ImGui::BeginGroup(); // Lock X position\r\n            ImGui::Text(\"Current\");\r\n            ImGui::ColorButton(\"##current\", color, ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_AlphaPreviewHalf, ImVec2(60, 40));\r\n            ImGui::Text(\"Previous\");\r\n            if (ImGui::ColorButton(\"##previous\", backup_color, ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_AlphaPreviewHalf, ImVec2(60, 40)))\r\n                color = backup_color;\r\n            ImGui::Separator();\r\n            ImGui::Text(\"Palette\");\r\n            for (int n = 0; n < IM_ARRAYSIZE(saved_palette); n++)\r\n            {\r\n                ImGui::PushID(n);\r\n                if ((n % 8) != 0)\r\n                    ImGui::SameLine(0.0f, ImGui::GetStyle().ItemSpacing.y);\r\n\r\n                ImGuiColorEditFlags palette_button_flags = ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_NoTooltip;\r\n                if (ImGui::ColorButton(\"##palette\", saved_palette[n], palette_button_flags, ImVec2(20, 20)))\r\n                    color = ImVec4(saved_palette[n].x, saved_palette[n].y, saved_palette[n].z, color.w); // Preserve alpha!\r\n\r\n                // Allow user to drop colors into each palette entry. Note that ColorButton() is already a\r\n                // drag source by default, unless specifying the ImGuiColorEditFlags_NoDragDrop flag.\r\n                if (ImGui::BeginDragDropTarget())\r\n                {\r\n                    if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F))\r\n                        memcpy((float*)&saved_palette[n], payload->Data, sizeof(float) * 3);\r\n                    if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F))\r\n                        memcpy((float*)&saved_palette[n], payload->Data, sizeof(float) * 4);\r\n                    ImGui::EndDragDropTarget();\r\n                }\r\n\r\n                ImGui::PopID();\r\n            }\r\n            ImGui::EndGroup();\r\n            ImGui::EndPopup();\r\n        }\r\n\r\n        IMGUI_DEMO_MARKER(\"Widgets/Color/ColorButton (simple)\");\r\n        ImGui::Text(\"Color button only:\");\r\n        static bool no_border = false;\r\n        ImGui::Checkbox(\"ImGuiColorEditFlags_NoBorder\", &no_border);\r\n        ImGui::ColorButton(\"MyColor##3c\", *(ImVec4*)&color, misc_flags | (no_border ? ImGuiColorEditFlags_NoBorder : 0), ImVec2(80, 80));\r\n\r\n        IMGUI_DEMO_MARKER(\"Widgets/Color/ColorPicker\");\r\n        ImGui::Text(\"Color picker:\");\r\n        static bool alpha = true;\r\n        static bool alpha_bar = true;\r\n        static bool side_preview = true;\r\n        static bool ref_color = false;\r\n        static ImVec4 ref_color_v(1.0f, 0.0f, 1.0f, 0.5f);\r\n        static int display_mode = 0;\r\n        static int picker_mode = 0;\r\n        ImGui::Checkbox(\"With Alpha\", &alpha);\r\n        ImGui::Checkbox(\"With Alpha Bar\", &alpha_bar);\r\n        ImGui::Checkbox(\"With Side Preview\", &side_preview);\r\n        if (side_preview)\r\n        {\r\n            ImGui::SameLine();\r\n            ImGui::Checkbox(\"With Ref Color\", &ref_color);\r\n            if (ref_color)\r\n            {\r\n                ImGui::SameLine();\r\n                ImGui::ColorEdit4(\"##RefColor\", &ref_color_v.x, ImGuiColorEditFlags_NoInputs | misc_flags);\r\n            }\r\n        }\r\n        ImGui::Combo(\"Display Mode\", &display_mode, \"Auto/Current\\0None\\0RGB Only\\0HSV Only\\0Hex Only\\0\");\r\n        ImGui::SameLine(); HelpMarker(\r\n            \"ColorEdit defaults to displaying RGB inputs if you don't specify a display mode, \"\r\n            \"but the user can change it with a right-click.\\n\\nColorPicker defaults to displaying RGB+HSV+Hex \"\r\n            \"if you don't specify a display mode.\\n\\nYou can change the defaults using SetColorEditOptions().\");\r\n        ImGui::Combo(\"Picker Mode\", &picker_mode, \"Auto/Current\\0Hue bar + SV rect\\0Hue wheel + SV triangle\\0\");\r\n        ImGui::SameLine(); HelpMarker(\"User can right-click the picker to change mode.\");\r\n        ImGuiColorEditFlags flags = misc_flags;\r\n        if (!alpha)            flags |= ImGuiColorEditFlags_NoAlpha;        // This is by default if you call ColorPicker3() instead of ColorPicker4()\r\n        if (alpha_bar)         flags |= ImGuiColorEditFlags_AlphaBar;\r\n        if (!side_preview)     flags |= ImGuiColorEditFlags_NoSidePreview;\r\n        if (picker_mode == 1)  flags |= ImGuiColorEditFlags_PickerHueBar;\r\n        if (picker_mode == 2)  flags |= ImGuiColorEditFlags_PickerHueWheel;\r\n        if (display_mode == 1) flags |= ImGuiColorEditFlags_NoInputs;       // Disable all RGB/HSV/Hex displays\r\n        if (display_mode == 2) flags |= ImGuiColorEditFlags_DisplayRGB;     // Override display mode\r\n        if (display_mode == 3) flags |= ImGuiColorEditFlags_DisplayHSV;\r\n        if (display_mode == 4) flags |= ImGuiColorEditFlags_DisplayHex;\r\n        ImGui::ColorPicker4(\"MyColor##4\", (float*)&color, flags, ref_color ? &ref_color_v.x : NULL);\r\n\r\n        ImGui::Text(\"Set defaults in code:\");\r\n        ImGui::SameLine(); HelpMarker(\r\n            \"SetColorEditOptions() is designed to allow you to set boot-time default.\\n\"\r\n            \"We don't have Push/Pop functions because you can force options on a per-widget basis if needed,\"\r\n            \"and the user can change non-forced ones with the options menu.\\nWe don't have a getter to avoid\"\r\n            \"encouraging you to persistently save values that aren't forward-compatible.\");\r\n        if (ImGui::Button(\"Default: Uint8 + HSV + Hue Bar\"))\r\n            ImGui::SetColorEditOptions(ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_PickerHueBar);\r\n        if (ImGui::Button(\"Default: Float + HDR + Hue Wheel\"))\r\n            ImGui::SetColorEditOptions(ImGuiColorEditFlags_Float | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_PickerHueWheel);\r\n\r\n        // HSV encoded support (to avoid RGB<>HSV round trips and singularities when S==0 or V==0)\r\n        static ImVec4 color_hsv(0.23f, 1.0f, 1.0f, 1.0f); // Stored as HSV!\r\n        ImGui::Spacing();\r\n        ImGui::Text(\"HSV encoded colors\");\r\n        ImGui::SameLine(); HelpMarker(\r\n            \"By default, colors are given to ColorEdit and ColorPicker in RGB, but ImGuiColorEditFlags_InputHSV\"\r\n            \"allows you to store colors as HSV and pass them to ColorEdit and ColorPicker as HSV. This comes with the\"\r\n            \"added benefit that you can manipulate hue values with the picker even when saturation or value are zero.\");\r\n        ImGui::Text(\"Color widget with InputHSV:\");\r\n        ImGui::ColorEdit4(\"HSV shown as RGB##1\", (float*)&color_hsv, ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_InputHSV | ImGuiColorEditFlags_Float);\r\n        ImGui::ColorEdit4(\"HSV shown as HSV##1\", (float*)&color_hsv, ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_InputHSV | ImGuiColorEditFlags_Float);\r\n        ImGui::DragFloat4(\"Raw HSV values\", (float*)&color_hsv, 0.01f, 0.0f, 1.0f);\r\n\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    IMGUI_DEMO_MARKER(\"Widgets/Drag and Slider Flags\");\r\n    if (ImGui::TreeNode(\"Drag/Slider Flags\"))\r\n    {\r\n        // Demonstrate using advanced flags for DragXXX and SliderXXX functions. Note that the flags are the same!\r\n        static ImGuiSliderFlags flags = ImGuiSliderFlags_None;\r\n        ImGui::CheckboxFlags(\"ImGuiSliderFlags_AlwaysClamp\", &flags, ImGuiSliderFlags_AlwaysClamp);\r\n        ImGui::SameLine(); HelpMarker(\"Always clamp value to min/max bounds (if any) when input manually with CTRL+Click.\");\r\n        ImGui::CheckboxFlags(\"ImGuiSliderFlags_Logarithmic\", &flags, ImGuiSliderFlags_Logarithmic);\r\n        ImGui::SameLine(); HelpMarker(\"Enable logarithmic editing (more precision for small values).\");\r\n        ImGui::CheckboxFlags(\"ImGuiSliderFlags_NoRoundToFormat\", &flags, ImGuiSliderFlags_NoRoundToFormat);\r\n        ImGui::SameLine(); HelpMarker(\"Disable rounding underlying value to match precision of the format string (e.g. %.3f values are rounded to those 3 digits).\");\r\n        ImGui::CheckboxFlags(\"ImGuiSliderFlags_NoInput\", &flags, ImGuiSliderFlags_NoInput);\r\n        ImGui::SameLine(); HelpMarker(\"Disable CTRL+Click or Enter key allowing to input text directly into the widget.\");\r\n\r\n        // Drags\r\n        static float drag_f = 0.5f;\r\n        static int drag_i = 50;\r\n        ImGui::Text(\"Underlying float value: %f\", drag_f);\r\n        ImGui::DragFloat(\"DragFloat (0 -> 1)\", &drag_f, 0.005f, 0.0f, 1.0f, \"%.3f\", flags);\r\n        ImGui::DragFloat(\"DragFloat (0 -> +inf)\", &drag_f, 0.005f, 0.0f, FLT_MAX, \"%.3f\", flags);\r\n        ImGui::DragFloat(\"DragFloat (-inf -> 1)\", &drag_f, 0.005f, -FLT_MAX, 1.0f, \"%.3f\", flags);\r\n        ImGui::DragFloat(\"DragFloat (-inf -> +inf)\", &drag_f, 0.005f, -FLT_MAX, +FLT_MAX, \"%.3f\", flags);\r\n        ImGui::DragInt(\"DragInt (0 -> 100)\", &drag_i, 0.5f, 0, 100, \"%d\", flags);\r\n\r\n        // Sliders\r\n        static float slider_f = 0.5f;\r\n        static int slider_i = 50;\r\n        ImGui::Text(\"Underlying float value: %f\", slider_f);\r\n        ImGui::SliderFloat(\"SliderFloat (0 -> 1)\", &slider_f, 0.0f, 1.0f, \"%.3f\", flags);\r\n        ImGui::SliderInt(\"SliderInt (0 -> 100)\", &slider_i, 0, 100, \"%d\", flags);\r\n\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    IMGUI_DEMO_MARKER(\"Widgets/Range Widgets\");\r\n    if (ImGui::TreeNode(\"Range Widgets\"))\r\n    {\r\n        static float begin = 10, end = 90;\r\n        static int begin_i = 100, end_i = 1000;\r\n        ImGui::DragFloatRange2(\"range float\", &begin, &end, 0.25f, 0.0f, 100.0f, \"Min: %.1f %%\", \"Max: %.1f %%\", ImGuiSliderFlags_AlwaysClamp);\r\n        ImGui::DragIntRange2(\"range int\", &begin_i, &end_i, 5, 0, 1000, \"Min: %d units\", \"Max: %d units\");\r\n        ImGui::DragIntRange2(\"range int (no bounds)\", &begin_i, &end_i, 5, 0, 0, \"Min: %d units\", \"Max: %d units\");\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    IMGUI_DEMO_MARKER(\"Widgets/Data Types\");\r\n    if (ImGui::TreeNode(\"Data Types\"))\r\n    {\r\n        // DragScalar/InputScalar/SliderScalar functions allow various data types\r\n        // - signed/unsigned\r\n        // - 8/16/32/64-bits\r\n        // - integer/float/double\r\n        // To avoid polluting the public API with all possible combinations, we use the ImGuiDataType enum\r\n        // to pass the type, and passing all arguments by pointer.\r\n        // This is the reason the test code below creates local variables to hold \"zero\" \"one\" etc. for each types.\r\n        // In practice, if you frequently use a given type that is not covered by the normal API entry points,\r\n        // you can wrap it yourself inside a 1 line function which can take typed argument as value instead of void*,\r\n        // and then pass their address to the generic function. For example:\r\n        //   bool MySliderU64(const char *label, u64* value, u64 min = 0, u64 max = 0, const char* format = \"%lld\")\r\n        //   {\r\n        //      return SliderScalar(label, ImGuiDataType_U64, value, &min, &max, format);\r\n        //   }\r\n\r\n        // Setup limits (as helper variables so we can take their address, as explained above)\r\n        // Note: SliderScalar() functions have a maximum usable range of half the natural type maximum, hence the /2.\r\n        #ifndef LLONG_MIN\r\n        ImS64 LLONG_MIN = -9223372036854775807LL - 1;\r\n        ImS64 LLONG_MAX = 9223372036854775807LL;\r\n        ImU64 ULLONG_MAX = (2ULL * 9223372036854775807LL + 1);\r\n        #endif\r\n        const char    s8_zero  = 0,   s8_one  = 1,   s8_fifty  = 50, s8_min  = -128,        s8_max = 127;\r\n        const ImU8    u8_zero  = 0,   u8_one  = 1,   u8_fifty  = 50, u8_min  = 0,           u8_max = 255;\r\n        const short   s16_zero = 0,   s16_one = 1,   s16_fifty = 50, s16_min = -32768,      s16_max = 32767;\r\n        const ImU16   u16_zero = 0,   u16_one = 1,   u16_fifty = 50, u16_min = 0,           u16_max = 65535;\r\n        const ImS32   s32_zero = 0,   s32_one = 1,   s32_fifty = 50, s32_min = INT_MIN/2,   s32_max = INT_MAX/2,    s32_hi_a = INT_MAX/2 - 100,    s32_hi_b = INT_MAX/2;\r\n        const ImU32   u32_zero = 0,   u32_one = 1,   u32_fifty = 50, u32_min = 0,           u32_max = UINT_MAX/2,   u32_hi_a = UINT_MAX/2 - 100,   u32_hi_b = UINT_MAX/2;\r\n        const ImS64   s64_zero = 0,   s64_one = 1,   s64_fifty = 50, s64_min = LLONG_MIN/2, s64_max = LLONG_MAX/2,  s64_hi_a = LLONG_MAX/2 - 100,  s64_hi_b = LLONG_MAX/2;\r\n        const ImU64   u64_zero = 0,   u64_one = 1,   u64_fifty = 50, u64_min = 0,           u64_max = ULLONG_MAX/2, u64_hi_a = ULLONG_MAX/2 - 100, u64_hi_b = ULLONG_MAX/2;\r\n        const float   f32_zero = 0.f, f32_one = 1.f, f32_lo_a = -10000000000.0f, f32_hi_a = +10000000000.0f;\r\n        const double  f64_zero = 0.,  f64_one = 1.,  f64_lo_a = -1000000000000000.0, f64_hi_a = +1000000000000000.0;\r\n\r\n        // State\r\n        static char   s8_v  = 127;\r\n        static ImU8   u8_v  = 255;\r\n        static short  s16_v = 32767;\r\n        static ImU16  u16_v = 65535;\r\n        static ImS32  s32_v = -1;\r\n        static ImU32  u32_v = (ImU32)-1;\r\n        static ImS64  s64_v = -1;\r\n        static ImU64  u64_v = (ImU64)-1;\r\n        static float  f32_v = 0.123f;\r\n        static double f64_v = 90000.01234567890123456789;\r\n\r\n        const float drag_speed = 0.2f;\r\n        static bool drag_clamp = false;\r\n        IMGUI_DEMO_MARKER(\"Widgets/Data Types/Drags\");\r\n        ImGui::Text(\"Drags:\");\r\n        ImGui::Checkbox(\"Clamp integers to 0..50\", &drag_clamp);\r\n        ImGui::SameLine(); HelpMarker(\r\n            \"As with every widgets in dear imgui, we never modify values unless there is a user interaction.\\n\"\r\n            \"You can override the clamping limits by using CTRL+Click to input a value.\");\r\n        ImGui::DragScalar(\"drag s8\",        ImGuiDataType_S8,     &s8_v,  drag_speed, drag_clamp ? &s8_zero  : NULL, drag_clamp ? &s8_fifty  : NULL);\r\n        ImGui::DragScalar(\"drag u8\",        ImGuiDataType_U8,     &u8_v,  drag_speed, drag_clamp ? &u8_zero  : NULL, drag_clamp ? &u8_fifty  : NULL, \"%u ms\");\r\n        ImGui::DragScalar(\"drag s16\",       ImGuiDataType_S16,    &s16_v, drag_speed, drag_clamp ? &s16_zero : NULL, drag_clamp ? &s16_fifty : NULL);\r\n        ImGui::DragScalar(\"drag u16\",       ImGuiDataType_U16,    &u16_v, drag_speed, drag_clamp ? &u16_zero : NULL, drag_clamp ? &u16_fifty : NULL, \"%u ms\");\r\n        ImGui::DragScalar(\"drag s32\",       ImGuiDataType_S32,    &s32_v, drag_speed, drag_clamp ? &s32_zero : NULL, drag_clamp ? &s32_fifty : NULL);\r\n        ImGui::DragScalar(\"drag u32\",       ImGuiDataType_U32,    &u32_v, drag_speed, drag_clamp ? &u32_zero : NULL, drag_clamp ? &u32_fifty : NULL, \"%u ms\");\r\n        ImGui::DragScalar(\"drag s64\",       ImGuiDataType_S64,    &s64_v, drag_speed, drag_clamp ? &s64_zero : NULL, drag_clamp ? &s64_fifty : NULL);\r\n        ImGui::DragScalar(\"drag u64\",       ImGuiDataType_U64,    &u64_v, drag_speed, drag_clamp ? &u64_zero : NULL, drag_clamp ? &u64_fifty : NULL);\r\n        ImGui::DragScalar(\"drag float\",     ImGuiDataType_Float,  &f32_v, 0.005f,  &f32_zero, &f32_one, \"%f\");\r\n        ImGui::DragScalar(\"drag float log\", ImGuiDataType_Float,  &f32_v, 0.005f,  &f32_zero, &f32_one, \"%f\", ImGuiSliderFlags_Logarithmic);\r\n        ImGui::DragScalar(\"drag double\",    ImGuiDataType_Double, &f64_v, 0.0005f, &f64_zero, NULL,     \"%.10f grams\");\r\n        ImGui::DragScalar(\"drag double log\",ImGuiDataType_Double, &f64_v, 0.0005f, &f64_zero, &f64_one, \"0 < %.10f < 1\", ImGuiSliderFlags_Logarithmic);\r\n\r\n        IMGUI_DEMO_MARKER(\"Widgets/Data Types/Sliders\");\r\n        ImGui::Text(\"Sliders\");\r\n        ImGui::SliderScalar(\"slider s8 full\",       ImGuiDataType_S8,     &s8_v,  &s8_min,   &s8_max,   \"%d\");\r\n        ImGui::SliderScalar(\"slider u8 full\",       ImGuiDataType_U8,     &u8_v,  &u8_min,   &u8_max,   \"%u\");\r\n        ImGui::SliderScalar(\"slider s16 full\",      ImGuiDataType_S16,    &s16_v, &s16_min,  &s16_max,  \"%d\");\r\n        ImGui::SliderScalar(\"slider u16 full\",      ImGuiDataType_U16,    &u16_v, &u16_min,  &u16_max,  \"%u\");\r\n        ImGui::SliderScalar(\"slider s32 low\",       ImGuiDataType_S32,    &s32_v, &s32_zero, &s32_fifty,\"%d\");\r\n        ImGui::SliderScalar(\"slider s32 high\",      ImGuiDataType_S32,    &s32_v, &s32_hi_a, &s32_hi_b, \"%d\");\r\n        ImGui::SliderScalar(\"slider s32 full\",      ImGuiDataType_S32,    &s32_v, &s32_min,  &s32_max,  \"%d\");\r\n        ImGui::SliderScalar(\"slider u32 low\",       ImGuiDataType_U32,    &u32_v, &u32_zero, &u32_fifty,\"%u\");\r\n        ImGui::SliderScalar(\"slider u32 high\",      ImGuiDataType_U32,    &u32_v, &u32_hi_a, &u32_hi_b, \"%u\");\r\n        ImGui::SliderScalar(\"slider u32 full\",      ImGuiDataType_U32,    &u32_v, &u32_min,  &u32_max,  \"%u\");\r\n        ImGui::SliderScalar(\"slider s64 low\",       ImGuiDataType_S64,    &s64_v, &s64_zero, &s64_fifty,\"%\" IM_PRId64);\r\n        ImGui::SliderScalar(\"slider s64 high\",      ImGuiDataType_S64,    &s64_v, &s64_hi_a, &s64_hi_b, \"%\" IM_PRId64);\r\n        ImGui::SliderScalar(\"slider s64 full\",      ImGuiDataType_S64,    &s64_v, &s64_min,  &s64_max,  \"%\" IM_PRId64);\r\n        ImGui::SliderScalar(\"slider u64 low\",       ImGuiDataType_U64,    &u64_v, &u64_zero, &u64_fifty,\"%\" IM_PRIu64 \" ms\");\r\n        ImGui::SliderScalar(\"slider u64 high\",      ImGuiDataType_U64,    &u64_v, &u64_hi_a, &u64_hi_b, \"%\" IM_PRIu64 \" ms\");\r\n        ImGui::SliderScalar(\"slider u64 full\",      ImGuiDataType_U64,    &u64_v, &u64_min,  &u64_max,  \"%\" IM_PRIu64 \" ms\");\r\n        ImGui::SliderScalar(\"slider float low\",     ImGuiDataType_Float,  &f32_v, &f32_zero, &f32_one);\r\n        ImGui::SliderScalar(\"slider float low log\", ImGuiDataType_Float,  &f32_v, &f32_zero, &f32_one,  \"%.10f\", ImGuiSliderFlags_Logarithmic);\r\n        ImGui::SliderScalar(\"slider float high\",    ImGuiDataType_Float,  &f32_v, &f32_lo_a, &f32_hi_a, \"%e\");\r\n        ImGui::SliderScalar(\"slider double low\",    ImGuiDataType_Double, &f64_v, &f64_zero, &f64_one,  \"%.10f grams\");\r\n        ImGui::SliderScalar(\"slider double low log\",ImGuiDataType_Double, &f64_v, &f64_zero, &f64_one,  \"%.10f\", ImGuiSliderFlags_Logarithmic);\r\n        ImGui::SliderScalar(\"slider double high\",   ImGuiDataType_Double, &f64_v, &f64_lo_a, &f64_hi_a, \"%e grams\");\r\n\r\n        ImGui::Text(\"Sliders (reverse)\");\r\n        ImGui::SliderScalar(\"slider s8 reverse\",    ImGuiDataType_S8,   &s8_v,  &s8_max,    &s8_min,   \"%d\");\r\n        ImGui::SliderScalar(\"slider u8 reverse\",    ImGuiDataType_U8,   &u8_v,  &u8_max,    &u8_min,   \"%u\");\r\n        ImGui::SliderScalar(\"slider s32 reverse\",   ImGuiDataType_S32,  &s32_v, &s32_fifty, &s32_zero, \"%d\");\r\n        ImGui::SliderScalar(\"slider u32 reverse\",   ImGuiDataType_U32,  &u32_v, &u32_fifty, &u32_zero, \"%u\");\r\n        ImGui::SliderScalar(\"slider s64 reverse\",   ImGuiDataType_S64,  &s64_v, &s64_fifty, &s64_zero, \"%\" IM_PRId64);\r\n        ImGui::SliderScalar(\"slider u64 reverse\",   ImGuiDataType_U64,  &u64_v, &u64_fifty, &u64_zero, \"%\" IM_PRIu64 \" ms\");\r\n\r\n        IMGUI_DEMO_MARKER(\"Widgets/Data Types/Inputs\");\r\n        static bool inputs_step = true;\r\n        ImGui::Text(\"Inputs\");\r\n        ImGui::Checkbox(\"Show step buttons\", &inputs_step);\r\n        ImGui::InputScalar(\"input s8\",      ImGuiDataType_S8,     &s8_v,  inputs_step ? &s8_one  : NULL, NULL, \"%d\");\r\n        ImGui::InputScalar(\"input u8\",      ImGuiDataType_U8,     &u8_v,  inputs_step ? &u8_one  : NULL, NULL, \"%u\");\r\n        ImGui::InputScalar(\"input s16\",     ImGuiDataType_S16,    &s16_v, inputs_step ? &s16_one : NULL, NULL, \"%d\");\r\n        ImGui::InputScalar(\"input u16\",     ImGuiDataType_U16,    &u16_v, inputs_step ? &u16_one : NULL, NULL, \"%u\");\r\n        ImGui::InputScalar(\"input s32\",     ImGuiDataType_S32,    &s32_v, inputs_step ? &s32_one : NULL, NULL, \"%d\");\r\n        ImGui::InputScalar(\"input s32 hex\", ImGuiDataType_S32,    &s32_v, inputs_step ? &s32_one : NULL, NULL, \"%08X\", ImGuiInputTextFlags_CharsHexadecimal);\r\n        ImGui::InputScalar(\"input u32\",     ImGuiDataType_U32,    &u32_v, inputs_step ? &u32_one : NULL, NULL, \"%u\");\r\n        ImGui::InputScalar(\"input u32 hex\", ImGuiDataType_U32,    &u32_v, inputs_step ? &u32_one : NULL, NULL, \"%08X\", ImGuiInputTextFlags_CharsHexadecimal);\r\n        ImGui::InputScalar(\"input s64\",     ImGuiDataType_S64,    &s64_v, inputs_step ? &s64_one : NULL);\r\n        ImGui::InputScalar(\"input u64\",     ImGuiDataType_U64,    &u64_v, inputs_step ? &u64_one : NULL);\r\n        ImGui::InputScalar(\"input float\",   ImGuiDataType_Float,  &f32_v, inputs_step ? &f32_one : NULL);\r\n        ImGui::InputScalar(\"input double\",  ImGuiDataType_Double, &f64_v, inputs_step ? &f64_one : NULL);\r\n\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    IMGUI_DEMO_MARKER(\"Widgets/Multi-component Widgets\");\r\n    if (ImGui::TreeNode(\"Multi-component Widgets\"))\r\n    {\r\n        static float vec4f[4] = { 0.10f, 0.20f, 0.30f, 0.44f };\r\n        static int vec4i[4] = { 1, 5, 100, 255 };\r\n\r\n        ImGui::InputFloat2(\"input float2\", vec4f);\r\n        ImGui::DragFloat2(\"drag float2\", vec4f, 0.01f, 0.0f, 1.0f);\r\n        ImGui::SliderFloat2(\"slider float2\", vec4f, 0.0f, 1.0f);\r\n        ImGui::InputInt2(\"input int2\", vec4i);\r\n        ImGui::DragInt2(\"drag int2\", vec4i, 1, 0, 255);\r\n        ImGui::SliderInt2(\"slider int2\", vec4i, 0, 255);\r\n        ImGui::Spacing();\r\n\r\n        ImGui::InputFloat3(\"input float3\", vec4f);\r\n        ImGui::DragFloat3(\"drag float3\", vec4f, 0.01f, 0.0f, 1.0f);\r\n        ImGui::SliderFloat3(\"slider float3\", vec4f, 0.0f, 1.0f);\r\n        ImGui::InputInt3(\"input int3\", vec4i);\r\n        ImGui::DragInt3(\"drag int3\", vec4i, 1, 0, 255);\r\n        ImGui::SliderInt3(\"slider int3\", vec4i, 0, 255);\r\n        ImGui::Spacing();\r\n\r\n        ImGui::InputFloat4(\"input float4\", vec4f);\r\n        ImGui::DragFloat4(\"drag float4\", vec4f, 0.01f, 0.0f, 1.0f);\r\n        ImGui::SliderFloat4(\"slider float4\", vec4f, 0.0f, 1.0f);\r\n        ImGui::InputInt4(\"input int4\", vec4i);\r\n        ImGui::DragInt4(\"drag int4\", vec4i, 1, 0, 255);\r\n        ImGui::SliderInt4(\"slider int4\", vec4i, 0, 255);\r\n\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    IMGUI_DEMO_MARKER(\"Widgets/Vertical Sliders\");\r\n    if (ImGui::TreeNode(\"Vertical Sliders\"))\r\n    {\r\n        const float spacing = 4;\r\n        ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(spacing, spacing));\r\n\r\n        static int int_value = 0;\r\n        ImGui::VSliderInt(\"##int\", ImVec2(18, 160), &int_value, 0, 5);\r\n        ImGui::SameLine();\r\n\r\n        static float values[7] = { 0.0f, 0.60f, 0.35f, 0.9f, 0.70f, 0.20f, 0.0f };\r\n        ImGui::PushID(\"set1\");\r\n        for (int i = 0; i < 7; i++)\r\n        {\r\n            if (i > 0) ImGui::SameLine();\r\n            ImGui::PushID(i);\r\n            ImGui::PushStyleColor(ImGuiCol_FrameBg, (ImVec4)ImColor::HSV(i / 7.0f, 0.5f, 0.5f));\r\n            ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, (ImVec4)ImColor::HSV(i / 7.0f, 0.6f, 0.5f));\r\n            ImGui::PushStyleColor(ImGuiCol_FrameBgActive, (ImVec4)ImColor::HSV(i / 7.0f, 0.7f, 0.5f));\r\n            ImGui::PushStyleColor(ImGuiCol_SliderGrab, (ImVec4)ImColor::HSV(i / 7.0f, 0.9f, 0.9f));\r\n            ImGui::VSliderFloat(\"##v\", ImVec2(18, 160), &values[i], 0.0f, 1.0f, \"\");\r\n            if (ImGui::IsItemActive() || ImGui::IsItemHovered())\r\n                ImGui::SetTooltip(\"%.3f\", values[i]);\r\n            ImGui::PopStyleColor(4);\r\n            ImGui::PopID();\r\n        }\r\n        ImGui::PopID();\r\n\r\n        ImGui::SameLine();\r\n        ImGui::PushID(\"set2\");\r\n        static float values2[4] = { 0.20f, 0.80f, 0.40f, 0.25f };\r\n        const int rows = 3;\r\n        const ImVec2 small_slider_size(18, (float)(int)((160.0f - (rows - 1) * spacing) / rows));\r\n        for (int nx = 0; nx < 4; nx++)\r\n        {\r\n            if (nx > 0) ImGui::SameLine();\r\n            ImGui::BeginGroup();\r\n            for (int ny = 0; ny < rows; ny++)\r\n            {\r\n                ImGui::PushID(nx * rows + ny);\r\n                ImGui::VSliderFloat(\"##v\", small_slider_size, &values2[nx], 0.0f, 1.0f, \"\");\r\n                if (ImGui::IsItemActive() || ImGui::IsItemHovered())\r\n                    ImGui::SetTooltip(\"%.3f\", values2[nx]);\r\n                ImGui::PopID();\r\n            }\r\n            ImGui::EndGroup();\r\n        }\r\n        ImGui::PopID();\r\n\r\n        ImGui::SameLine();\r\n        ImGui::PushID(\"set3\");\r\n        for (int i = 0; i < 4; i++)\r\n        {\r\n            if (i > 0) ImGui::SameLine();\r\n            ImGui::PushID(i);\r\n            ImGui::PushStyleVar(ImGuiStyleVar_GrabMinSize, 40);\r\n            ImGui::VSliderFloat(\"##v\", ImVec2(40, 160), &values[i], 0.0f, 1.0f, \"%.2f\\nsec\");\r\n            ImGui::PopStyleVar();\r\n            ImGui::PopID();\r\n        }\r\n        ImGui::PopID();\r\n        ImGui::PopStyleVar();\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    IMGUI_DEMO_MARKER(\"Widgets/Drag and drop\");\r\n    if (ImGui::TreeNode(\"Drag and Drop\"))\r\n    {\r\n        IMGUI_DEMO_MARKER(\"Widgets/Drag and drop/Standard widgets\");\r\n        if (ImGui::TreeNode(\"Drag and drop in standard widgets\"))\r\n        {\r\n            // ColorEdit widgets automatically act as drag source and drag target.\r\n            // They are using standardized payload strings IMGUI_PAYLOAD_TYPE_COLOR_3F and IMGUI_PAYLOAD_TYPE_COLOR_4F\r\n            // to allow your own widgets to use colors in their drag and drop interaction.\r\n            // Also see 'Demo->Widgets->Color/Picker Widgets->Palette' demo.\r\n            HelpMarker(\"You can drag from the color squares.\");\r\n            static float col1[3] = { 1.0f, 0.0f, 0.2f };\r\n            static float col2[4] = { 0.4f, 0.7f, 0.0f, 0.5f };\r\n            ImGui::ColorEdit3(\"color 1\", col1);\r\n            ImGui::ColorEdit4(\"color 2\", col2);\r\n            ImGui::TreePop();\r\n        }\r\n\r\n        IMGUI_DEMO_MARKER(\"Widgets/Drag and drop/Copy-swap items\");\r\n        if (ImGui::TreeNode(\"Drag and drop to copy/swap items\"))\r\n        {\r\n            enum Mode\r\n            {\r\n                Mode_Copy,\r\n                Mode_Move,\r\n                Mode_Swap\r\n            };\r\n            static int mode = 0;\r\n            if (ImGui::RadioButton(\"Copy\", mode == Mode_Copy)) { mode = Mode_Copy; } ImGui::SameLine();\r\n            if (ImGui::RadioButton(\"Move\", mode == Mode_Move)) { mode = Mode_Move; } ImGui::SameLine();\r\n            if (ImGui::RadioButton(\"Swap\", mode == Mode_Swap)) { mode = Mode_Swap; }\r\n            static const char* names[9] =\r\n            {\r\n                \"Bobby\", \"Beatrice\", \"Betty\",\r\n                \"Brianna\", \"Barry\", \"Bernard\",\r\n                \"Bibi\", \"Blaine\", \"Bryn\"\r\n            };\r\n            for (int n = 0; n < IM_ARRAYSIZE(names); n++)\r\n            {\r\n                ImGui::PushID(n);\r\n                if ((n % 3) != 0)\r\n                    ImGui::SameLine();\r\n                ImGui::Button(names[n], ImVec2(60, 60));\r\n\r\n                // Our buttons are both drag sources and drag targets here!\r\n                if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_None))\r\n                {\r\n                    // Set payload to carry the index of our item (could be anything)\r\n                    ImGui::SetDragDropPayload(\"DND_DEMO_CELL\", &n, sizeof(int));\r\n\r\n                    // Display preview (could be anything, e.g. when dragging an image we could decide to display\r\n                    // the filename and a small preview of the image, etc.)\r\n                    if (mode == Mode_Copy) { ImGui::Text(\"Copy %s\", names[n]); }\r\n                    if (mode == Mode_Move) { ImGui::Text(\"Move %s\", names[n]); }\r\n                    if (mode == Mode_Swap) { ImGui::Text(\"Swap %s\", names[n]); }\r\n                    ImGui::EndDragDropSource();\r\n                }\r\n                if (ImGui::BeginDragDropTarget())\r\n                {\r\n                    if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload(\"DND_DEMO_CELL\"))\r\n                    {\r\n                        IM_ASSERT(payload->DataSize == sizeof(int));\r\n                        int payload_n = *(const int*)payload->Data;\r\n                        if (mode == Mode_Copy)\r\n                        {\r\n                            names[n] = names[payload_n];\r\n                        }\r\n                        if (mode == Mode_Move)\r\n                        {\r\n                            names[n] = names[payload_n];\r\n                            names[payload_n] = \"\";\r\n                        }\r\n                        if (mode == Mode_Swap)\r\n                        {\r\n                            const char* tmp = names[n];\r\n                            names[n] = names[payload_n];\r\n                            names[payload_n] = tmp;\r\n                        }\r\n                    }\r\n                    ImGui::EndDragDropTarget();\r\n                }\r\n                ImGui::PopID();\r\n            }\r\n            ImGui::TreePop();\r\n        }\r\n\r\n        IMGUI_DEMO_MARKER(\"Widgets/Drag and Drop/Drag to reorder items (simple)\");\r\n        if (ImGui::TreeNode(\"Drag to reorder items (simple)\"))\r\n        {\r\n            // Simple reordering\r\n            HelpMarker(\r\n                \"We don't use the drag and drop api at all here! \"\r\n                \"Instead we query when the item is held but not hovered, and order items accordingly.\");\r\n            static const char* item_names[] = { \"Item One\", \"Item Two\", \"Item Three\", \"Item Four\", \"Item Five\" };\r\n            for (int n = 0; n < IM_ARRAYSIZE(item_names); n++)\r\n            {\r\n                const char* item = item_names[n];\r\n                ImGui::Selectable(item);\r\n\r\n                if (ImGui::IsItemActive() && !ImGui::IsItemHovered())\r\n                {\r\n                    int n_next = n + (ImGui::GetMouseDragDelta(0).y < 0.f ? -1 : 1);\r\n                    if (n_next >= 0 && n_next < IM_ARRAYSIZE(item_names))\r\n                    {\r\n                        item_names[n] = item_names[n_next];\r\n                        item_names[n_next] = item;\r\n                        ImGui::ResetMouseDragDelta();\r\n                    }\r\n                }\r\n            }\r\n            ImGui::TreePop();\r\n        }\r\n\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    IMGUI_DEMO_MARKER(\"Widgets/Querying Item Status (Edited,Active,Hovered etc.)\");\r\n    if (ImGui::TreeNode(\"Querying Item Status (Edited/Active/Hovered etc.)\"))\r\n    {\r\n        // Select an item type\r\n        const char* item_names[] =\r\n        {\r\n            \"Text\", \"Button\", \"Button (w/ repeat)\", \"Checkbox\", \"SliderFloat\", \"InputText\", \"InputTextMultiline\", \"InputFloat\",\r\n            \"InputFloat3\", \"ColorEdit4\", \"Selectable\", \"MenuItem\", \"TreeNode\", \"TreeNode (w/ double-click)\", \"Combo\", \"ListBox\"\r\n        };\r\n        static int item_type = 4;\r\n        static bool item_disabled = false;\r\n        ImGui::Combo(\"Item Type\", &item_type, item_names, IM_ARRAYSIZE(item_names), IM_ARRAYSIZE(item_names));\r\n        ImGui::SameLine();\r\n        HelpMarker(\"Testing how various types of items are interacting with the IsItemXXX functions. Note that the bool return value of most ImGui function is generally equivalent to calling ImGui::IsItemHovered().\");\r\n        ImGui::Checkbox(\"Item Disabled\",  &item_disabled);\r\n\r\n        // Submit selected item item so we can query their status in the code following it.\r\n        bool ret = false;\r\n        static bool b = false;\r\n        static float col4f[4] = { 1.0f, 0.5, 0.0f, 1.0f };\r\n        static char str[16] = {};\r\n        if (item_disabled)\r\n            ImGui::BeginDisabled(true);\r\n        if (item_type == 0) { ImGui::Text(\"ITEM: Text\"); }                                              // Testing text items with no identifier/interaction\r\n        if (item_type == 1) { ret = ImGui::Button(\"ITEM: Button\"); }                                    // Testing button\r\n        if (item_type == 2) { ImGui::PushButtonRepeat(true); ret = ImGui::Button(\"ITEM: Button\"); ImGui::PopButtonRepeat(); } // Testing button (with repeater)\r\n        if (item_type == 3) { ret = ImGui::Checkbox(\"ITEM: Checkbox\", &b); }                            // Testing checkbox\r\n        if (item_type == 4) { ret = ImGui::SliderFloat(\"ITEM: SliderFloat\", &col4f[0], 0.0f, 1.0f); }   // Testing basic item\r\n        if (item_type == 5) { ret = ImGui::InputText(\"ITEM: InputText\", &str[0], IM_ARRAYSIZE(str)); }  // Testing input text (which handles tabbing)\r\n        if (item_type == 6) { ret = ImGui::InputTextMultiline(\"ITEM: InputTextMultiline\", &str[0], IM_ARRAYSIZE(str)); } // Testing input text (which uses a child window)\r\n        if (item_type == 7) { ret = ImGui::InputFloat(\"ITEM: InputFloat\", col4f, 1.0f); }               // Testing +/- buttons on scalar input\r\n        if (item_type == 8) { ret = ImGui::InputFloat3(\"ITEM: InputFloat3\", col4f); }                   // Testing multi-component items (IsItemXXX flags are reported merged)\r\n        if (item_type == 9) { ret = ImGui::ColorEdit4(\"ITEM: ColorEdit4\", col4f); }                     // Testing multi-component items (IsItemXXX flags are reported merged)\r\n        if (item_type == 10){ ret = ImGui::Selectable(\"ITEM: Selectable\"); }                            // Testing selectable item\r\n        if (item_type == 11){ ret = ImGui::MenuItem(\"ITEM: MenuItem\"); }                                // Testing menu item (they use ImGuiButtonFlags_PressedOnRelease button policy)\r\n        if (item_type == 12){ ret = ImGui::TreeNode(\"ITEM: TreeNode\"); if (ret) ImGui::TreePop(); }     // Testing tree node\r\n        if (item_type == 13){ ret = ImGui::TreeNodeEx(\"ITEM: TreeNode w/ ImGuiTreeNodeFlags_OpenOnDoubleClick\", ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_NoTreePushOnOpen); } // Testing tree node with ImGuiButtonFlags_PressedOnDoubleClick button policy.\r\n        if (item_type == 14){ const char* items[] = { \"Apple\", \"Banana\", \"Cherry\", \"Kiwi\" }; static int current = 1; ret = ImGui::Combo(\"ITEM: Combo\", &current, items, IM_ARRAYSIZE(items)); }\r\n        if (item_type == 15){ const char* items[] = { \"Apple\", \"Banana\", \"Cherry\", \"Kiwi\" }; static int current = 1; ret = ImGui::ListBox(\"ITEM: ListBox\", &current, items, IM_ARRAYSIZE(items), IM_ARRAYSIZE(items)); }\r\n\r\n        // Display the values of IsItemHovered() and other common item state functions.\r\n        // Note that the ImGuiHoveredFlags_XXX flags can be combined.\r\n        // Because BulletText is an item itself and that would affect the output of IsItemXXX functions,\r\n        // we query every state in a single call to avoid storing them and to simplify the code.\r\n        ImGui::BulletText(\r\n            \"Return value = %d\\n\"\r\n            \"IsItemFocused() = %d\\n\"\r\n            \"IsItemHovered() = %d\\n\"\r\n            \"IsItemHovered(_AllowWhenBlockedByPopup) = %d\\n\"\r\n            \"IsItemHovered(_AllowWhenBlockedByActiveItem) = %d\\n\"\r\n            \"IsItemHovered(_AllowWhenOverlapped) = %d\\n\"\r\n            \"IsItemHovered(_AllowWhenDisabled) = %d\\n\"\r\n            \"IsItemHovered(_RectOnly) = %d\\n\"\r\n            \"IsItemActive() = %d\\n\"\r\n            \"IsItemEdited() = %d\\n\"\r\n            \"IsItemActivated() = %d\\n\"\r\n            \"IsItemDeactivated() = %d\\n\"\r\n            \"IsItemDeactivatedAfterEdit() = %d\\n\"\r\n            \"IsItemVisible() = %d\\n\"\r\n            \"IsItemClicked() = %d\\n\"\r\n            \"IsItemToggledOpen() = %d\\n\"\r\n            \"GetItemRectMin() = (%.1f, %.1f)\\n\"\r\n            \"GetItemRectMax() = (%.1f, %.1f)\\n\"\r\n            \"GetItemRectSize() = (%.1f, %.1f)\",\r\n            ret,\r\n            ImGui::IsItemFocused(),\r\n            ImGui::IsItemHovered(),\r\n            ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup),\r\n            ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem),\r\n            ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenOverlapped),\r\n            ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled),\r\n            ImGui::IsItemHovered(ImGuiHoveredFlags_RectOnly),\r\n            ImGui::IsItemActive(),\r\n            ImGui::IsItemEdited(),\r\n            ImGui::IsItemActivated(),\r\n            ImGui::IsItemDeactivated(),\r\n            ImGui::IsItemDeactivatedAfterEdit(),\r\n            ImGui::IsItemVisible(),\r\n            ImGui::IsItemClicked(),\r\n            ImGui::IsItemToggledOpen(),\r\n            ImGui::GetItemRectMin().x, ImGui::GetItemRectMin().y,\r\n            ImGui::GetItemRectMax().x, ImGui::GetItemRectMax().y,\r\n            ImGui::GetItemRectSize().x, ImGui::GetItemRectSize().y\r\n        );\r\n\r\n        if (item_disabled)\r\n            ImGui::EndDisabled();\r\n\r\n        char buf[1] = \"\";\r\n        ImGui::InputText(\"unused\", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_ReadOnly);\r\n        ImGui::SameLine();\r\n        HelpMarker(\"This widget is only here to be able to tab-out of the widgets above and see e.g. Deactivated() status.\");\r\n\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    IMGUI_DEMO_MARKER(\"Widgets/Querying Window Status (Focused,Hovered etc.)\");\r\n    if (ImGui::TreeNode(\"Querying Window Status (Focused/Hovered etc.)\"))\r\n    {\r\n        static bool embed_all_inside_a_child_window = false;\r\n        ImGui::Checkbox(\"Embed everything inside a child window for testing _RootWindow flag.\", &embed_all_inside_a_child_window);\r\n        if (embed_all_inside_a_child_window)\r\n            ImGui::BeginChild(\"outer_child\", ImVec2(0, ImGui::GetFontSize() * 20.0f), true);\r\n\r\n        // Testing IsWindowFocused() function with its various flags.\r\n        ImGui::BulletText(\r\n            \"IsWindowFocused() = %d\\n\"\r\n            \"IsWindowFocused(_ChildWindows) = %d\\n\"\r\n            \"IsWindowFocused(_ChildWindows|_NoPopupHierarchy) = %d\\n\"\r\n            \"IsWindowFocused(_ChildWindows|_RootWindow) = %d\\n\"\r\n            \"IsWindowFocused(_ChildWindows|_RootWindow|_NoPopupHierarchy) = %d\\n\"\r\n            \"IsWindowFocused(_RootWindow) = %d\\n\"\r\n            \"IsWindowFocused(_RootWindow|_NoPopupHierarchy) = %d\\n\"\r\n            \"IsWindowFocused(_AnyWindow) = %d\\n\",\r\n            ImGui::IsWindowFocused(),\r\n            ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows),\r\n            ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows | ImGuiFocusedFlags_NoPopupHierarchy),\r\n            ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows | ImGuiFocusedFlags_RootWindow),\r\n            ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows | ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_NoPopupHierarchy),\r\n            ImGui::IsWindowFocused(ImGuiFocusedFlags_RootWindow),\r\n            ImGui::IsWindowFocused(ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_NoPopupHierarchy),\r\n            ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow));\r\n\r\n        // Testing IsWindowHovered() function with its various flags.\r\n        ImGui::BulletText(\r\n            \"IsWindowHovered() = %d\\n\"\r\n            \"IsWindowHovered(_AllowWhenBlockedByPopup) = %d\\n\"\r\n            \"IsWindowHovered(_AllowWhenBlockedByActiveItem) = %d\\n\"\r\n            \"IsWindowHovered(_ChildWindows) = %d\\n\"\r\n            \"IsWindowHovered(_ChildWindows|_NoPopupHierarchy) = %d\\n\"\r\n            \"IsWindowHovered(_ChildWindows|_RootWindow) = %d\\n\"\r\n            \"IsWindowHovered(_ChildWindows|_RootWindow|_NoPopupHierarchy) = %d\\n\"\r\n            \"IsWindowHovered(_RootWindow) = %d\\n\"\r\n            \"IsWindowHovered(_RootWindow|_NoPopupHierarchy) = %d\\n\"\r\n            \"IsWindowHovered(_ChildWindows|_AllowWhenBlockedByPopup) = %d\\n\"\r\n            \"IsWindowHovered(_AnyWindow) = %d\\n\",\r\n            ImGui::IsWindowHovered(),\r\n            ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup),\r\n            ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem),\r\n            ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows),\r\n            ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_NoPopupHierarchy),\r\n            ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_RootWindow),\r\n            ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_NoPopupHierarchy),\r\n            ImGui::IsWindowHovered(ImGuiHoveredFlags_RootWindow),\r\n            ImGui::IsWindowHovered(ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_NoPopupHierarchy),\r\n            ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_AllowWhenBlockedByPopup),\r\n            ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow));\r\n\r\n        ImGui::BeginChild(\"child\", ImVec2(0, 50), true);\r\n        ImGui::Text(\"This is another child window for testing the _ChildWindows flag.\");\r\n        ImGui::EndChild();\r\n        if (embed_all_inside_a_child_window)\r\n            ImGui::EndChild();\r\n\r\n        // Calling IsItemHovered() after begin returns the hovered status of the title bar.\r\n        // This is useful in particular if you want to create a context menu associated to the title bar of a window.\r\n        static bool test_window = false;\r\n        ImGui::Checkbox(\"Hovered/Active tests after Begin() for title bar testing\", &test_window);\r\n        if (test_window)\r\n        {\r\n            ImGui::Begin(\"Title bar Hovered/Active tests\", &test_window);\r\n            if (ImGui::BeginPopupContextItem()) // <-- This is using IsItemHovered()\r\n            {\r\n                if (ImGui::MenuItem(\"Close\")) { test_window = false; }\r\n                ImGui::EndPopup();\r\n            }\r\n            ImGui::Text(\r\n                \"IsItemHovered() after begin = %d (== is title bar hovered)\\n\"\r\n                \"IsItemActive() after begin = %d (== is window being clicked/moved)\\n\",\r\n                ImGui::IsItemHovered(), ImGui::IsItemActive());\r\n            ImGui::End();\r\n        }\r\n\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    // Demonstrate BeginDisabled/EndDisabled using a checkbox located at the bottom of the section (which is a bit odd:\r\n    // logically we'd have this checkbox at the top of the section, but we don't want this feature to steal that space)\r\n    if (disable_all)\r\n        ImGui::EndDisabled();\r\n\r\n    IMGUI_DEMO_MARKER(\"Widgets/Disable Block\");\r\n    if (ImGui::TreeNode(\"Disable block\"))\r\n    {\r\n        ImGui::Checkbox(\"Disable entire section above\", &disable_all);\r\n        ImGui::SameLine(); HelpMarker(\"Demonstrate using BeginDisabled()/EndDisabled() across this section.\");\r\n        ImGui::TreePop();\r\n    }\r\n}\r\n\r\nstatic void ShowDemoWindowLayout()\r\n{\r\n    IMGUI_DEMO_MARKER(\"Layout\");\r\n    if (!ImGui::CollapsingHeader(\"Layout & Scrolling\"))\r\n        return;\r\n\r\n    IMGUI_DEMO_MARKER(\"Layout/Child windows\");\r\n    if (ImGui::TreeNode(\"Child windows\"))\r\n    {\r\n        HelpMarker(\"Use child windows to begin into a self-contained independent scrolling/clipping regions within a host window.\");\r\n        static bool disable_mouse_wheel = false;\r\n        static bool disable_menu = false;\r\n        ImGui::Checkbox(\"Disable Mouse Wheel\", &disable_mouse_wheel);\r\n        ImGui::Checkbox(\"Disable Menu\", &disable_menu);\r\n\r\n        // Child 1: no border, enable horizontal scrollbar\r\n        {\r\n            ImGuiWindowFlags window_flags = ImGuiWindowFlags_HorizontalScrollbar;\r\n            if (disable_mouse_wheel)\r\n                window_flags |= ImGuiWindowFlags_NoScrollWithMouse;\r\n            ImGui::BeginChild(\"ChildL\", ImVec2(ImGui::GetContentRegionAvail().x * 0.5f, 260), false, window_flags);\r\n            for (int i = 0; i < 100; i++)\r\n                ImGui::Text(\"%04d: scrollable region\", i);\r\n            ImGui::EndChild();\r\n        }\r\n\r\n        ImGui::SameLine();\r\n\r\n        // Child 2: rounded border\r\n        {\r\n            ImGuiWindowFlags window_flags = ImGuiWindowFlags_None;\r\n            if (disable_mouse_wheel)\r\n                window_flags |= ImGuiWindowFlags_NoScrollWithMouse;\r\n            if (!disable_menu)\r\n                window_flags |= ImGuiWindowFlags_MenuBar;\r\n            ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 5.0f);\r\n            ImGui::BeginChild(\"ChildR\", ImVec2(0, 260), true, window_flags);\r\n            if (!disable_menu && ImGui::BeginMenuBar())\r\n            {\r\n                if (ImGui::BeginMenu(\"Menu\"))\r\n                {\r\n                    ShowExampleMenuFile();\r\n                    ImGui::EndMenu();\r\n                }\r\n                ImGui::EndMenuBar();\r\n            }\r\n            if (ImGui::BeginTable(\"split\", 2, ImGuiTableFlags_Resizable | ImGuiTableFlags_NoSavedSettings))\r\n            {\r\n                for (int i = 0; i < 100; i++)\r\n                {\r\n                    char buf[32];\r\n                    sprintf(buf, \"%03d\", i);\r\n                    ImGui::TableNextColumn();\r\n                    ImGui::Button(buf, ImVec2(-FLT_MIN, 0.0f));\r\n                }\r\n                ImGui::EndTable();\r\n            }\r\n            ImGui::EndChild();\r\n            ImGui::PopStyleVar();\r\n        }\r\n\r\n        ImGui::Separator();\r\n\r\n        // Demonstrate a few extra things\r\n        // - Changing ImGuiCol_ChildBg (which is transparent black in default styles)\r\n        // - Using SetCursorPos() to position child window (the child window is an item from the POV of parent window)\r\n        //   You can also call SetNextWindowPos() to position the child window. The parent window will effectively\r\n        //   layout from this position.\r\n        // - Using ImGui::GetItemRectMin/Max() to query the \"item\" state (because the child window is an item from\r\n        //   the POV of the parent window). See 'Demo->Querying Status (Edited/Active/Hovered etc.)' for details.\r\n        {\r\n            static int offset_x = 0;\r\n            ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8);\r\n            ImGui::DragInt(\"Offset X\", &offset_x, 1.0f, -1000, 1000);\r\n\r\n            ImGui::SetCursorPosX(ImGui::GetCursorPosX() + (float)offset_x);\r\n            ImGui::PushStyleColor(ImGuiCol_ChildBg, IM_COL32(255, 0, 0, 100));\r\n            ImGui::BeginChild(\"Red\", ImVec2(200, 100), true, ImGuiWindowFlags_None);\r\n            for (int n = 0; n < 50; n++)\r\n                ImGui::Text(\"Some test %d\", n);\r\n            ImGui::EndChild();\r\n            bool child_is_hovered = ImGui::IsItemHovered();\r\n            ImVec2 child_rect_min = ImGui::GetItemRectMin();\r\n            ImVec2 child_rect_max = ImGui::GetItemRectMax();\r\n            ImGui::PopStyleColor();\r\n            ImGui::Text(\"Hovered: %d\", child_is_hovered);\r\n            ImGui::Text(\"Rect of child window is: (%.0f,%.0f) (%.0f,%.0f)\", child_rect_min.x, child_rect_min.y, child_rect_max.x, child_rect_max.y);\r\n        }\r\n\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    IMGUI_DEMO_MARKER(\"Layout/Widgets Width\");\r\n    if (ImGui::TreeNode(\"Widgets Width\"))\r\n    {\r\n        static float f = 0.0f;\r\n        static bool show_indented_items = true;\r\n        ImGui::Checkbox(\"Show indented items\", &show_indented_items);\r\n\r\n        // Use SetNextItemWidth() to set the width of a single upcoming item.\r\n        // Use PushItemWidth()/PopItemWidth() to set the width of a group of items.\r\n        // In real code use you'll probably want to choose width values that are proportional to your font size\r\n        // e.g. Using '20.0f * GetFontSize()' as width instead of '200.0f', etc.\r\n\r\n        ImGui::Text(\"SetNextItemWidth/PushItemWidth(100)\");\r\n        ImGui::SameLine(); HelpMarker(\"Fixed width.\");\r\n        ImGui::PushItemWidth(100);\r\n        ImGui::DragFloat(\"float##1b\", &f);\r\n        if (show_indented_items)\r\n        {\r\n            ImGui::Indent();\r\n            ImGui::DragFloat(\"float (indented)##1b\", &f);\r\n            ImGui::Unindent();\r\n        }\r\n        ImGui::PopItemWidth();\r\n\r\n        ImGui::Text(\"SetNextItemWidth/PushItemWidth(-100)\");\r\n        ImGui::SameLine(); HelpMarker(\"Align to right edge minus 100\");\r\n        ImGui::PushItemWidth(-100);\r\n        ImGui::DragFloat(\"float##2a\", &f);\r\n        if (show_indented_items)\r\n        {\r\n            ImGui::Indent();\r\n            ImGui::DragFloat(\"float (indented)##2b\", &f);\r\n            ImGui::Unindent();\r\n        }\r\n        ImGui::PopItemWidth();\r\n\r\n        ImGui::Text(\"SetNextItemWidth/PushItemWidth(GetContentRegionAvail().x * 0.5f)\");\r\n        ImGui::SameLine(); HelpMarker(\"Half of available width.\\n(~ right-cursor_pos)\\n(works within a column set)\");\r\n        ImGui::PushItemWidth(ImGui::GetContentRegionAvail().x * 0.5f);\r\n        ImGui::DragFloat(\"float##3a\", &f);\r\n        if (show_indented_items)\r\n        {\r\n            ImGui::Indent();\r\n            ImGui::DragFloat(\"float (indented)##3b\", &f);\r\n            ImGui::Unindent();\r\n        }\r\n        ImGui::PopItemWidth();\r\n\r\n        ImGui::Text(\"SetNextItemWidth/PushItemWidth(-GetContentRegionAvail().x * 0.5f)\");\r\n        ImGui::SameLine(); HelpMarker(\"Align to right edge minus half\");\r\n        ImGui::PushItemWidth(-ImGui::GetContentRegionAvail().x * 0.5f);\r\n        ImGui::DragFloat(\"float##4a\", &f);\r\n        if (show_indented_items)\r\n        {\r\n            ImGui::Indent();\r\n            ImGui::DragFloat(\"float (indented)##4b\", &f);\r\n            ImGui::Unindent();\r\n        }\r\n        ImGui::PopItemWidth();\r\n\r\n        // Demonstrate using PushItemWidth to surround three items.\r\n        // Calling SetNextItemWidth() before each of them would have the same effect.\r\n        ImGui::Text(\"SetNextItemWidth/PushItemWidth(-FLT_MIN)\");\r\n        ImGui::SameLine(); HelpMarker(\"Align to right edge\");\r\n        ImGui::PushItemWidth(-FLT_MIN);\r\n        ImGui::DragFloat(\"##float5a\", &f);\r\n        if (show_indented_items)\r\n        {\r\n            ImGui::Indent();\r\n            ImGui::DragFloat(\"float (indented)##5b\", &f);\r\n            ImGui::Unindent();\r\n        }\r\n        ImGui::PopItemWidth();\r\n\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    IMGUI_DEMO_MARKER(\"Layout/Basic Horizontal Layout\");\r\n    if (ImGui::TreeNode(\"Basic Horizontal Layout\"))\r\n    {\r\n        ImGui::TextWrapped(\"(Use ImGui::SameLine() to keep adding items to the right of the preceding item)\");\r\n\r\n        // Text\r\n        IMGUI_DEMO_MARKER(\"Layout/Basic Horizontal Layout/SameLine\");\r\n        ImGui::Text(\"Two items: Hello\"); ImGui::SameLine();\r\n        ImGui::TextColored(ImVec4(1,1,0,1), \"Sailor\");\r\n\r\n        // Adjust spacing\r\n        ImGui::Text(\"More spacing: Hello\"); ImGui::SameLine(0, 20);\r\n        ImGui::TextColored(ImVec4(1,1,0,1), \"Sailor\");\r\n\r\n        // Button\r\n        ImGui::AlignTextToFramePadding();\r\n        ImGui::Text(\"Normal buttons\"); ImGui::SameLine();\r\n        ImGui::Button(\"Banana\"); ImGui::SameLine();\r\n        ImGui::Button(\"Apple\"); ImGui::SameLine();\r\n        ImGui::Button(\"Corniflower\");\r\n\r\n        // Button\r\n        ImGui::Text(\"Small buttons\"); ImGui::SameLine();\r\n        ImGui::SmallButton(\"Like this one\"); ImGui::SameLine();\r\n        ImGui::Text(\"can fit within a text block.\");\r\n\r\n        // Aligned to arbitrary position. Easy/cheap column.\r\n        IMGUI_DEMO_MARKER(\"Layout/Basic Horizontal Layout/SameLine (with offset)\");\r\n        ImGui::Text(\"Aligned\");\r\n        ImGui::SameLine(150); ImGui::Text(\"x=150\");\r\n        ImGui::SameLine(300); ImGui::Text(\"x=300\");\r\n        ImGui::Text(\"Aligned\");\r\n        ImGui::SameLine(150); ImGui::SmallButton(\"x=150\");\r\n        ImGui::SameLine(300); ImGui::SmallButton(\"x=300\");\r\n\r\n        // Checkbox\r\n        IMGUI_DEMO_MARKER(\"Layout/Basic Horizontal Layout/SameLine (more)\");\r\n        static bool c1 = false, c2 = false, c3 = false, c4 = false;\r\n        ImGui::Checkbox(\"My\", &c1); ImGui::SameLine();\r\n        ImGui::Checkbox(\"Tailor\", &c2); ImGui::SameLine();\r\n        ImGui::Checkbox(\"Is\", &c3); ImGui::SameLine();\r\n        ImGui::Checkbox(\"Rich\", &c4);\r\n\r\n        // Various\r\n        static float f0 = 1.0f, f1 = 2.0f, f2 = 3.0f;\r\n        ImGui::PushItemWidth(80);\r\n        const char* items[] = { \"AAAA\", \"BBBB\", \"CCCC\", \"DDDD\" };\r\n        static int item = -1;\r\n        ImGui::Combo(\"Combo\", &item, items, IM_ARRAYSIZE(items)); ImGui::SameLine();\r\n        ImGui::SliderFloat(\"X\", &f0, 0.0f, 5.0f); ImGui::SameLine();\r\n        ImGui::SliderFloat(\"Y\", &f1, 0.0f, 5.0f); ImGui::SameLine();\r\n        ImGui::SliderFloat(\"Z\", &f2, 0.0f, 5.0f);\r\n        ImGui::PopItemWidth();\r\n\r\n        ImGui::PushItemWidth(80);\r\n        ImGui::Text(\"Lists:\");\r\n        static int selection[4] = { 0, 1, 2, 3 };\r\n        for (int i = 0; i < 4; i++)\r\n        {\r\n            if (i > 0) ImGui::SameLine();\r\n            ImGui::PushID(i);\r\n            ImGui::ListBox(\"\", &selection[i], items, IM_ARRAYSIZE(items));\r\n            ImGui::PopID();\r\n            //if (ImGui::IsItemHovered()) ImGui::SetTooltip(\"ListBox %d hovered\", i);\r\n        }\r\n        ImGui::PopItemWidth();\r\n\r\n        // Dummy\r\n        IMGUI_DEMO_MARKER(\"Layout/Basic Horizontal Layout/Dummy\");\r\n        ImVec2 button_sz(40, 40);\r\n        ImGui::Button(\"A\", button_sz); ImGui::SameLine();\r\n        ImGui::Dummy(button_sz); ImGui::SameLine();\r\n        ImGui::Button(\"B\", button_sz);\r\n\r\n        // Manually wrapping\r\n        // (we should eventually provide this as an automatic layout feature, but for now you can do it manually)\r\n        IMGUI_DEMO_MARKER(\"Layout/Basic Horizontal Layout/Manual wrapping\");\r\n        ImGui::Text(\"Manual wrapping:\");\r\n        ImGuiStyle& style = ImGui::GetStyle();\r\n        int buttons_count = 20;\r\n        float window_visible_x2 = ImGui::GetWindowPos().x + ImGui::GetWindowContentRegionMax().x;\r\n        for (int n = 0; n < buttons_count; n++)\r\n        {\r\n            ImGui::PushID(n);\r\n            ImGui::Button(\"Box\", button_sz);\r\n            float last_button_x2 = ImGui::GetItemRectMax().x;\r\n            float next_button_x2 = last_button_x2 + style.ItemSpacing.x + button_sz.x; // Expected position if next button was on same line\r\n            if (n + 1 < buttons_count && next_button_x2 < window_visible_x2)\r\n                ImGui::SameLine();\r\n            ImGui::PopID();\r\n        }\r\n\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    IMGUI_DEMO_MARKER(\"Layout/Groups\");\r\n    if (ImGui::TreeNode(\"Groups\"))\r\n    {\r\n        HelpMarker(\r\n            \"BeginGroup() basically locks the horizontal position for new line. \"\r\n            \"EndGroup() bundles the whole group so that you can use \\\"item\\\" functions such as \"\r\n            \"IsItemHovered()/IsItemActive() or SameLine() etc. on the whole group.\");\r\n        ImGui::BeginGroup();\r\n        {\r\n            ImGui::BeginGroup();\r\n            ImGui::Button(\"AAA\");\r\n            ImGui::SameLine();\r\n            ImGui::Button(\"BBB\");\r\n            ImGui::SameLine();\r\n            ImGui::BeginGroup();\r\n            ImGui::Button(\"CCC\");\r\n            ImGui::Button(\"DDD\");\r\n            ImGui::EndGroup();\r\n            ImGui::SameLine();\r\n            ImGui::Button(\"EEE\");\r\n            ImGui::EndGroup();\r\n            if (ImGui::IsItemHovered())\r\n                ImGui::SetTooltip(\"First group hovered\");\r\n        }\r\n        // Capture the group size and create widgets using the same size\r\n        ImVec2 size = ImGui::GetItemRectSize();\r\n        const float values[5] = { 0.5f, 0.20f, 0.80f, 0.60f, 0.25f };\r\n        ImGui::PlotHistogram(\"##values\", values, IM_ARRAYSIZE(values), 0, NULL, 0.0f, 1.0f, size);\r\n\r\n        ImGui::Button(\"ACTION\", ImVec2((size.x - ImGui::GetStyle().ItemSpacing.x) * 0.5f, size.y));\r\n        ImGui::SameLine();\r\n        ImGui::Button(\"REACTION\", ImVec2((size.x - ImGui::GetStyle().ItemSpacing.x) * 0.5f, size.y));\r\n        ImGui::EndGroup();\r\n        ImGui::SameLine();\r\n\r\n        ImGui::Button(\"LEVERAGE\\nBUZZWORD\", size);\r\n        ImGui::SameLine();\r\n\r\n        if (ImGui::BeginListBox(\"List\", size))\r\n        {\r\n            ImGui::Selectable(\"Selected\", true);\r\n            ImGui::Selectable(\"Not Selected\", false);\r\n            ImGui::EndListBox();\r\n        }\r\n\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    IMGUI_DEMO_MARKER(\"Layout/Text Baseline Alignment\");\r\n    if (ImGui::TreeNode(\"Text Baseline Alignment\"))\r\n    {\r\n        {\r\n            ImGui::BulletText(\"Text baseline:\");\r\n            ImGui::SameLine(); HelpMarker(\r\n                \"This is testing the vertical alignment that gets applied on text to keep it aligned with widgets. \"\r\n                \"Lines only composed of text or \\\"small\\\" widgets use less vertical space than lines with framed widgets.\");\r\n            ImGui::Indent();\r\n\r\n            ImGui::Text(\"KO Blahblah\"); ImGui::SameLine();\r\n            ImGui::Button(\"Some framed item\"); ImGui::SameLine();\r\n            HelpMarker(\"Baseline of button will look misaligned with text..\");\r\n\r\n            // If your line starts with text, call AlignTextToFramePadding() to align text to upcoming widgets.\r\n            // (because we don't know what's coming after the Text() statement, we need to move the text baseline\r\n            // down by FramePadding.y ahead of time)\r\n            ImGui::AlignTextToFramePadding();\r\n            ImGui::Text(\"OK Blahblah\"); ImGui::SameLine();\r\n            ImGui::Button(\"Some framed item\"); ImGui::SameLine();\r\n            HelpMarker(\"We call AlignTextToFramePadding() to vertically align the text baseline by +FramePadding.y\");\r\n\r\n            // SmallButton() uses the same vertical padding as Text\r\n            ImGui::Button(\"TEST##1\"); ImGui::SameLine();\r\n            ImGui::Text(\"TEST\"); ImGui::SameLine();\r\n            ImGui::SmallButton(\"TEST##2\");\r\n\r\n            // If your line starts with text, call AlignTextToFramePadding() to align text to upcoming widgets.\r\n            ImGui::AlignTextToFramePadding();\r\n            ImGui::Text(\"Text aligned to framed item\"); ImGui::SameLine();\r\n            ImGui::Button(\"Item##1\"); ImGui::SameLine();\r\n            ImGui::Text(\"Item\"); ImGui::SameLine();\r\n            ImGui::SmallButton(\"Item##2\"); ImGui::SameLine();\r\n            ImGui::Button(\"Item##3\");\r\n\r\n            ImGui::Unindent();\r\n        }\r\n\r\n        ImGui::Spacing();\r\n\r\n        {\r\n            ImGui::BulletText(\"Multi-line text:\");\r\n            ImGui::Indent();\r\n            ImGui::Text(\"One\\nTwo\\nThree\"); ImGui::SameLine();\r\n            ImGui::Text(\"Hello\\nWorld\"); ImGui::SameLine();\r\n            ImGui::Text(\"Banana\");\r\n\r\n            ImGui::Text(\"Banana\"); ImGui::SameLine();\r\n            ImGui::Text(\"Hello\\nWorld\"); ImGui::SameLine();\r\n            ImGui::Text(\"One\\nTwo\\nThree\");\r\n\r\n            ImGui::Button(\"HOP##1\"); ImGui::SameLine();\r\n            ImGui::Text(\"Banana\"); ImGui::SameLine();\r\n            ImGui::Text(\"Hello\\nWorld\"); ImGui::SameLine();\r\n            ImGui::Text(\"Banana\");\r\n\r\n            ImGui::Button(\"HOP##2\"); ImGui::SameLine();\r\n            ImGui::Text(\"Hello\\nWorld\"); ImGui::SameLine();\r\n            ImGui::Text(\"Banana\");\r\n            ImGui::Unindent();\r\n        }\r\n\r\n        ImGui::Spacing();\r\n\r\n        {\r\n            ImGui::BulletText(\"Misc items:\");\r\n            ImGui::Indent();\r\n\r\n            // SmallButton() sets FramePadding to zero. Text baseline is aligned to match baseline of previous Button.\r\n            ImGui::Button(\"80x80\", ImVec2(80, 80));\r\n            ImGui::SameLine();\r\n            ImGui::Button(\"50x50\", ImVec2(50, 50));\r\n            ImGui::SameLine();\r\n            ImGui::Button(\"Button()\");\r\n            ImGui::SameLine();\r\n            ImGui::SmallButton(\"SmallButton()\");\r\n\r\n            // Tree\r\n            const float spacing = ImGui::GetStyle().ItemInnerSpacing.x;\r\n            ImGui::Button(\"Button##1\");\r\n            ImGui::SameLine(0.0f, spacing);\r\n            if (ImGui::TreeNode(\"Node##1\"))\r\n            {\r\n                // Placeholder tree data\r\n                for (int i = 0; i < 6; i++)\r\n                    ImGui::BulletText(\"Item %d..\", i);\r\n                ImGui::TreePop();\r\n            }\r\n\r\n            // Vertically align text node a bit lower so it'll be vertically centered with upcoming widget.\r\n            // Otherwise you can use SmallButton() (smaller fit).\r\n            ImGui::AlignTextToFramePadding();\r\n\r\n            // Common mistake to avoid: if we want to SameLine after TreeNode we need to do it before we add\r\n            // other contents below the node.\r\n            bool node_open = ImGui::TreeNode(\"Node##2\");\r\n            ImGui::SameLine(0.0f, spacing); ImGui::Button(\"Button##2\");\r\n            if (node_open)\r\n            {\r\n                // Placeholder tree data\r\n                for (int i = 0; i < 6; i++)\r\n                    ImGui::BulletText(\"Item %d..\", i);\r\n                ImGui::TreePop();\r\n            }\r\n\r\n            // Bullet\r\n            ImGui::Button(\"Button##3\");\r\n            ImGui::SameLine(0.0f, spacing);\r\n            ImGui::BulletText(\"Bullet text\");\r\n\r\n            ImGui::AlignTextToFramePadding();\r\n            ImGui::BulletText(\"Node\");\r\n            ImGui::SameLine(0.0f, spacing); ImGui::Button(\"Button##4\");\r\n            ImGui::Unindent();\r\n        }\r\n\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    IMGUI_DEMO_MARKER(\"Layout/Scrolling\");\r\n    if (ImGui::TreeNode(\"Scrolling\"))\r\n    {\r\n        // Vertical scroll functions\r\n        IMGUI_DEMO_MARKER(\"Layout/Scrolling/Vertical\");\r\n        HelpMarker(\"Use SetScrollHereY() or SetScrollFromPosY() to scroll to a given vertical position.\");\r\n\r\n        static int track_item = 50;\r\n        static bool enable_track = true;\r\n        static bool enable_extra_decorations = false;\r\n        static float scroll_to_off_px = 0.0f;\r\n        static float scroll_to_pos_px = 200.0f;\r\n\r\n        ImGui::Checkbox(\"Decoration\", &enable_extra_decorations);\r\n\r\n        ImGui::Checkbox(\"Track\", &enable_track);\r\n        ImGui::PushItemWidth(100);\r\n        ImGui::SameLine(140); enable_track |= ImGui::DragInt(\"##item\", &track_item, 0.25f, 0, 99, \"Item = %d\");\r\n\r\n        bool scroll_to_off = ImGui::Button(\"Scroll Offset\");\r\n        ImGui::SameLine(140); scroll_to_off |= ImGui::DragFloat(\"##off\", &scroll_to_off_px, 1.00f, 0, FLT_MAX, \"+%.0f px\");\r\n\r\n        bool scroll_to_pos = ImGui::Button(\"Scroll To Pos\");\r\n        ImGui::SameLine(140); scroll_to_pos |= ImGui::DragFloat(\"##pos\", &scroll_to_pos_px, 1.00f, -10, FLT_MAX, \"X/Y = %.0f px\");\r\n        ImGui::PopItemWidth();\r\n\r\n        if (scroll_to_off || scroll_to_pos)\r\n            enable_track = false;\r\n\r\n        ImGuiStyle& style = ImGui::GetStyle();\r\n        float child_w = (ImGui::GetContentRegionAvail().x - 4 * style.ItemSpacing.x) / 5;\r\n        if (child_w < 1.0f)\r\n            child_w = 1.0f;\r\n        ImGui::PushID(\"##VerticalScrolling\");\r\n        for (int i = 0; i < 5; i++)\r\n        {\r\n            if (i > 0) ImGui::SameLine();\r\n            ImGui::BeginGroup();\r\n            const char* names[] = { \"Top\", \"25%\", \"Center\", \"75%\", \"Bottom\" };\r\n            ImGui::TextUnformatted(names[i]);\r\n\r\n            const ImGuiWindowFlags child_flags = enable_extra_decorations ? ImGuiWindowFlags_MenuBar : 0;\r\n            const ImGuiID child_id = ImGui::GetID((void*)(intptr_t)i);\r\n            const bool child_is_visible = ImGui::BeginChild(child_id, ImVec2(child_w, 200.0f), true, child_flags);\r\n            if (ImGui::BeginMenuBar())\r\n            {\r\n                ImGui::TextUnformatted(\"abc\");\r\n                ImGui::EndMenuBar();\r\n            }\r\n            if (scroll_to_off)\r\n                ImGui::SetScrollY(scroll_to_off_px);\r\n            if (scroll_to_pos)\r\n                ImGui::SetScrollFromPosY(ImGui::GetCursorStartPos().y + scroll_to_pos_px, i * 0.25f);\r\n            if (child_is_visible) // Avoid calling SetScrollHereY when running with culled items\r\n            {\r\n                for (int item = 0; item < 100; item++)\r\n                {\r\n                    if (enable_track && item == track_item)\r\n                    {\r\n                        ImGui::TextColored(ImVec4(1, 1, 0, 1), \"Item %d\", item);\r\n                        ImGui::SetScrollHereY(i * 0.25f); // 0.0f:top, 0.5f:center, 1.0f:bottom\r\n                    }\r\n                    else\r\n                    {\r\n                        ImGui::Text(\"Item %d\", item);\r\n                    }\r\n                }\r\n            }\r\n            float scroll_y = ImGui::GetScrollY();\r\n            float scroll_max_y = ImGui::GetScrollMaxY();\r\n            ImGui::EndChild();\r\n            ImGui::Text(\"%.0f/%.0f\", scroll_y, scroll_max_y);\r\n            ImGui::EndGroup();\r\n        }\r\n        ImGui::PopID();\r\n\r\n        // Horizontal scroll functions\r\n        IMGUI_DEMO_MARKER(\"Layout/Scrolling/Horizontal\");\r\n        ImGui::Spacing();\r\n        HelpMarker(\r\n            \"Use SetScrollHereX() or SetScrollFromPosX() to scroll to a given horizontal position.\\n\\n\"\r\n            \"Because the clipping rectangle of most window hides half worth of WindowPadding on the \"\r\n            \"left/right, using SetScrollFromPosX(+1) will usually result in clipped text whereas the \"\r\n            \"equivalent SetScrollFromPosY(+1) wouldn't.\");\r\n        ImGui::PushID(\"##HorizontalScrolling\");\r\n        for (int i = 0; i < 5; i++)\r\n        {\r\n            float child_height = ImGui::GetTextLineHeight() + style.ScrollbarSize + style.WindowPadding.y * 2.0f;\r\n            ImGuiWindowFlags child_flags = ImGuiWindowFlags_HorizontalScrollbar | (enable_extra_decorations ? ImGuiWindowFlags_AlwaysVerticalScrollbar : 0);\r\n            ImGuiID child_id = ImGui::GetID((void*)(intptr_t)i);\r\n            bool child_is_visible = ImGui::BeginChild(child_id, ImVec2(-100, child_height), true, child_flags);\r\n            if (scroll_to_off)\r\n                ImGui::SetScrollX(scroll_to_off_px);\r\n            if (scroll_to_pos)\r\n                ImGui::SetScrollFromPosX(ImGui::GetCursorStartPos().x + scroll_to_pos_px, i * 0.25f);\r\n            if (child_is_visible) // Avoid calling SetScrollHereY when running with culled items\r\n            {\r\n                for (int item = 0; item < 100; item++)\r\n                {\r\n                    if (item > 0)\r\n                        ImGui::SameLine();\r\n                    if (enable_track && item == track_item)\r\n                    {\r\n                        ImGui::TextColored(ImVec4(1, 1, 0, 1), \"Item %d\", item);\r\n                        ImGui::SetScrollHereX(i * 0.25f); // 0.0f:left, 0.5f:center, 1.0f:right\r\n                    }\r\n                    else\r\n                    {\r\n                        ImGui::Text(\"Item %d\", item);\r\n                    }\r\n                }\r\n            }\r\n            float scroll_x = ImGui::GetScrollX();\r\n            float scroll_max_x = ImGui::GetScrollMaxX();\r\n            ImGui::EndChild();\r\n            ImGui::SameLine();\r\n            const char* names[] = { \"Left\", \"25%\", \"Center\", \"75%\", \"Right\" };\r\n            ImGui::Text(\"%s\\n%.0f/%.0f\", names[i], scroll_x, scroll_max_x);\r\n            ImGui::Spacing();\r\n        }\r\n        ImGui::PopID();\r\n\r\n        // Miscellaneous Horizontal Scrolling Demo\r\n        IMGUI_DEMO_MARKER(\"Layout/Scrolling/Horizontal (more)\");\r\n        HelpMarker(\r\n            \"Horizontal scrolling for a window is enabled via the ImGuiWindowFlags_HorizontalScrollbar flag.\\n\\n\"\r\n            \"You may want to also explicitly specify content width by using SetNextWindowContentWidth() before Begin().\");\r\n        static int lines = 7;\r\n        ImGui::SliderInt(\"Lines\", &lines, 1, 15);\r\n        ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 3.0f);\r\n        ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2.0f, 1.0f));\r\n        ImVec2 scrolling_child_size = ImVec2(0, ImGui::GetFrameHeightWithSpacing() * 7 + 30);\r\n        ImGui::BeginChild(\"scrolling\", scrolling_child_size, true, ImGuiWindowFlags_HorizontalScrollbar);\r\n        for (int line = 0; line < lines; line++)\r\n        {\r\n            // Display random stuff. For the sake of this trivial demo we are using basic Button() + SameLine()\r\n            // If you want to create your own time line for a real application you may be better off manipulating\r\n            // the cursor position yourself, aka using SetCursorPos/SetCursorScreenPos to position the widgets\r\n            // yourself. You may also want to use the lower-level ImDrawList API.\r\n            int num_buttons = 10 + ((line & 1) ? line * 9 : line * 3);\r\n            for (int n = 0; n < num_buttons; n++)\r\n            {\r\n                if (n > 0) ImGui::SameLine();\r\n                ImGui::PushID(n + line * 1000);\r\n                char num_buf[16];\r\n                sprintf(num_buf, \"%d\", n);\r\n                const char* label = (!(n % 15)) ? \"FizzBuzz\" : (!(n % 3)) ? \"Fizz\" : (!(n % 5)) ? \"Buzz\" : num_buf;\r\n                float hue = n * 0.05f;\r\n                ImGui::PushStyleColor(ImGuiCol_Button, (ImVec4)ImColor::HSV(hue, 0.6f, 0.6f));\r\n                ImGui::PushStyleColor(ImGuiCol_ButtonHovered, (ImVec4)ImColor::HSV(hue, 0.7f, 0.7f));\r\n                ImGui::PushStyleColor(ImGuiCol_ButtonActive, (ImVec4)ImColor::HSV(hue, 0.8f, 0.8f));\r\n                ImGui::Button(label, ImVec2(40.0f + sinf((float)(line + n)) * 20.0f, 0.0f));\r\n                ImGui::PopStyleColor(3);\r\n                ImGui::PopID();\r\n            }\r\n        }\r\n        float scroll_x = ImGui::GetScrollX();\r\n        float scroll_max_x = ImGui::GetScrollMaxX();\r\n        ImGui::EndChild();\r\n        ImGui::PopStyleVar(2);\r\n        float scroll_x_delta = 0.0f;\r\n        ImGui::SmallButton(\"<<\");\r\n        if (ImGui::IsItemActive())\r\n            scroll_x_delta = -ImGui::GetIO().DeltaTime * 1000.0f;\r\n        ImGui::SameLine();\r\n        ImGui::Text(\"Scroll from code\"); ImGui::SameLine();\r\n        ImGui::SmallButton(\">>\");\r\n        if (ImGui::IsItemActive())\r\n            scroll_x_delta = +ImGui::GetIO().DeltaTime * 1000.0f;\r\n        ImGui::SameLine();\r\n        ImGui::Text(\"%.0f/%.0f\", scroll_x, scroll_max_x);\r\n        if (scroll_x_delta != 0.0f)\r\n        {\r\n            // Demonstrate a trick: you can use Begin to set yourself in the context of another window\r\n            // (here we are already out of your child window)\r\n            ImGui::BeginChild(\"scrolling\");\r\n            ImGui::SetScrollX(ImGui::GetScrollX() + scroll_x_delta);\r\n            ImGui::EndChild();\r\n        }\r\n        ImGui::Spacing();\r\n\r\n        static bool show_horizontal_contents_size_demo_window = false;\r\n        ImGui::Checkbox(\"Show Horizontal contents size demo window\", &show_horizontal_contents_size_demo_window);\r\n\r\n        if (show_horizontal_contents_size_demo_window)\r\n        {\r\n            static bool show_h_scrollbar = true;\r\n            static bool show_button = true;\r\n            static bool show_tree_nodes = true;\r\n            static bool show_text_wrapped = false;\r\n            static bool show_columns = true;\r\n            static bool show_tab_bar = true;\r\n            static bool show_child = false;\r\n            static bool explicit_content_size = false;\r\n            static float contents_size_x = 300.0f;\r\n            if (explicit_content_size)\r\n                ImGui::SetNextWindowContentSize(ImVec2(contents_size_x, 0.0f));\r\n            ImGui::Begin(\"Horizontal contents size demo window\", &show_horizontal_contents_size_demo_window, show_h_scrollbar ? ImGuiWindowFlags_HorizontalScrollbar : 0);\r\n            IMGUI_DEMO_MARKER(\"Layout/Scrolling/Horizontal contents size demo window\");\r\n            ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(2, 0));\r\n            ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2, 0));\r\n            HelpMarker(\"Test of different widgets react and impact the work rectangle growing when horizontal scrolling is enabled.\\n\\nUse 'Metrics->Tools->Show windows rectangles' to visualize rectangles.\");\r\n            ImGui::Checkbox(\"H-scrollbar\", &show_h_scrollbar);\r\n            ImGui::Checkbox(\"Button\", &show_button);            // Will grow contents size (unless explicitly overwritten)\r\n            ImGui::Checkbox(\"Tree nodes\", &show_tree_nodes);    // Will grow contents size and display highlight over full width\r\n            ImGui::Checkbox(\"Text wrapped\", &show_text_wrapped);// Will grow and use contents size\r\n            ImGui::Checkbox(\"Columns\", &show_columns);          // Will use contents size\r\n            ImGui::Checkbox(\"Tab bar\", &show_tab_bar);          // Will use contents size\r\n            ImGui::Checkbox(\"Child\", &show_child);              // Will grow and use contents size\r\n            ImGui::Checkbox(\"Explicit content size\", &explicit_content_size);\r\n            ImGui::Text(\"Scroll %.1f/%.1f %.1f/%.1f\", ImGui::GetScrollX(), ImGui::GetScrollMaxX(), ImGui::GetScrollY(), ImGui::GetScrollMaxY());\r\n            if (explicit_content_size)\r\n            {\r\n                ImGui::SameLine();\r\n                ImGui::SetNextItemWidth(100);\r\n                ImGui::DragFloat(\"##csx\", &contents_size_x);\r\n                ImVec2 p = ImGui::GetCursorScreenPos();\r\n                ImGui::GetWindowDrawList()->AddRectFilled(p, ImVec2(p.x + 10, p.y + 10), IM_COL32_WHITE);\r\n                ImGui::GetWindowDrawList()->AddRectFilled(ImVec2(p.x + contents_size_x - 10, p.y), ImVec2(p.x + contents_size_x, p.y + 10), IM_COL32_WHITE);\r\n                ImGui::Dummy(ImVec2(0, 10));\r\n            }\r\n            ImGui::PopStyleVar(2);\r\n            ImGui::Separator();\r\n            if (show_button)\r\n            {\r\n                ImGui::Button(\"this is a 300-wide button\", ImVec2(300, 0));\r\n            }\r\n            if (show_tree_nodes)\r\n            {\r\n                bool open = true;\r\n                if (ImGui::TreeNode(\"this is a tree node\"))\r\n                {\r\n                    if (ImGui::TreeNode(\"another one of those tree node...\"))\r\n                    {\r\n                        ImGui::Text(\"Some tree contents\");\r\n                        ImGui::TreePop();\r\n                    }\r\n                    ImGui::TreePop();\r\n                }\r\n                ImGui::CollapsingHeader(\"CollapsingHeader\", &open);\r\n            }\r\n            if (show_text_wrapped)\r\n            {\r\n                ImGui::TextWrapped(\"This text should automatically wrap on the edge of the work rectangle.\");\r\n            }\r\n            if (show_columns)\r\n            {\r\n                ImGui::Text(\"Tables:\");\r\n                if (ImGui::BeginTable(\"table\", 4, ImGuiTableFlags_Borders))\r\n                {\r\n                    for (int n = 0; n < 4; n++)\r\n                    {\r\n                        ImGui::TableNextColumn();\r\n                        ImGui::Text(\"Width %.2f\", ImGui::GetContentRegionAvail().x);\r\n                    }\r\n                    ImGui::EndTable();\r\n                }\r\n                ImGui::Text(\"Columns:\");\r\n                ImGui::Columns(4);\r\n                for (int n = 0; n < 4; n++)\r\n                {\r\n                    ImGui::Text(\"Width %.2f\", ImGui::GetColumnWidth());\r\n                    ImGui::NextColumn();\r\n                }\r\n                ImGui::Columns(1);\r\n            }\r\n            if (show_tab_bar && ImGui::BeginTabBar(\"Hello\"))\r\n            {\r\n                if (ImGui::BeginTabItem(\"OneOneOne\")) { ImGui::EndTabItem(); }\r\n                if (ImGui::BeginTabItem(\"TwoTwoTwo\")) { ImGui::EndTabItem(); }\r\n                if (ImGui::BeginTabItem(\"ThreeThreeThree\")) { ImGui::EndTabItem(); }\r\n                if (ImGui::BeginTabItem(\"FourFourFour\")) { ImGui::EndTabItem(); }\r\n                ImGui::EndTabBar();\r\n            }\r\n            if (show_child)\r\n            {\r\n                ImGui::BeginChild(\"child\", ImVec2(0, 0), true);\r\n                ImGui::EndChild();\r\n            }\r\n            ImGui::End();\r\n        }\r\n\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    IMGUI_DEMO_MARKER(\"Layout/Clipping\");\r\n    if (ImGui::TreeNode(\"Clipping\"))\r\n    {\r\n        static ImVec2 size(100.0f, 100.0f);\r\n        static ImVec2 offset(30.0f, 30.0f);\r\n        ImGui::DragFloat2(\"size\", (float*)&size, 0.5f, 1.0f, 200.0f, \"%.0f\");\r\n        ImGui::TextWrapped(\"(Click and drag to scroll)\");\r\n\r\n        for (int n = 0; n < 3; n++)\r\n        {\r\n            if (n > 0)\r\n                ImGui::SameLine();\r\n            ImGui::PushID(n);\r\n            ImGui::BeginGroup(); // Lock X position\r\n\r\n            ImGui::InvisibleButton(\"##empty\", size);\r\n            if (ImGui::IsItemActive() && ImGui::IsMouseDragging(ImGuiMouseButton_Left))\r\n            {\r\n                offset.x += ImGui::GetIO().MouseDelta.x;\r\n                offset.y += ImGui::GetIO().MouseDelta.y;\r\n            }\r\n            const ImVec2 p0 = ImGui::GetItemRectMin();\r\n            const ImVec2 p1 = ImGui::GetItemRectMax();\r\n            const char* text_str = \"Line 1 hello\\nLine 2 clip me!\";\r\n            const ImVec2 text_pos = ImVec2(p0.x + offset.x, p0.y + offset.y);\r\n            ImDrawList* draw_list = ImGui::GetWindowDrawList();\r\n\r\n            switch (n)\r\n            {\r\n            case 0:\r\n                HelpMarker(\r\n                    \"Using ImGui::PushClipRect():\\n\"\r\n                    \"Will alter ImGui hit-testing logic + ImDrawList rendering.\\n\"\r\n                    \"(use this if you want your clipping rectangle to affect interactions)\");\r\n                ImGui::PushClipRect(p0, p1, true);\r\n                draw_list->AddRectFilled(p0, p1, IM_COL32(90, 90, 120, 255));\r\n                draw_list->AddText(text_pos, IM_COL32_WHITE, text_str);\r\n                ImGui::PopClipRect();\r\n                break;\r\n            case 1:\r\n                HelpMarker(\r\n                    \"Using ImDrawList::PushClipRect():\\n\"\r\n                    \"Will alter ImDrawList rendering only.\\n\"\r\n                    \"(use this as a shortcut if you are only using ImDrawList calls)\");\r\n                draw_list->PushClipRect(p0, p1, true);\r\n                draw_list->AddRectFilled(p0, p1, IM_COL32(90, 90, 120, 255));\r\n                draw_list->AddText(text_pos, IM_COL32_WHITE, text_str);\r\n                draw_list->PopClipRect();\r\n                break;\r\n            case 2:\r\n                HelpMarker(\r\n                    \"Using ImDrawList::AddText() with a fine ClipRect:\\n\"\r\n                    \"Will alter only this specific ImDrawList::AddText() rendering.\\n\"\r\n                    \"(this is often used internally to avoid altering the clipping rectangle and minimize draw calls)\");\r\n                ImVec4 clip_rect(p0.x, p0.y, p1.x, p1.y); // AddText() takes a ImVec4* here so let's convert.\r\n                draw_list->AddRectFilled(p0, p1, IM_COL32(90, 90, 120, 255));\r\n                draw_list->AddText(ImGui::GetFont(), ImGui::GetFontSize(), text_pos, IM_COL32_WHITE, text_str, NULL, 0.0f, &clip_rect);\r\n                break;\r\n            }\r\n            ImGui::EndGroup();\r\n            ImGui::PopID();\r\n        }\r\n\r\n        ImGui::TreePop();\r\n    }\r\n}\r\n\r\nstatic void ShowDemoWindowPopups()\r\n{\r\n    IMGUI_DEMO_MARKER(\"Popups\");\r\n    if (!ImGui::CollapsingHeader(\"Popups & Modal windows\"))\r\n        return;\r\n\r\n    // The properties of popups windows are:\r\n    // - They block normal mouse hovering detection outside them. (*)\r\n    // - Unless modal, they can be closed by clicking anywhere outside them, or by pressing ESCAPE.\r\n    // - Their visibility state (~bool) is held internally by Dear ImGui instead of being held by the programmer as\r\n    //   we are used to with regular Begin() calls. User can manipulate the visibility state by calling OpenPopup().\r\n    // (*) One can use IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup) to bypass it and detect hovering even\r\n    //     when normally blocked by a popup.\r\n    // Those three properties are connected. The library needs to hold their visibility state BECAUSE it can close\r\n    // popups at any time.\r\n\r\n    // Typical use for regular windows:\r\n    //   bool my_tool_is_active = false; if (ImGui::Button(\"Open\")) my_tool_is_active = true; [...] if (my_tool_is_active) Begin(\"My Tool\", &my_tool_is_active) { [...] } End();\r\n    // Typical use for popups:\r\n    //   if (ImGui::Button(\"Open\")) ImGui::OpenPopup(\"MyPopup\"); if (ImGui::BeginPopup(\"MyPopup\") { [...] EndPopup(); }\r\n\r\n    // With popups we have to go through a library call (here OpenPopup) to manipulate the visibility state.\r\n    // This may be a bit confusing at first but it should quickly make sense. Follow on the examples below.\r\n\r\n    IMGUI_DEMO_MARKER(\"Popups/Popups\");\r\n    if (ImGui::TreeNode(\"Popups\"))\r\n    {\r\n        ImGui::TextWrapped(\r\n            \"When a popup is active, it inhibits interacting with windows that are behind the popup. \"\r\n            \"Clicking outside the popup closes it.\");\r\n\r\n        static int selected_fish = -1;\r\n        const char* names[] = { \"Bream\", \"Haddock\", \"Mackerel\", \"Pollock\", \"Tilefish\" };\r\n        static bool toggles[] = { true, false, false, false, false };\r\n\r\n        // Simple selection popup (if you want to show the current selection inside the Button itself,\r\n        // you may want to build a string using the \"###\" operator to preserve a constant ID with a variable label)\r\n        if (ImGui::Button(\"Select..\"))\r\n            ImGui::OpenPopup(\"my_select_popup\");\r\n        ImGui::SameLine();\r\n        ImGui::TextUnformatted(selected_fish == -1 ? \"<None>\" : names[selected_fish]);\r\n        if (ImGui::BeginPopup(\"my_select_popup\"))\r\n        {\r\n            ImGui::Text(\"Aquarium\");\r\n            ImGui::Separator();\r\n            for (int i = 0; i < IM_ARRAYSIZE(names); i++)\r\n                if (ImGui::Selectable(names[i]))\r\n                    selected_fish = i;\r\n            ImGui::EndPopup();\r\n        }\r\n\r\n        // Showing a menu with toggles\r\n        if (ImGui::Button(\"Toggle..\"))\r\n            ImGui::OpenPopup(\"my_toggle_popup\");\r\n        if (ImGui::BeginPopup(\"my_toggle_popup\"))\r\n        {\r\n            for (int i = 0; i < IM_ARRAYSIZE(names); i++)\r\n                ImGui::MenuItem(names[i], \"\", &toggles[i]);\r\n            if (ImGui::BeginMenu(\"Sub-menu\"))\r\n            {\r\n                ImGui::MenuItem(\"Click me\");\r\n                ImGui::EndMenu();\r\n            }\r\n\r\n            ImGui::Separator();\r\n            ImGui::Text(\"Tooltip here\");\r\n            if (ImGui::IsItemHovered())\r\n                ImGui::SetTooltip(\"I am a tooltip over a popup\");\r\n\r\n            if (ImGui::Button(\"Stacked Popup\"))\r\n                ImGui::OpenPopup(\"another popup\");\r\n            if (ImGui::BeginPopup(\"another popup\"))\r\n            {\r\n                for (int i = 0; i < IM_ARRAYSIZE(names); i++)\r\n                    ImGui::MenuItem(names[i], \"\", &toggles[i]);\r\n                if (ImGui::BeginMenu(\"Sub-menu\"))\r\n                {\r\n                    ImGui::MenuItem(\"Click me\");\r\n                    if (ImGui::Button(\"Stacked Popup\"))\r\n                        ImGui::OpenPopup(\"another popup\");\r\n                    if (ImGui::BeginPopup(\"another popup\"))\r\n                    {\r\n                        ImGui::Text(\"I am the last one here.\");\r\n                        ImGui::EndPopup();\r\n                    }\r\n                    ImGui::EndMenu();\r\n                }\r\n                ImGui::EndPopup();\r\n            }\r\n            ImGui::EndPopup();\r\n        }\r\n\r\n        // Call the more complete ShowExampleMenuFile which we use in various places of this demo\r\n        if (ImGui::Button(\"With a menu..\"))\r\n            ImGui::OpenPopup(\"my_file_popup\");\r\n        if (ImGui::BeginPopup(\"my_file_popup\", ImGuiWindowFlags_MenuBar))\r\n        {\r\n            if (ImGui::BeginMenuBar())\r\n            {\r\n                if (ImGui::BeginMenu(\"File\"))\r\n                {\r\n                    ShowExampleMenuFile();\r\n                    ImGui::EndMenu();\r\n                }\r\n                if (ImGui::BeginMenu(\"Edit\"))\r\n                {\r\n                    ImGui::MenuItem(\"Dummy\");\r\n                    ImGui::EndMenu();\r\n                }\r\n                ImGui::EndMenuBar();\r\n            }\r\n            ImGui::Text(\"Hello from popup!\");\r\n            ImGui::Button(\"This is a dummy button..\");\r\n            ImGui::EndPopup();\r\n        }\r\n\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    IMGUI_DEMO_MARKER(\"Popups/Context menus\");\r\n    if (ImGui::TreeNode(\"Context menus\"))\r\n    {\r\n        HelpMarker(\"\\\"Context\\\" functions are simple helpers to associate a Popup to a given Item or Window identifier.\");\r\n\r\n        // BeginPopupContextItem() is a helper to provide common/simple popup behavior of essentially doing:\r\n        //     if (id == 0)\r\n        //         id = GetItemID(); // Use last item id\r\n        //     if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right))\r\n        //         OpenPopup(id);\r\n        //     return BeginPopup(id);\r\n        // For advanced advanced uses you may want to replicate and customize this code.\r\n        // See more details in BeginPopupContextItem().\r\n\r\n        // Example 1\r\n        // When used after an item that has an ID (e.g. Button), we can skip providing an ID to BeginPopupContextItem(),\r\n        // and BeginPopupContextItem() will use the last item ID as the popup ID.\r\n        {\r\n            const char* names[5] = { \"Label1\", \"Label2\", \"Label3\", \"Label4\", \"Label5\" };\r\n            for (int n = 0; n < 5; n++)\r\n            {\r\n                ImGui::Selectable(names[n]);\r\n                if (ImGui::BeginPopupContextItem()) // <-- use last item id as popup id\r\n                {\r\n                    ImGui::Text(\"This a popup for \\\"%s\\\"!\", names[n]);\r\n                    if (ImGui::Button(\"Close\"))\r\n                        ImGui::CloseCurrentPopup();\r\n                    ImGui::EndPopup();\r\n                }\r\n                if (ImGui::IsItemHovered())\r\n                    ImGui::SetTooltip(\"Right-click to open popup\");\r\n            }\r\n        }\r\n\r\n        // Example 2\r\n        // Popup on a Text() element which doesn't have an identifier: we need to provide an identifier to BeginPopupContextItem().\r\n        // Using an explicit identifier is also convenient if you want to activate the popups from different locations.\r\n        {\r\n            HelpMarker(\"Text() elements don't have stable identifiers so we need to provide one.\");\r\n            static float value = 0.5f;\r\n            ImGui::Text(\"Value = %.3f <-- (1) right-click this value\", value);\r\n            if (ImGui::BeginPopupContextItem(\"my popup\"))\r\n            {\r\n                if (ImGui::Selectable(\"Set to zero\")) value = 0.0f;\r\n                if (ImGui::Selectable(\"Set to PI\")) value = 3.1415f;\r\n                ImGui::SetNextItemWidth(-FLT_MIN);\r\n                ImGui::DragFloat(\"##Value\", &value, 0.1f, 0.0f, 0.0f);\r\n                ImGui::EndPopup();\r\n            }\r\n\r\n            // We can also use OpenPopupOnItemClick() to toggle the visibility of a given popup.\r\n            // Here we make it that right-clicking this other text element opens the same popup as above.\r\n            // The popup itself will be submitted by the code above.\r\n            ImGui::Text(\"(2) Or right-click this text\");\r\n            ImGui::OpenPopupOnItemClick(\"my popup\", ImGuiPopupFlags_MouseButtonRight);\r\n\r\n            // Back to square one: manually open the same popup.\r\n            if (ImGui::Button(\"(3) Or click this button\"))\r\n                ImGui::OpenPopup(\"my popup\");\r\n        }\r\n\r\n        // Example 3\r\n        // When using BeginPopupContextItem() with an implicit identifier (NULL == use last item ID),\r\n        // we need to make sure your item identifier is stable.\r\n        // In this example we showcase altering the item label while preserving its identifier, using the ### operator (see FAQ).\r\n        {\r\n            HelpMarker(\"Showcase using a popup ID linked to item ID, with the item having a changing label + stable ID using the ### operator.\");\r\n            static char name[32] = \"Label1\";\r\n            char buf[64];\r\n            sprintf(buf, \"Button: %s###Button\", name); // ### operator override ID ignoring the preceding label\r\n            ImGui::Button(buf);\r\n            if (ImGui::BeginPopupContextItem())\r\n            {\r\n                ImGui::Text(\"Edit name:\");\r\n                ImGui::InputText(\"##edit\", name, IM_ARRAYSIZE(name));\r\n                if (ImGui::Button(\"Close\"))\r\n                    ImGui::CloseCurrentPopup();\r\n                ImGui::EndPopup();\r\n            }\r\n            ImGui::SameLine(); ImGui::Text(\"(<-- right-click here)\");\r\n        }\r\n\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    IMGUI_DEMO_MARKER(\"Popups/Modals\");\r\n    if (ImGui::TreeNode(\"Modals\"))\r\n    {\r\n        ImGui::TextWrapped(\"Modal windows are like popups but the user cannot close them by clicking outside.\");\r\n\r\n        if (ImGui::Button(\"Delete..\"))\r\n            ImGui::OpenPopup(\"Delete?\");\r\n\r\n        // Always center this window when appearing\r\n        ImVec2 center = ImGui::GetMainViewport()->GetCenter();\r\n        ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));\r\n\r\n        if (ImGui::BeginPopupModal(\"Delete?\", NULL, ImGuiWindowFlags_AlwaysAutoResize))\r\n        {\r\n            ImGui::Text(\"All those beautiful files will be deleted.\\nThis operation cannot be undone!\\n\\n\");\r\n            ImGui::Separator();\r\n\r\n            //static int unused_i = 0;\r\n            //ImGui::Combo(\"Combo\", &unused_i, \"Delete\\0Delete harder\\0\");\r\n\r\n            static bool dont_ask_me_next_time = false;\r\n            ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));\r\n            ImGui::Checkbox(\"Don't ask me next time\", &dont_ask_me_next_time);\r\n            ImGui::PopStyleVar();\r\n\r\n            if (ImGui::Button(\"OK\", ImVec2(120, 0))) { ImGui::CloseCurrentPopup(); }\r\n            ImGui::SetItemDefaultFocus();\r\n            ImGui::SameLine();\r\n            if (ImGui::Button(\"Cancel\", ImVec2(120, 0))) { ImGui::CloseCurrentPopup(); }\r\n            ImGui::EndPopup();\r\n        }\r\n\r\n        if (ImGui::Button(\"Stacked modals..\"))\r\n            ImGui::OpenPopup(\"Stacked 1\");\r\n        if (ImGui::BeginPopupModal(\"Stacked 1\", NULL, ImGuiWindowFlags_MenuBar))\r\n        {\r\n            if (ImGui::BeginMenuBar())\r\n            {\r\n                if (ImGui::BeginMenu(\"File\"))\r\n                {\r\n                    if (ImGui::MenuItem(\"Some menu item\")) {}\r\n                    ImGui::EndMenu();\r\n                }\r\n                ImGui::EndMenuBar();\r\n            }\r\n            ImGui::Text(\"Hello from Stacked The First\\nUsing style.Colors[ImGuiCol_ModalWindowDimBg] behind it.\");\r\n\r\n            // Testing behavior of widgets stacking their own regular popups over the modal.\r\n            static int item = 1;\r\n            static float color[4] = { 0.4f, 0.7f, 0.0f, 0.5f };\r\n            ImGui::Combo(\"Combo\", &item, \"aaaa\\0bbbb\\0cccc\\0dddd\\0eeee\\0\\0\");\r\n            ImGui::ColorEdit4(\"color\", color);\r\n\r\n            if (ImGui::Button(\"Add another modal..\"))\r\n                ImGui::OpenPopup(\"Stacked 2\");\r\n\r\n            // Also demonstrate passing a bool* to BeginPopupModal(), this will create a regular close button which\r\n            // will close the popup. Note that the visibility state of popups is owned by imgui, so the input value\r\n            // of the bool actually doesn't matter here.\r\n            bool unused_open = true;\r\n            if (ImGui::BeginPopupModal(\"Stacked 2\", &unused_open))\r\n            {\r\n                ImGui::Text(\"Hello from Stacked The Second!\");\r\n                if (ImGui::Button(\"Close\"))\r\n                    ImGui::CloseCurrentPopup();\r\n                ImGui::EndPopup();\r\n            }\r\n\r\n            if (ImGui::Button(\"Close\"))\r\n                ImGui::CloseCurrentPopup();\r\n            ImGui::EndPopup();\r\n        }\r\n\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    IMGUI_DEMO_MARKER(\"Popups/Menus inside a regular window\");\r\n    if (ImGui::TreeNode(\"Menus inside a regular window\"))\r\n    {\r\n        ImGui::TextWrapped(\"Below we are testing adding menu items to a regular window. It's rather unusual but should work!\");\r\n        ImGui::Separator();\r\n\r\n        // Note: As a quirk in this very specific example, we want to differentiate the parent of this menu from the\r\n        // parent of the various popup menus above. To do so we are encloding the items in a PushID()/PopID() block\r\n        // to make them two different menusets. If we don't, opening any popup above and hovering our menu here would\r\n        // open it. This is because once a menu is active, we allow to switch to a sibling menu by just hovering on it,\r\n        // which is the desired behavior for regular menus.\r\n        ImGui::PushID(\"foo\");\r\n        ImGui::MenuItem(\"Menu item\", \"CTRL+M\");\r\n        if (ImGui::BeginMenu(\"Menu inside a regular window\"))\r\n        {\r\n            ShowExampleMenuFile();\r\n            ImGui::EndMenu();\r\n        }\r\n        ImGui::PopID();\r\n        ImGui::Separator();\r\n        ImGui::TreePop();\r\n    }\r\n}\r\n\r\n// Dummy data structure that we use for the Table demo.\r\n// (pre-C++11 doesn't allow us to instantiate ImVector<MyItem> template if this structure if defined inside the demo function)\r\nnamespace\r\n{\r\n// We are passing our own identifier to TableSetupColumn() to facilitate identifying columns in the sorting code.\r\n// This identifier will be passed down into ImGuiTableSortSpec::ColumnUserID.\r\n// But it is possible to omit the user id parameter of TableSetupColumn() and just use the column index instead! (ImGuiTableSortSpec::ColumnIndex)\r\n// If you don't use sorting, you will generally never care about giving column an ID!\r\nenum MyItemColumnID\r\n{\r\n    MyItemColumnID_ID,\r\n    MyItemColumnID_Name,\r\n    MyItemColumnID_Action,\r\n    MyItemColumnID_Quantity,\r\n    MyItemColumnID_Description\r\n};\r\n\r\nstruct MyItem\r\n{\r\n    int         ID;\r\n    const char* Name;\r\n    int         Quantity;\r\n\r\n    // We have a problem which is affecting _only this demo_ and should not affect your code:\r\n    // As we don't rely on std:: or other third-party library to compile dear imgui, we only have reliable access to qsort(),\r\n    // however qsort doesn't allow passing user data to comparing function.\r\n    // As a workaround, we are storing the sort specs in a static/global for the comparing function to access.\r\n    // In your own use case you would probably pass the sort specs to your sorting/comparing functions directly and not use a global.\r\n    // We could technically call ImGui::TableGetSortSpecs() in CompareWithSortSpecs(), but considering that this function is called\r\n    // very often by the sorting algorithm it would be a little wasteful.\r\n    static const ImGuiTableSortSpecs* s_current_sort_specs;\r\n\r\n    // Compare function to be used by qsort()\r\n    static int IMGUI_CDECL CompareWithSortSpecs(const void* lhs, const void* rhs)\r\n    {\r\n        const MyItem* a = (const MyItem*)lhs;\r\n        const MyItem* b = (const MyItem*)rhs;\r\n        for (int n = 0; n < s_current_sort_specs->SpecsCount; n++)\r\n        {\r\n            // Here we identify columns using the ColumnUserID value that we ourselves passed to TableSetupColumn()\r\n            // We could also choose to identify columns based on their index (sort_spec->ColumnIndex), which is simpler!\r\n            const ImGuiTableColumnSortSpecs* sort_spec = &s_current_sort_specs->Specs[n];\r\n            int delta = 0;\r\n            switch (sort_spec->ColumnUserID)\r\n            {\r\n            case MyItemColumnID_ID:             delta = (a->ID - b->ID);                break;\r\n            case MyItemColumnID_Name:           delta = (strcmp(a->Name, b->Name));     break;\r\n            case MyItemColumnID_Quantity:       delta = (a->Quantity - b->Quantity);    break;\r\n            case MyItemColumnID_Description:    delta = (strcmp(a->Name, b->Name));     break;\r\n            default: IM_ASSERT(0); break;\r\n            }\r\n            if (delta > 0)\r\n                return (sort_spec->SortDirection == ImGuiSortDirection_Ascending) ? +1 : -1;\r\n            if (delta < 0)\r\n                return (sort_spec->SortDirection == ImGuiSortDirection_Ascending) ? -1 : +1;\r\n        }\r\n\r\n        // qsort() is instable so always return a way to differenciate items.\r\n        // Your own compare function may want to avoid fallback on implicit sort specs e.g. a Name compare if it wasn't already part of the sort specs.\r\n        return (a->ID - b->ID);\r\n    }\r\n};\r\nconst ImGuiTableSortSpecs* MyItem::s_current_sort_specs = NULL;\r\n}\r\n\r\n// Make the UI compact because there are so many fields\r\nstatic void PushStyleCompact()\r\n{\r\n    ImGuiStyle& style = ImGui::GetStyle();\r\n    ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(style.FramePadding.x, (float)(int)(style.FramePadding.y * 0.60f)));\r\n    ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(style.ItemSpacing.x, (float)(int)(style.ItemSpacing.y * 0.60f)));\r\n}\r\n\r\nstatic void PopStyleCompact()\r\n{\r\n    ImGui::PopStyleVar(2);\r\n}\r\n\r\n// Show a combo box with a choice of sizing policies\r\nstatic void EditTableSizingFlags(ImGuiTableFlags* p_flags)\r\n{\r\n    struct EnumDesc { ImGuiTableFlags Value; const char* Name; const char* Tooltip; };\r\n    static const EnumDesc policies[] =\r\n    {\r\n        { ImGuiTableFlags_None,               \"Default\",                            \"Use default sizing policy:\\n- ImGuiTableFlags_SizingFixedFit if ScrollX is on or if host window has ImGuiWindowFlags_AlwaysAutoResize.\\n- ImGuiTableFlags_SizingStretchSame otherwise.\" },\r\n        { ImGuiTableFlags_SizingFixedFit,     \"ImGuiTableFlags_SizingFixedFit\",     \"Columns default to _WidthFixed (if resizable) or _WidthAuto (if not resizable), matching contents width.\" },\r\n        { ImGuiTableFlags_SizingFixedSame,    \"ImGuiTableFlags_SizingFixedSame\",    \"Columns are all the same width, matching the maximum contents width.\\nImplicitly disable ImGuiTableFlags_Resizable and enable ImGuiTableFlags_NoKeepColumnsVisible.\" },\r\n        { ImGuiTableFlags_SizingStretchProp,  \"ImGuiTableFlags_SizingStretchProp\",  \"Columns default to _WidthStretch with weights proportional to their widths.\" },\r\n        { ImGuiTableFlags_SizingStretchSame,  \"ImGuiTableFlags_SizingStretchSame\",  \"Columns default to _WidthStretch with same weights.\" }\r\n    };\r\n    int idx;\r\n    for (idx = 0; idx < IM_ARRAYSIZE(policies); idx++)\r\n        if (policies[idx].Value == (*p_flags & ImGuiTableFlags_SizingMask_))\r\n            break;\r\n    const char* preview_text = (idx < IM_ARRAYSIZE(policies)) ? policies[idx].Name + (idx > 0 ? strlen(\"ImGuiTableFlags\") : 0) : \"\";\r\n    if (ImGui::BeginCombo(\"Sizing Policy\", preview_text))\r\n    {\r\n        for (int n = 0; n < IM_ARRAYSIZE(policies); n++)\r\n            if (ImGui::Selectable(policies[n].Name, idx == n))\r\n                *p_flags = (*p_flags & ~ImGuiTableFlags_SizingMask_) | policies[n].Value;\r\n        ImGui::EndCombo();\r\n    }\r\n    ImGui::SameLine();\r\n    ImGui::TextDisabled(\"(?)\");\r\n    if (ImGui::IsItemHovered())\r\n    {\r\n        ImGui::BeginTooltip();\r\n        ImGui::PushTextWrapPos(ImGui::GetFontSize() * 50.0f);\r\n        for (int m = 0; m < IM_ARRAYSIZE(policies); m++)\r\n        {\r\n            ImGui::Separator();\r\n            ImGui::Text(\"%s:\", policies[m].Name);\r\n            ImGui::Separator();\r\n            ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetStyle().IndentSpacing * 0.5f);\r\n            ImGui::TextUnformatted(policies[m].Tooltip);\r\n        }\r\n        ImGui::PopTextWrapPos();\r\n        ImGui::EndTooltip();\r\n    }\r\n}\r\n\r\nstatic void EditTableColumnsFlags(ImGuiTableColumnFlags* p_flags)\r\n{\r\n    ImGui::CheckboxFlags(\"_Disabled\", p_flags, ImGuiTableColumnFlags_Disabled); ImGui::SameLine(); HelpMarker(\"Master disable flag (also hide from context menu)\");\r\n    ImGui::CheckboxFlags(\"_DefaultHide\", p_flags, ImGuiTableColumnFlags_DefaultHide);\r\n    ImGui::CheckboxFlags(\"_DefaultSort\", p_flags, ImGuiTableColumnFlags_DefaultSort);\r\n    if (ImGui::CheckboxFlags(\"_WidthStretch\", p_flags, ImGuiTableColumnFlags_WidthStretch))\r\n        *p_flags &= ~(ImGuiTableColumnFlags_WidthMask_ ^ ImGuiTableColumnFlags_WidthStretch);\r\n    if (ImGui::CheckboxFlags(\"_WidthFixed\", p_flags, ImGuiTableColumnFlags_WidthFixed))\r\n        *p_flags &= ~(ImGuiTableColumnFlags_WidthMask_ ^ ImGuiTableColumnFlags_WidthFixed);\r\n    ImGui::CheckboxFlags(\"_NoResize\", p_flags, ImGuiTableColumnFlags_NoResize);\r\n    ImGui::CheckboxFlags(\"_NoReorder\", p_flags, ImGuiTableColumnFlags_NoReorder);\r\n    ImGui::CheckboxFlags(\"_NoHide\", p_flags, ImGuiTableColumnFlags_NoHide);\r\n    ImGui::CheckboxFlags(\"_NoClip\", p_flags, ImGuiTableColumnFlags_NoClip);\r\n    ImGui::CheckboxFlags(\"_NoSort\", p_flags, ImGuiTableColumnFlags_NoSort);\r\n    ImGui::CheckboxFlags(\"_NoSortAscending\", p_flags, ImGuiTableColumnFlags_NoSortAscending);\r\n    ImGui::CheckboxFlags(\"_NoSortDescending\", p_flags, ImGuiTableColumnFlags_NoSortDescending);\r\n    ImGui::CheckboxFlags(\"_NoHeaderLabel\", p_flags, ImGuiTableColumnFlags_NoHeaderLabel);\r\n    ImGui::CheckboxFlags(\"_NoHeaderWidth\", p_flags, ImGuiTableColumnFlags_NoHeaderWidth);\r\n    ImGui::CheckboxFlags(\"_PreferSortAscending\", p_flags, ImGuiTableColumnFlags_PreferSortAscending);\r\n    ImGui::CheckboxFlags(\"_PreferSortDescending\", p_flags, ImGuiTableColumnFlags_PreferSortDescending);\r\n    ImGui::CheckboxFlags(\"_IndentEnable\", p_flags, ImGuiTableColumnFlags_IndentEnable); ImGui::SameLine(); HelpMarker(\"Default for column 0\");\r\n    ImGui::CheckboxFlags(\"_IndentDisable\", p_flags, ImGuiTableColumnFlags_IndentDisable); ImGui::SameLine(); HelpMarker(\"Default for column >0\");\r\n}\r\n\r\nstatic void ShowTableColumnsStatusFlags(ImGuiTableColumnFlags flags)\r\n{\r\n    ImGui::CheckboxFlags(\"_IsEnabled\", &flags, ImGuiTableColumnFlags_IsEnabled);\r\n    ImGui::CheckboxFlags(\"_IsVisible\", &flags, ImGuiTableColumnFlags_IsVisible);\r\n    ImGui::CheckboxFlags(\"_IsSorted\", &flags, ImGuiTableColumnFlags_IsSorted);\r\n    ImGui::CheckboxFlags(\"_IsHovered\", &flags, ImGuiTableColumnFlags_IsHovered);\r\n}\r\n\r\nstatic void ShowDemoWindowTables()\r\n{\r\n    //ImGui::SetNextItemOpen(true, ImGuiCond_Once);\r\n    IMGUI_DEMO_MARKER(\"Tables\");\r\n    if (!ImGui::CollapsingHeader(\"Tables & Columns\"))\r\n        return;\r\n\r\n    // Using those as a base value to create width/height that are factor of the size of our font\r\n    const float TEXT_BASE_WIDTH = ImGui::CalcTextSize(\"A\").x;\r\n    const float TEXT_BASE_HEIGHT = ImGui::GetTextLineHeightWithSpacing();\r\n\r\n    ImGui::PushID(\"Tables\");\r\n\r\n    int open_action = -1;\r\n    if (ImGui::Button(\"Open all\"))\r\n        open_action = 1;\r\n    ImGui::SameLine();\r\n    if (ImGui::Button(\"Close all\"))\r\n        open_action = 0;\r\n    ImGui::SameLine();\r\n\r\n    // Options\r\n    static bool disable_indent = false;\r\n    ImGui::Checkbox(\"Disable tree indentation\", &disable_indent);\r\n    ImGui::SameLine();\r\n    HelpMarker(\"Disable the indenting of tree nodes so demo tables can use the full window width.\");\r\n    ImGui::Separator();\r\n    if (disable_indent)\r\n        ImGui::PushStyleVar(ImGuiStyleVar_IndentSpacing, 0.0f);\r\n\r\n    // About Styling of tables\r\n    // Most settings are configured on a per-table basis via the flags passed to BeginTable() and TableSetupColumns APIs.\r\n    // There are however a few settings that a shared and part of the ImGuiStyle structure:\r\n    //   style.CellPadding                          // Padding within each cell\r\n    //   style.Colors[ImGuiCol_TableHeaderBg]       // Table header background\r\n    //   style.Colors[ImGuiCol_TableBorderStrong]   // Table outer and header borders\r\n    //   style.Colors[ImGuiCol_TableBorderLight]    // Table inner borders\r\n    //   style.Colors[ImGuiCol_TableRowBg]          // Table row background when ImGuiTableFlags_RowBg is enabled (even rows)\r\n    //   style.Colors[ImGuiCol_TableRowBgAlt]       // Table row background when ImGuiTableFlags_RowBg is enabled (odds rows)\r\n\r\n    // Demos\r\n    if (open_action != -1)\r\n        ImGui::SetNextItemOpen(open_action != 0);\r\n    IMGUI_DEMO_MARKER(\"Tables/Basic\");\r\n    if (ImGui::TreeNode(\"Basic\"))\r\n    {\r\n        // Here we will showcase three different ways to output a table.\r\n        // They are very simple variations of a same thing!\r\n\r\n        // [Method 1] Using TableNextRow() to create a new row, and TableSetColumnIndex() to select the column.\r\n        // In many situations, this is the most flexible and easy to use pattern.\r\n        HelpMarker(\"Using TableNextRow() + calling TableSetColumnIndex() _before_ each cell, in a loop.\");\r\n        if (ImGui::BeginTable(\"table1\", 3))\r\n        {\r\n            for (int row = 0; row < 4; row++)\r\n            {\r\n                ImGui::TableNextRow();\r\n                for (int column = 0; column < 3; column++)\r\n                {\r\n                    ImGui::TableSetColumnIndex(column);\r\n                    ImGui::Text(\"Row %d Column %d\", row, column);\r\n                }\r\n            }\r\n            ImGui::EndTable();\r\n        }\r\n\r\n        // [Method 2] Using TableNextColumn() called multiple times, instead of using a for loop + TableSetColumnIndex().\r\n        // This is generally more convenient when you have code manually submitting the contents of each columns.\r\n        HelpMarker(\"Using TableNextRow() + calling TableNextColumn() _before_ each cell, manually.\");\r\n        if (ImGui::BeginTable(\"table2\", 3))\r\n        {\r\n            for (int row = 0; row < 4; row++)\r\n            {\r\n                ImGui::TableNextRow();\r\n                ImGui::TableNextColumn();\r\n                ImGui::Text(\"Row %d\", row);\r\n                ImGui::TableNextColumn();\r\n                ImGui::Text(\"Some contents\");\r\n                ImGui::TableNextColumn();\r\n                ImGui::Text(\"123.456\");\r\n            }\r\n            ImGui::EndTable();\r\n        }\r\n\r\n        // [Method 3] We call TableNextColumn() _before_ each cell. We never call TableNextRow(),\r\n        // as TableNextColumn() will automatically wrap around and create new roes as needed.\r\n        // This is generally more convenient when your cells all contains the same type of data.\r\n        HelpMarker(\r\n            \"Only using TableNextColumn(), which tends to be convenient for tables where every cells contains the same type of contents.\\n\"\r\n            \"This is also more similar to the old NextColumn() function of the Columns API, and provided to facilitate the Columns->Tables API transition.\");\r\n        if (ImGui::BeginTable(\"table3\", 3))\r\n        {\r\n            for (int item = 0; item < 14; item++)\r\n            {\r\n                ImGui::TableNextColumn();\r\n                ImGui::Text(\"Item %d\", item);\r\n            }\r\n            ImGui::EndTable();\r\n        }\r\n\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    if (open_action != -1)\r\n        ImGui::SetNextItemOpen(open_action != 0);\r\n    IMGUI_DEMO_MARKER(\"Tables/Borders, background\");\r\n    if (ImGui::TreeNode(\"Borders, background\"))\r\n    {\r\n        // Expose a few Borders related flags interactively\r\n        enum ContentsType { CT_Text, CT_FillButton };\r\n        static ImGuiTableFlags flags = ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg;\r\n        static bool display_headers = false;\r\n        static int contents_type = CT_Text;\r\n\r\n        PushStyleCompact();\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_RowBg\", &flags, ImGuiTableFlags_RowBg);\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_Borders\", &flags, ImGuiTableFlags_Borders);\r\n        ImGui::SameLine(); HelpMarker(\"ImGuiTableFlags_Borders\\n = ImGuiTableFlags_BordersInnerV\\n | ImGuiTableFlags_BordersOuterV\\n | ImGuiTableFlags_BordersInnerV\\n | ImGuiTableFlags_BordersOuterH\");\r\n        ImGui::Indent();\r\n\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_BordersH\", &flags, ImGuiTableFlags_BordersH);\r\n        ImGui::Indent();\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_BordersOuterH\", &flags, ImGuiTableFlags_BordersOuterH);\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_BordersInnerH\", &flags, ImGuiTableFlags_BordersInnerH);\r\n        ImGui::Unindent();\r\n\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_BordersV\", &flags, ImGuiTableFlags_BordersV);\r\n        ImGui::Indent();\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_BordersOuterV\", &flags, ImGuiTableFlags_BordersOuterV);\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_BordersInnerV\", &flags, ImGuiTableFlags_BordersInnerV);\r\n        ImGui::Unindent();\r\n\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_BordersOuter\", &flags, ImGuiTableFlags_BordersOuter);\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_BordersInner\", &flags, ImGuiTableFlags_BordersInner);\r\n        ImGui::Unindent();\r\n\r\n        ImGui::AlignTextToFramePadding(); ImGui::Text(\"Cell contents:\");\r\n        ImGui::SameLine(); ImGui::RadioButton(\"Text\", &contents_type, CT_Text);\r\n        ImGui::SameLine(); ImGui::RadioButton(\"FillButton\", &contents_type, CT_FillButton);\r\n        ImGui::Checkbox(\"Display headers\", &display_headers);\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_NoBordersInBody\", &flags, ImGuiTableFlags_NoBordersInBody); ImGui::SameLine(); HelpMarker(\"Disable vertical borders in columns Body (borders will always appears in Headers\");\r\n        PopStyleCompact();\r\n\r\n        if (ImGui::BeginTable(\"table1\", 3, flags))\r\n        {\r\n            // Display headers so we can inspect their interaction with borders.\r\n            // (Headers are not the main purpose of this section of the demo, so we are not elaborating on them too much. See other sections for details)\r\n            if (display_headers)\r\n            {\r\n                ImGui::TableSetupColumn(\"One\");\r\n                ImGui::TableSetupColumn(\"Two\");\r\n                ImGui::TableSetupColumn(\"Three\");\r\n                ImGui::TableHeadersRow();\r\n            }\r\n\r\n            for (int row = 0; row < 5; row++)\r\n            {\r\n                ImGui::TableNextRow();\r\n                for (int column = 0; column < 3; column++)\r\n                {\r\n                    ImGui::TableSetColumnIndex(column);\r\n                    char buf[32];\r\n                    sprintf(buf, \"Hello %d,%d\", column, row);\r\n                    if (contents_type == CT_Text)\r\n                        ImGui::TextUnformatted(buf);\r\n                    else if (contents_type)\r\n                        ImGui::Button(buf, ImVec2(-FLT_MIN, 0.0f));\r\n                }\r\n            }\r\n            ImGui::EndTable();\r\n        }\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    if (open_action != -1)\r\n        ImGui::SetNextItemOpen(open_action != 0);\r\n    IMGUI_DEMO_MARKER(\"Tables/Resizable, stretch\");\r\n    if (ImGui::TreeNode(\"Resizable, stretch\"))\r\n    {\r\n        // By default, if we don't enable ScrollX the sizing policy for each columns is \"Stretch\"\r\n        // Each columns maintain a sizing weight, and they will occupy all available width.\r\n        static ImGuiTableFlags flags = ImGuiTableFlags_SizingStretchSame | ImGuiTableFlags_Resizable | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_ContextMenuInBody;\r\n        PushStyleCompact();\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_Resizable\", &flags, ImGuiTableFlags_Resizable);\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_BordersV\", &flags, ImGuiTableFlags_BordersV);\r\n        ImGui::SameLine(); HelpMarker(\"Using the _Resizable flag automatically enables the _BordersInnerV flag as well, this is why the resize borders are still showing when unchecking this.\");\r\n        PopStyleCompact();\r\n\r\n        if (ImGui::BeginTable(\"table1\", 3, flags))\r\n        {\r\n            for (int row = 0; row < 5; row++)\r\n            {\r\n                ImGui::TableNextRow();\r\n                for (int column = 0; column < 3; column++)\r\n                {\r\n                    ImGui::TableSetColumnIndex(column);\r\n                    ImGui::Text(\"Hello %d,%d\", column, row);\r\n                }\r\n            }\r\n            ImGui::EndTable();\r\n        }\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    if (open_action != -1)\r\n        ImGui::SetNextItemOpen(open_action != 0);\r\n    IMGUI_DEMO_MARKER(\"Tables/Resizable, fixed\");\r\n    if (ImGui::TreeNode(\"Resizable, fixed\"))\r\n    {\r\n        // Here we use ImGuiTableFlags_SizingFixedFit (even though _ScrollX is not set)\r\n        // So columns will adopt the \"Fixed\" policy and will maintain a fixed width regardless of the whole available width (unless table is small)\r\n        // If there is not enough available width to fit all columns, they will however be resized down.\r\n        // FIXME-TABLE: Providing a stretch-on-init would make sense especially for tables which don't have saved settings\r\n        HelpMarker(\r\n            \"Using _Resizable + _SizingFixedFit flags.\\n\"\r\n            \"Fixed-width columns generally makes more sense if you want to use horizontal scrolling.\\n\\n\"\r\n            \"Double-click a column border to auto-fit the column to its contents.\");\r\n        PushStyleCompact();\r\n        static ImGuiTableFlags flags = ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Resizable | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_ContextMenuInBody;\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_NoHostExtendX\", &flags, ImGuiTableFlags_NoHostExtendX);\r\n        PopStyleCompact();\r\n\r\n        if (ImGui::BeginTable(\"table1\", 3, flags))\r\n        {\r\n            for (int row = 0; row < 5; row++)\r\n            {\r\n                ImGui::TableNextRow();\r\n                for (int column = 0; column < 3; column++)\r\n                {\r\n                    ImGui::TableSetColumnIndex(column);\r\n                    ImGui::Text(\"Hello %d,%d\", column, row);\r\n                }\r\n            }\r\n            ImGui::EndTable();\r\n        }\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    if (open_action != -1)\r\n        ImGui::SetNextItemOpen(open_action != 0);\r\n    IMGUI_DEMO_MARKER(\"Tables/Resizable, mixed\");\r\n    if (ImGui::TreeNode(\"Resizable, mixed\"))\r\n    {\r\n        HelpMarker(\r\n            \"Using TableSetupColumn() to alter resizing policy on a per-column basis.\\n\\n\"\r\n            \"When combining Fixed and Stretch columns, generally you only want one, maybe two trailing columns to use _WidthStretch.\");\r\n        static ImGuiTableFlags flags = ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable;\r\n\r\n        if (ImGui::BeginTable(\"table1\", 3, flags))\r\n        {\r\n            ImGui::TableSetupColumn(\"AAA\", ImGuiTableColumnFlags_WidthFixed);\r\n            ImGui::TableSetupColumn(\"BBB\", ImGuiTableColumnFlags_WidthFixed);\r\n            ImGui::TableSetupColumn(\"CCC\", ImGuiTableColumnFlags_WidthStretch);\r\n            ImGui::TableHeadersRow();\r\n            for (int row = 0; row < 5; row++)\r\n            {\r\n                ImGui::TableNextRow();\r\n                for (int column = 0; column < 3; column++)\r\n                {\r\n                    ImGui::TableSetColumnIndex(column);\r\n                    ImGui::Text(\"%s %d,%d\", (column == 2) ? \"Stretch\" : \"Fixed\", column, row);\r\n                }\r\n            }\r\n            ImGui::EndTable();\r\n        }\r\n        if (ImGui::BeginTable(\"table2\", 6, flags))\r\n        {\r\n            ImGui::TableSetupColumn(\"AAA\", ImGuiTableColumnFlags_WidthFixed);\r\n            ImGui::TableSetupColumn(\"BBB\", ImGuiTableColumnFlags_WidthFixed);\r\n            ImGui::TableSetupColumn(\"CCC\", ImGuiTableColumnFlags_WidthFixed | ImGuiTableColumnFlags_DefaultHide);\r\n            ImGui::TableSetupColumn(\"DDD\", ImGuiTableColumnFlags_WidthStretch);\r\n            ImGui::TableSetupColumn(\"EEE\", ImGuiTableColumnFlags_WidthStretch);\r\n            ImGui::TableSetupColumn(\"FFF\", ImGuiTableColumnFlags_WidthStretch | ImGuiTableColumnFlags_DefaultHide);\r\n            ImGui::TableHeadersRow();\r\n            for (int row = 0; row < 5; row++)\r\n            {\r\n                ImGui::TableNextRow();\r\n                for (int column = 0; column < 6; column++)\r\n                {\r\n                    ImGui::TableSetColumnIndex(column);\r\n                    ImGui::Text(\"%s %d,%d\", (column >= 3) ? \"Stretch\" : \"Fixed\", column, row);\r\n                }\r\n            }\r\n            ImGui::EndTable();\r\n        }\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    if (open_action != -1)\r\n        ImGui::SetNextItemOpen(open_action != 0);\r\n    IMGUI_DEMO_MARKER(\"Tables/Reorderable, hideable, with headers\");\r\n    if (ImGui::TreeNode(\"Reorderable, hideable, with headers\"))\r\n    {\r\n        HelpMarker(\r\n            \"Click and drag column headers to reorder columns.\\n\\n\"\r\n            \"Right-click on a header to open a context menu.\");\r\n        static ImGuiTableFlags flags = ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV;\r\n        PushStyleCompact();\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_Resizable\", &flags, ImGuiTableFlags_Resizable);\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_Reorderable\", &flags, ImGuiTableFlags_Reorderable);\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_Hideable\", &flags, ImGuiTableFlags_Hideable);\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_NoBordersInBody\", &flags, ImGuiTableFlags_NoBordersInBody);\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_NoBordersInBodyUntilResize\", &flags, ImGuiTableFlags_NoBordersInBodyUntilResize); ImGui::SameLine(); HelpMarker(\"Disable vertical borders in columns Body until hovered for resize (borders will always appears in Headers)\");\r\n        PopStyleCompact();\r\n\r\n        if (ImGui::BeginTable(\"table1\", 3, flags))\r\n        {\r\n            // Submit columns name with TableSetupColumn() and call TableHeadersRow() to create a row with a header in each column.\r\n            // (Later we will show how TableSetupColumn() has other uses, optional flags, sizing weight etc.)\r\n            ImGui::TableSetupColumn(\"One\");\r\n            ImGui::TableSetupColumn(\"Two\");\r\n            ImGui::TableSetupColumn(\"Three\");\r\n            ImGui::TableHeadersRow();\r\n            for (int row = 0; row < 6; row++)\r\n            {\r\n                ImGui::TableNextRow();\r\n                for (int column = 0; column < 3; column++)\r\n                {\r\n                    ImGui::TableSetColumnIndex(column);\r\n                    ImGui::Text(\"Hello %d,%d\", column, row);\r\n                }\r\n            }\r\n            ImGui::EndTable();\r\n        }\r\n\r\n        // Use outer_size.x == 0.0f instead of default to make the table as tight as possible (only valid when no scrolling and no stretch column)\r\n        if (ImGui::BeginTable(\"table2\", 3, flags | ImGuiTableFlags_SizingFixedFit, ImVec2(0.0f, 0.0f)))\r\n        {\r\n            ImGui::TableSetupColumn(\"One\");\r\n            ImGui::TableSetupColumn(\"Two\");\r\n            ImGui::TableSetupColumn(\"Three\");\r\n            ImGui::TableHeadersRow();\r\n            for (int row = 0; row < 6; row++)\r\n            {\r\n                ImGui::TableNextRow();\r\n                for (int column = 0; column < 3; column++)\r\n                {\r\n                    ImGui::TableSetColumnIndex(column);\r\n                    ImGui::Text(\"Fixed %d,%d\", column, row);\r\n                }\r\n            }\r\n            ImGui::EndTable();\r\n        }\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    if (open_action != -1)\r\n        ImGui::SetNextItemOpen(open_action != 0);\r\n    IMGUI_DEMO_MARKER(\"Tables/Padding\");\r\n    if (ImGui::TreeNode(\"Padding\"))\r\n    {\r\n        // First example: showcase use of padding flags and effect of BorderOuterV/BorderInnerV on X padding.\r\n        // We don't expose BorderOuterH/BorderInnerH here because they have no effect on X padding.\r\n        HelpMarker(\r\n            \"We often want outer padding activated when any using features which makes the edges of a column visible:\\n\"\r\n            \"e.g.:\\n\"\r\n            \"- BorderOuterV\\n\"\r\n            \"- any form of row selection\\n\"\r\n            \"Because of this, activating BorderOuterV sets the default to PadOuterX. Using PadOuterX or NoPadOuterX you can override the default.\\n\\n\"\r\n            \"Actual padding values are using style.CellPadding.\\n\\n\"\r\n            \"In this demo we don't show horizontal borders to emphasis how they don't affect default horizontal padding.\");\r\n\r\n        static ImGuiTableFlags flags1 = ImGuiTableFlags_BordersV;\r\n        PushStyleCompact();\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_PadOuterX\", &flags1, ImGuiTableFlags_PadOuterX);\r\n        ImGui::SameLine(); HelpMarker(\"Enable outer-most padding (default if ImGuiTableFlags_BordersOuterV is set)\");\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_NoPadOuterX\", &flags1, ImGuiTableFlags_NoPadOuterX);\r\n        ImGui::SameLine(); HelpMarker(\"Disable outer-most padding (default if ImGuiTableFlags_BordersOuterV is not set)\");\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_NoPadInnerX\", &flags1, ImGuiTableFlags_NoPadInnerX);\r\n        ImGui::SameLine(); HelpMarker(\"Disable inner padding between columns (double inner padding if BordersOuterV is on, single inner padding if BordersOuterV is off)\");\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_BordersOuterV\", &flags1, ImGuiTableFlags_BordersOuterV);\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_BordersInnerV\", &flags1, ImGuiTableFlags_BordersInnerV);\r\n        static bool show_headers = false;\r\n        ImGui::Checkbox(\"show_headers\", &show_headers);\r\n        PopStyleCompact();\r\n\r\n        if (ImGui::BeginTable(\"table_padding\", 3, flags1))\r\n        {\r\n            if (show_headers)\r\n            {\r\n                ImGui::TableSetupColumn(\"One\");\r\n                ImGui::TableSetupColumn(\"Two\");\r\n                ImGui::TableSetupColumn(\"Three\");\r\n                ImGui::TableHeadersRow();\r\n            }\r\n\r\n            for (int row = 0; row < 5; row++)\r\n            {\r\n                ImGui::TableNextRow();\r\n                for (int column = 0; column < 3; column++)\r\n                {\r\n                    ImGui::TableSetColumnIndex(column);\r\n                    if (row == 0)\r\n                    {\r\n                        ImGui::Text(\"Avail %.2f\", ImGui::GetContentRegionAvail().x);\r\n                    }\r\n                    else\r\n                    {\r\n                        char buf[32];\r\n                        sprintf(buf, \"Hello %d,%d\", column, row);\r\n                        ImGui::Button(buf, ImVec2(-FLT_MIN, 0.0f));\r\n                    }\r\n                    //if (ImGui::TableGetColumnFlags() & ImGuiTableColumnFlags_IsHovered)\r\n                    //    ImGui::TableSetBgColor(ImGuiTableBgTarget_CellBg, IM_COL32(0, 100, 0, 255));\r\n                }\r\n            }\r\n            ImGui::EndTable();\r\n        }\r\n\r\n        // Second example: set style.CellPadding to (0.0) or a custom value.\r\n        // FIXME-TABLE: Vertical border effectively not displayed the same way as horizontal one...\r\n        HelpMarker(\"Setting style.CellPadding to (0,0) or a custom value.\");\r\n        static ImGuiTableFlags flags2 = ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg;\r\n        static ImVec2 cell_padding(0.0f, 0.0f);\r\n        static bool show_widget_frame_bg = true;\r\n\r\n        PushStyleCompact();\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_Borders\", &flags2, ImGuiTableFlags_Borders);\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_BordersH\", &flags2, ImGuiTableFlags_BordersH);\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_BordersV\", &flags2, ImGuiTableFlags_BordersV);\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_BordersInner\", &flags2, ImGuiTableFlags_BordersInner);\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_BordersOuter\", &flags2, ImGuiTableFlags_BordersOuter);\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_RowBg\", &flags2, ImGuiTableFlags_RowBg);\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_Resizable\", &flags2, ImGuiTableFlags_Resizable);\r\n        ImGui::Checkbox(\"show_widget_frame_bg\", &show_widget_frame_bg);\r\n        ImGui::SliderFloat2(\"CellPadding\", &cell_padding.x, 0.0f, 10.0f, \"%.0f\");\r\n        PopStyleCompact();\r\n\r\n        ImGui::PushStyleVar(ImGuiStyleVar_CellPadding, cell_padding);\r\n        if (ImGui::BeginTable(\"table_padding_2\", 3, flags2))\r\n        {\r\n            static char text_bufs[3 * 5][16]; // Mini text storage for 3x5 cells\r\n            static bool init = true;\r\n            if (!show_widget_frame_bg)\r\n                ImGui::PushStyleColor(ImGuiCol_FrameBg, 0);\r\n            for (int cell = 0; cell < 3 * 5; cell++)\r\n            {\r\n                ImGui::TableNextColumn();\r\n                if (init)\r\n                    strcpy(text_bufs[cell], \"edit me\");\r\n                ImGui::SetNextItemWidth(-FLT_MIN);\r\n                ImGui::PushID(cell);\r\n                ImGui::InputText(\"##cell\", text_bufs[cell], IM_ARRAYSIZE(text_bufs[cell]));\r\n                ImGui::PopID();\r\n            }\r\n            if (!show_widget_frame_bg)\r\n                ImGui::PopStyleColor();\r\n            init = false;\r\n            ImGui::EndTable();\r\n        }\r\n        ImGui::PopStyleVar();\r\n\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    if (open_action != -1)\r\n        ImGui::SetNextItemOpen(open_action != 0);\r\n    IMGUI_DEMO_MARKER(\"Tables/Explicit widths\");\r\n    if (ImGui::TreeNode(\"Sizing policies\"))\r\n    {\r\n        static ImGuiTableFlags flags1 = ImGuiTableFlags_BordersV | ImGuiTableFlags_BordersOuterH | ImGuiTableFlags_RowBg | ImGuiTableFlags_ContextMenuInBody;\r\n        PushStyleCompact();\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_Resizable\", &flags1, ImGuiTableFlags_Resizable);\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_NoHostExtendX\", &flags1, ImGuiTableFlags_NoHostExtendX);\r\n        PopStyleCompact();\r\n\r\n        static ImGuiTableFlags sizing_policy_flags[4] = { ImGuiTableFlags_SizingFixedFit, ImGuiTableFlags_SizingFixedSame, ImGuiTableFlags_SizingStretchProp, ImGuiTableFlags_SizingStretchSame };\r\n        for (int table_n = 0; table_n < 4; table_n++)\r\n        {\r\n            ImGui::PushID(table_n);\r\n            ImGui::SetNextItemWidth(TEXT_BASE_WIDTH * 30);\r\n            EditTableSizingFlags(&sizing_policy_flags[table_n]);\r\n\r\n            // To make it easier to understand the different sizing policy,\r\n            // For each policy: we display one table where the columns have equal contents width, and one where the columns have different contents width.\r\n            if (ImGui::BeginTable(\"table1\", 3, sizing_policy_flags[table_n] | flags1))\r\n            {\r\n                for (int row = 0; row < 3; row++)\r\n                {\r\n                    ImGui::TableNextRow();\r\n                    ImGui::TableNextColumn(); ImGui::Text(\"Oh dear\");\r\n                    ImGui::TableNextColumn(); ImGui::Text(\"Oh dear\");\r\n                    ImGui::TableNextColumn(); ImGui::Text(\"Oh dear\");\r\n                }\r\n                ImGui::EndTable();\r\n            }\r\n            if (ImGui::BeginTable(\"table2\", 3, sizing_policy_flags[table_n] | flags1))\r\n            {\r\n                for (int row = 0; row < 3; row++)\r\n                {\r\n                    ImGui::TableNextRow();\r\n                    ImGui::TableNextColumn(); ImGui::Text(\"AAAA\");\r\n                    ImGui::TableNextColumn(); ImGui::Text(\"BBBBBBBB\");\r\n                    ImGui::TableNextColumn(); ImGui::Text(\"CCCCCCCCCCCC\");\r\n                }\r\n                ImGui::EndTable();\r\n            }\r\n            ImGui::PopID();\r\n        }\r\n\r\n        ImGui::Spacing();\r\n        ImGui::TextUnformatted(\"Advanced\");\r\n        ImGui::SameLine();\r\n        HelpMarker(\"This section allows you to interact and see the effect of various sizing policies depending on whether Scroll is enabled and the contents of your columns.\");\r\n\r\n        enum ContentsType { CT_ShowWidth, CT_ShortText, CT_LongText, CT_Button, CT_FillButton, CT_InputText };\r\n        static ImGuiTableFlags flags = ImGuiTableFlags_ScrollY | ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_Resizable;\r\n        static int contents_type = CT_ShowWidth;\r\n        static int column_count = 3;\r\n\r\n        PushStyleCompact();\r\n        ImGui::PushID(\"Advanced\");\r\n        ImGui::PushItemWidth(TEXT_BASE_WIDTH * 30);\r\n        EditTableSizingFlags(&flags);\r\n        ImGui::Combo(\"Contents\", &contents_type, \"Show width\\0Short Text\\0Long Text\\0Button\\0Fill Button\\0InputText\\0\");\r\n        if (contents_type == CT_FillButton)\r\n        {\r\n            ImGui::SameLine();\r\n            HelpMarker(\"Be mindful that using right-alignment (e.g. size.x = -FLT_MIN) creates a feedback loop where contents width can feed into auto-column width can feed into contents width.\");\r\n        }\r\n        ImGui::DragInt(\"Columns\", &column_count, 0.1f, 1, 64, \"%d\", ImGuiSliderFlags_AlwaysClamp);\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_Resizable\", &flags, ImGuiTableFlags_Resizable);\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_PreciseWidths\", &flags, ImGuiTableFlags_PreciseWidths);\r\n        ImGui::SameLine(); HelpMarker(\"Disable distributing remainder width to stretched columns (width allocation on a 100-wide table with 3 columns: Without this flag: 33,33,34. With this flag: 33,33,33). With larger number of columns, resizing will appear to be less smooth.\");\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_ScrollX\", &flags, ImGuiTableFlags_ScrollX);\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_ScrollY\", &flags, ImGuiTableFlags_ScrollY);\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_NoClip\", &flags, ImGuiTableFlags_NoClip);\r\n        ImGui::PopItemWidth();\r\n        ImGui::PopID();\r\n        PopStyleCompact();\r\n\r\n        if (ImGui::BeginTable(\"table2\", column_count, flags, ImVec2(0.0f, TEXT_BASE_HEIGHT * 7)))\r\n        {\r\n            for (int cell = 0; cell < 10 * column_count; cell++)\r\n            {\r\n                ImGui::TableNextColumn();\r\n                int column = ImGui::TableGetColumnIndex();\r\n                int row = ImGui::TableGetRowIndex();\r\n\r\n                ImGui::PushID(cell);\r\n                char label[32];\r\n                static char text_buf[32] = \"\";\r\n                sprintf(label, \"Hello %d,%d\", column, row);\r\n                switch (contents_type)\r\n                {\r\n                case CT_ShortText:  ImGui::TextUnformatted(label); break;\r\n                case CT_LongText:   ImGui::Text(\"Some %s text %d,%d\\nOver two lines..\", column == 0 ? \"long\" : \"longeeer\", column, row); break;\r\n                case CT_ShowWidth:  ImGui::Text(\"W: %.1f\", ImGui::GetContentRegionAvail().x); break;\r\n                case CT_Button:     ImGui::Button(label); break;\r\n                case CT_FillButton: ImGui::Button(label, ImVec2(-FLT_MIN, 0.0f)); break;\r\n                case CT_InputText:  ImGui::SetNextItemWidth(-FLT_MIN); ImGui::InputText(\"##\", text_buf, IM_ARRAYSIZE(text_buf)); break;\r\n                }\r\n                ImGui::PopID();\r\n            }\r\n            ImGui::EndTable();\r\n        }\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    if (open_action != -1)\r\n        ImGui::SetNextItemOpen(open_action != 0);\r\n    IMGUI_DEMO_MARKER(\"Tables/Vertical scrolling, with clipping\");\r\n    if (ImGui::TreeNode(\"Vertical scrolling, with clipping\"))\r\n    {\r\n        HelpMarker(\"Here we activate ScrollY, which will create a child window container to allow hosting scrollable contents.\\n\\nWe also demonstrate using ImGuiListClipper to virtualize the submission of many items.\");\r\n        static ImGuiTableFlags flags = ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable;\r\n\r\n        PushStyleCompact();\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_ScrollY\", &flags, ImGuiTableFlags_ScrollY);\r\n        PopStyleCompact();\r\n\r\n        // When using ScrollX or ScrollY we need to specify a size for our table container!\r\n        // Otherwise by default the table will fit all available space, like a BeginChild() call.\r\n        ImVec2 outer_size = ImVec2(0.0f, TEXT_BASE_HEIGHT * 8);\r\n        if (ImGui::BeginTable(\"table_scrolly\", 3, flags, outer_size))\r\n        {\r\n            ImGui::TableSetupScrollFreeze(0, 1); // Make top row always visible\r\n            ImGui::TableSetupColumn(\"One\", ImGuiTableColumnFlags_None);\r\n            ImGui::TableSetupColumn(\"Two\", ImGuiTableColumnFlags_None);\r\n            ImGui::TableSetupColumn(\"Three\", ImGuiTableColumnFlags_None);\r\n            ImGui::TableHeadersRow();\r\n\r\n            // Demonstrate using clipper for large vertical lists\r\n            ImGuiListClipper clipper;\r\n            clipper.Begin(1000);\r\n            while (clipper.Step())\r\n            {\r\n                for (int row = clipper.DisplayStart; row < clipper.DisplayEnd; row++)\r\n                {\r\n                    ImGui::TableNextRow();\r\n                    for (int column = 0; column < 3; column++)\r\n                    {\r\n                        ImGui::TableSetColumnIndex(column);\r\n                        ImGui::Text(\"Hello %d,%d\", column, row);\r\n                    }\r\n                }\r\n            }\r\n            ImGui::EndTable();\r\n        }\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    if (open_action != -1)\r\n        ImGui::SetNextItemOpen(open_action != 0);\r\n    IMGUI_DEMO_MARKER(\"Tables/Horizontal scrolling\");\r\n    if (ImGui::TreeNode(\"Horizontal scrolling\"))\r\n    {\r\n        HelpMarker(\r\n            \"When ScrollX is enabled, the default sizing policy becomes ImGuiTableFlags_SizingFixedFit, \"\r\n            \"as automatically stretching columns doesn't make much sense with horizontal scrolling.\\n\\n\"\r\n            \"Also note that as of the current version, you will almost always want to enable ScrollY along with ScrollX,\"\r\n            \"because the container window won't automatically extend vertically to fix contents (this may be improved in future versions).\");\r\n        static ImGuiTableFlags flags = ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable;\r\n        static int freeze_cols = 1;\r\n        static int freeze_rows = 1;\r\n\r\n        PushStyleCompact();\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_Resizable\", &flags, ImGuiTableFlags_Resizable);\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_ScrollX\", &flags, ImGuiTableFlags_ScrollX);\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_ScrollY\", &flags, ImGuiTableFlags_ScrollY);\r\n        ImGui::SetNextItemWidth(ImGui::GetFrameHeight());\r\n        ImGui::DragInt(\"freeze_cols\", &freeze_cols, 0.2f, 0, 9, NULL, ImGuiSliderFlags_NoInput);\r\n        ImGui::SetNextItemWidth(ImGui::GetFrameHeight());\r\n        ImGui::DragInt(\"freeze_rows\", &freeze_rows, 0.2f, 0, 9, NULL, ImGuiSliderFlags_NoInput);\r\n        PopStyleCompact();\r\n\r\n        // When using ScrollX or ScrollY we need to specify a size for our table container!\r\n        // Otherwise by default the table will fit all available space, like a BeginChild() call.\r\n        ImVec2 outer_size = ImVec2(0.0f, TEXT_BASE_HEIGHT * 8);\r\n        if (ImGui::BeginTable(\"table_scrollx\", 7, flags, outer_size))\r\n        {\r\n            ImGui::TableSetupScrollFreeze(freeze_cols, freeze_rows);\r\n            ImGui::TableSetupColumn(\"Line #\", ImGuiTableColumnFlags_NoHide); // Make the first column not hideable to match our use of TableSetupScrollFreeze()\r\n            ImGui::TableSetupColumn(\"One\");\r\n            ImGui::TableSetupColumn(\"Two\");\r\n            ImGui::TableSetupColumn(\"Three\");\r\n            ImGui::TableSetupColumn(\"Four\");\r\n            ImGui::TableSetupColumn(\"Five\");\r\n            ImGui::TableSetupColumn(\"Six\");\r\n            ImGui::TableHeadersRow();\r\n            for (int row = 0; row < 20; row++)\r\n            {\r\n                ImGui::TableNextRow();\r\n                for (int column = 0; column < 7; column++)\r\n                {\r\n                    // Both TableNextColumn() and TableSetColumnIndex() return true when a column is visible or performing width measurement.\r\n                    // Because here we know that:\r\n                    // - A) all our columns are contributing the same to row height\r\n                    // - B) column 0 is always visible,\r\n                    // We only always submit this one column and can skip others.\r\n                    // More advanced per-column clipping behaviors may benefit from polling the status flags via TableGetColumnFlags().\r\n                    if (!ImGui::TableSetColumnIndex(column) && column > 0)\r\n                        continue;\r\n                    if (column == 0)\r\n                        ImGui::Text(\"Line %d\", row);\r\n                    else\r\n                        ImGui::Text(\"Hello world %d,%d\", column, row);\r\n                }\r\n            }\r\n            ImGui::EndTable();\r\n        }\r\n\r\n        ImGui::Spacing();\r\n        ImGui::TextUnformatted(\"Stretch + ScrollX\");\r\n        ImGui::SameLine();\r\n        HelpMarker(\r\n            \"Showcase using Stretch columns + ScrollX together: \"\r\n            \"this is rather unusual and only makes sense when specifying an 'inner_width' for the table!\\n\"\r\n            \"Without an explicit value, inner_width is == outer_size.x and therefore using Stretch columns + ScrollX together doesn't make sense.\");\r\n        static ImGuiTableFlags flags2 = ImGuiTableFlags_SizingStretchSame | ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_RowBg | ImGuiTableFlags_ContextMenuInBody;\r\n        static float inner_width = 1000.0f;\r\n        PushStyleCompact();\r\n        ImGui::PushID(\"flags3\");\r\n        ImGui::PushItemWidth(TEXT_BASE_WIDTH * 30);\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_ScrollX\", &flags2, ImGuiTableFlags_ScrollX);\r\n        ImGui::DragFloat(\"inner_width\", &inner_width, 1.0f, 0.0f, FLT_MAX, \"%.1f\");\r\n        ImGui::PopItemWidth();\r\n        ImGui::PopID();\r\n        PopStyleCompact();\r\n        if (ImGui::BeginTable(\"table2\", 7, flags2, outer_size, inner_width))\r\n        {\r\n            for (int cell = 0; cell < 20 * 7; cell++)\r\n            {\r\n                ImGui::TableNextColumn();\r\n                ImGui::Text(\"Hello world %d,%d\", ImGui::TableGetColumnIndex(), ImGui::TableGetRowIndex());\r\n            }\r\n            ImGui::EndTable();\r\n        }\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    if (open_action != -1)\r\n        ImGui::SetNextItemOpen(open_action != 0);\r\n    IMGUI_DEMO_MARKER(\"Tables/Columns flags\");\r\n    if (ImGui::TreeNode(\"Columns flags\"))\r\n    {\r\n        // Create a first table just to show all the options/flags we want to make visible in our example!\r\n        const int column_count = 3;\r\n        const char* column_names[column_count] = { \"One\", \"Two\", \"Three\" };\r\n        static ImGuiTableColumnFlags column_flags[column_count] = { ImGuiTableColumnFlags_DefaultSort, ImGuiTableColumnFlags_None, ImGuiTableColumnFlags_DefaultHide };\r\n        static ImGuiTableColumnFlags column_flags_out[column_count] = { 0, 0, 0 }; // Output from TableGetColumnFlags()\r\n\r\n        if (ImGui::BeginTable(\"table_columns_flags_checkboxes\", column_count, ImGuiTableFlags_None))\r\n        {\r\n            PushStyleCompact();\r\n            for (int column = 0; column < column_count; column++)\r\n            {\r\n                ImGui::TableNextColumn();\r\n                ImGui::PushID(column);\r\n                ImGui::AlignTextToFramePadding(); // FIXME-TABLE: Workaround for wrong text baseline propagation\r\n                ImGui::Text(\"'%s'\", column_names[column]);\r\n                ImGui::Spacing();\r\n                ImGui::Text(\"Input flags:\");\r\n                EditTableColumnsFlags(&column_flags[column]);\r\n                ImGui::Spacing();\r\n                ImGui::Text(\"Output flags:\");\r\n                ShowTableColumnsStatusFlags(column_flags_out[column]);\r\n                ImGui::PopID();\r\n            }\r\n            PopStyleCompact();\r\n            ImGui::EndTable();\r\n        }\r\n\r\n        // Create the real table we care about for the example!\r\n        // We use a scrolling table to be able to showcase the difference between the _IsEnabled and _IsVisible flags above, otherwise in\r\n        // a non-scrolling table columns are always visible (unless using ImGuiTableFlags_NoKeepColumnsVisible + resizing the parent window down)\r\n        const ImGuiTableFlags flags\r\n            = ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY\r\n            | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV\r\n            | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Sortable;\r\n        ImVec2 outer_size = ImVec2(0.0f, TEXT_BASE_HEIGHT * 9);\r\n        if (ImGui::BeginTable(\"table_columns_flags\", column_count, flags, outer_size))\r\n        {\r\n            for (int column = 0; column < column_count; column++)\r\n                ImGui::TableSetupColumn(column_names[column], column_flags[column]);\r\n            ImGui::TableHeadersRow();\r\n            for (int column = 0; column < column_count; column++)\r\n                column_flags_out[column] = ImGui::TableGetColumnFlags(column);\r\n            float indent_step = (float)((int)TEXT_BASE_WIDTH / 2);\r\n            for (int row = 0; row < 8; row++)\r\n            {\r\n                ImGui::Indent(indent_step); // Add some indentation to demonstrate usage of per-column IndentEnable/IndentDisable flags.\r\n                ImGui::TableNextRow();\r\n                for (int column = 0; column < column_count; column++)\r\n                {\r\n                    ImGui::TableSetColumnIndex(column);\r\n                    ImGui::Text(\"%s %s\", (column == 0) ? \"Indented\" : \"Hello\", ImGui::TableGetColumnName(column));\r\n                }\r\n            }\r\n            ImGui::Unindent(indent_step * 8.0f);\r\n\r\n            ImGui::EndTable();\r\n        }\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    if (open_action != -1)\r\n        ImGui::SetNextItemOpen(open_action != 0);\r\n    IMGUI_DEMO_MARKER(\"Tables/Columns widths\");\r\n    if (ImGui::TreeNode(\"Columns widths\"))\r\n    {\r\n        HelpMarker(\"Using TableSetupColumn() to setup default width.\");\r\n\r\n        static ImGuiTableFlags flags1 = ImGuiTableFlags_Borders | ImGuiTableFlags_NoBordersInBodyUntilResize;\r\n        PushStyleCompact();\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_Resizable\", &flags1, ImGuiTableFlags_Resizable);\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_NoBordersInBodyUntilResize\", &flags1, ImGuiTableFlags_NoBordersInBodyUntilResize);\r\n        PopStyleCompact();\r\n        if (ImGui::BeginTable(\"table1\", 3, flags1))\r\n        {\r\n            // We could also set ImGuiTableFlags_SizingFixedFit on the table and all columns will default to ImGuiTableColumnFlags_WidthFixed.\r\n            ImGui::TableSetupColumn(\"one\", ImGuiTableColumnFlags_WidthFixed, 100.0f); // Default to 100.0f\r\n            ImGui::TableSetupColumn(\"two\", ImGuiTableColumnFlags_WidthFixed, 200.0f); // Default to 200.0f\r\n            ImGui::TableSetupColumn(\"three\", ImGuiTableColumnFlags_WidthFixed);       // Default to auto\r\n            ImGui::TableHeadersRow();\r\n            for (int row = 0; row < 4; row++)\r\n            {\r\n                ImGui::TableNextRow();\r\n                for (int column = 0; column < 3; column++)\r\n                {\r\n                    ImGui::TableSetColumnIndex(column);\r\n                    if (row == 0)\r\n                        ImGui::Text(\"(w: %5.1f)\", ImGui::GetContentRegionAvail().x);\r\n                    else\r\n                        ImGui::Text(\"Hello %d,%d\", column, row);\r\n                }\r\n            }\r\n            ImGui::EndTable();\r\n        }\r\n\r\n        HelpMarker(\"Using TableSetupColumn() to setup explicit width.\\n\\nUnless _NoKeepColumnsVisible is set, fixed columns with set width may still be shrunk down if there's not enough space in the host.\");\r\n\r\n        static ImGuiTableFlags flags2 = ImGuiTableFlags_None;\r\n        PushStyleCompact();\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_NoKeepColumnsVisible\", &flags2, ImGuiTableFlags_NoKeepColumnsVisible);\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_BordersInnerV\", &flags2, ImGuiTableFlags_BordersInnerV);\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_BordersOuterV\", &flags2, ImGuiTableFlags_BordersOuterV);\r\n        PopStyleCompact();\r\n        if (ImGui::BeginTable(\"table2\", 4, flags2))\r\n        {\r\n            // We could also set ImGuiTableFlags_SizingFixedFit on the table and all columns will default to ImGuiTableColumnFlags_WidthFixed.\r\n            ImGui::TableSetupColumn(\"\", ImGuiTableColumnFlags_WidthFixed, 100.0f);\r\n            ImGui::TableSetupColumn(\"\", ImGuiTableColumnFlags_WidthFixed, TEXT_BASE_WIDTH * 15.0f);\r\n            ImGui::TableSetupColumn(\"\", ImGuiTableColumnFlags_WidthFixed, TEXT_BASE_WIDTH * 30.0f);\r\n            ImGui::TableSetupColumn(\"\", ImGuiTableColumnFlags_WidthFixed, TEXT_BASE_WIDTH * 15.0f);\r\n            for (int row = 0; row < 5; row++)\r\n            {\r\n                ImGui::TableNextRow();\r\n                for (int column = 0; column < 4; column++)\r\n                {\r\n                    ImGui::TableSetColumnIndex(column);\r\n                    if (row == 0)\r\n                        ImGui::Text(\"(w: %5.1f)\", ImGui::GetContentRegionAvail().x);\r\n                    else\r\n                        ImGui::Text(\"Hello %d,%d\", column, row);\r\n                }\r\n            }\r\n            ImGui::EndTable();\r\n        }\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    if (open_action != -1)\r\n        ImGui::SetNextItemOpen(open_action != 0);\r\n    IMGUI_DEMO_MARKER(\"Tables/Nested tables\");\r\n    if (ImGui::TreeNode(\"Nested tables\"))\r\n    {\r\n        HelpMarker(\"This demonstrate embedding a table into another table cell.\");\r\n\r\n        if (ImGui::BeginTable(\"table_nested1\", 2, ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable))\r\n        {\r\n            ImGui::TableSetupColumn(\"A0\");\r\n            ImGui::TableSetupColumn(\"A1\");\r\n            ImGui::TableHeadersRow();\r\n\r\n            ImGui::TableNextColumn();\r\n            ImGui::Text(\"A0 Row 0\");\r\n            {\r\n                float rows_height = TEXT_BASE_HEIGHT * 2;\r\n                if (ImGui::BeginTable(\"table_nested2\", 2, ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable))\r\n                {\r\n                    ImGui::TableSetupColumn(\"B0\");\r\n                    ImGui::TableSetupColumn(\"B1\");\r\n                    ImGui::TableHeadersRow();\r\n\r\n                    ImGui::TableNextRow(ImGuiTableRowFlags_None, rows_height);\r\n                    ImGui::TableNextColumn();\r\n                    ImGui::Text(\"B0 Row 0\");\r\n                    ImGui::TableNextColumn();\r\n                    ImGui::Text(\"B1 Row 0\");\r\n                    ImGui::TableNextRow(ImGuiTableRowFlags_None, rows_height);\r\n                    ImGui::TableNextColumn();\r\n                    ImGui::Text(\"B0 Row 1\");\r\n                    ImGui::TableNextColumn();\r\n                    ImGui::Text(\"B1 Row 1\");\r\n\r\n                    ImGui::EndTable();\r\n                }\r\n            }\r\n            ImGui::TableNextColumn(); ImGui::Text(\"A1 Row 0\");\r\n            ImGui::TableNextColumn(); ImGui::Text(\"A0 Row 1\");\r\n            ImGui::TableNextColumn(); ImGui::Text(\"A1 Row 1\");\r\n            ImGui::EndTable();\r\n        }\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    if (open_action != -1)\r\n        ImGui::SetNextItemOpen(open_action != 0);\r\n    IMGUI_DEMO_MARKER(\"Tables/Row height\");\r\n    if (ImGui::TreeNode(\"Row height\"))\r\n    {\r\n        HelpMarker(\"You can pass a 'min_row_height' to TableNextRow().\\n\\nRows are padded with 'style.CellPadding.y' on top and bottom, so effectively the minimum row height will always be >= 'style.CellPadding.y * 2.0f'.\\n\\nWe cannot honor a _maximum_ row height as that would requires a unique clipping rectangle per row.\");\r\n        if (ImGui::BeginTable(\"table_row_height\", 1, ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersInnerV))\r\n        {\r\n            for (int row = 0; row < 10; row++)\r\n            {\r\n                float min_row_height = (float)(int)(TEXT_BASE_HEIGHT * 0.30f * row);\r\n                ImGui::TableNextRow(ImGuiTableRowFlags_None, min_row_height);\r\n                ImGui::TableNextColumn();\r\n                ImGui::Text(\"min_row_height = %.2f\", min_row_height);\r\n            }\r\n            ImGui::EndTable();\r\n        }\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    if (open_action != -1)\r\n        ImGui::SetNextItemOpen(open_action != 0);\r\n    IMGUI_DEMO_MARKER(\"Tables/Outer size\");\r\n    if (ImGui::TreeNode(\"Outer size\"))\r\n    {\r\n        // Showcasing use of ImGuiTableFlags_NoHostExtendX and ImGuiTableFlags_NoHostExtendY\r\n        // Important to that note how the two flags have slightly different behaviors!\r\n        ImGui::Text(\"Using NoHostExtendX and NoHostExtendY:\");\r\n        PushStyleCompact();\r\n        static ImGuiTableFlags flags = ImGuiTableFlags_Borders | ImGuiTableFlags_Resizable | ImGuiTableFlags_ContextMenuInBody | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_NoHostExtendX;\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_NoHostExtendX\", &flags, ImGuiTableFlags_NoHostExtendX);\r\n        ImGui::SameLine(); HelpMarker(\"Make outer width auto-fit to columns, overriding outer_size.x value.\\n\\nOnly available when ScrollX/ScrollY are disabled and Stretch columns are not used.\");\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_NoHostExtendY\", &flags, ImGuiTableFlags_NoHostExtendY);\r\n        ImGui::SameLine(); HelpMarker(\"Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit).\\n\\nOnly available when ScrollX/ScrollY are disabled. Data below the limit will be clipped and not visible.\");\r\n        PopStyleCompact();\r\n\r\n        ImVec2 outer_size = ImVec2(0.0f, TEXT_BASE_HEIGHT * 5.5f);\r\n        if (ImGui::BeginTable(\"table1\", 3, flags, outer_size))\r\n        {\r\n            for (int row = 0; row < 10; row++)\r\n            {\r\n                ImGui::TableNextRow();\r\n                for (int column = 0; column < 3; column++)\r\n                {\r\n                    ImGui::TableNextColumn();\r\n                    ImGui::Text(\"Cell %d,%d\", column, row);\r\n                }\r\n            }\r\n            ImGui::EndTable();\r\n        }\r\n        ImGui::SameLine();\r\n        ImGui::Text(\"Hello!\");\r\n\r\n        ImGui::Spacing();\r\n\r\n        ImGui::Text(\"Using explicit size:\");\r\n        if (ImGui::BeginTable(\"table2\", 3, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg, ImVec2(TEXT_BASE_WIDTH * 30, 0.0f)))\r\n        {\r\n            for (int row = 0; row < 5; row++)\r\n            {\r\n                ImGui::TableNextRow();\r\n                for (int column = 0; column < 3; column++)\r\n                {\r\n                    ImGui::TableNextColumn();\r\n                    ImGui::Text(\"Cell %d,%d\", column, row);\r\n                }\r\n            }\r\n            ImGui::EndTable();\r\n        }\r\n        ImGui::SameLine();\r\n        if (ImGui::BeginTable(\"table3\", 3, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg, ImVec2(TEXT_BASE_WIDTH * 30, 0.0f)))\r\n        {\r\n            for (int row = 0; row < 3; row++)\r\n            {\r\n                ImGui::TableNextRow(0, TEXT_BASE_HEIGHT * 1.5f);\r\n                for (int column = 0; column < 3; column++)\r\n                {\r\n                    ImGui::TableNextColumn();\r\n                    ImGui::Text(\"Cell %d,%d\", column, row);\r\n                }\r\n            }\r\n            ImGui::EndTable();\r\n        }\r\n\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    if (open_action != -1)\r\n        ImGui::SetNextItemOpen(open_action != 0);\r\n    IMGUI_DEMO_MARKER(\"Tables/Background color\");\r\n    if (ImGui::TreeNode(\"Background color\"))\r\n    {\r\n        static ImGuiTableFlags flags = ImGuiTableFlags_RowBg;\r\n        static int row_bg_type = 1;\r\n        static int row_bg_target = 1;\r\n        static int cell_bg_type = 1;\r\n\r\n        PushStyleCompact();\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_Borders\", &flags, ImGuiTableFlags_Borders);\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_RowBg\", &flags, ImGuiTableFlags_RowBg);\r\n        ImGui::SameLine(); HelpMarker(\"ImGuiTableFlags_RowBg automatically sets RowBg0 to alternative colors pulled from the Style.\");\r\n        ImGui::Combo(\"row bg type\", (int*)&row_bg_type, \"None\\0Red\\0Gradient\\0\");\r\n        ImGui::Combo(\"row bg target\", (int*)&row_bg_target, \"RowBg0\\0RowBg1\\0\"); ImGui::SameLine(); HelpMarker(\"Target RowBg0 to override the alternating odd/even colors,\\nTarget RowBg1 to blend with them.\");\r\n        ImGui::Combo(\"cell bg type\", (int*)&cell_bg_type, \"None\\0Blue\\0\"); ImGui::SameLine(); HelpMarker(\"We are colorizing cells to B1->C2 here.\");\r\n        IM_ASSERT(row_bg_type >= 0 && row_bg_type <= 2);\r\n        IM_ASSERT(row_bg_target >= 0 && row_bg_target <= 1);\r\n        IM_ASSERT(cell_bg_type >= 0 && cell_bg_type <= 1);\r\n        PopStyleCompact();\r\n\r\n        if (ImGui::BeginTable(\"table1\", 5, flags))\r\n        {\r\n            for (int row = 0; row < 6; row++)\r\n            {\r\n                ImGui::TableNextRow();\r\n\r\n                // Demonstrate setting a row background color with 'ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBgX, ...)'\r\n                // We use a transparent color so we can see the one behind in case our target is RowBg1 and RowBg0 was already targeted by the ImGuiTableFlags_RowBg flag.\r\n                if (row_bg_type != 0)\r\n                {\r\n                    ImU32 row_bg_color = ImGui::GetColorU32(row_bg_type == 1 ? ImVec4(0.7f, 0.3f, 0.3f, 0.65f) : ImVec4(0.2f + row * 0.1f, 0.2f, 0.2f, 0.65f)); // Flat or Gradient?\r\n                    ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBg0 + row_bg_target, row_bg_color);\r\n                }\r\n\r\n                // Fill cells\r\n                for (int column = 0; column < 5; column++)\r\n                {\r\n                    ImGui::TableSetColumnIndex(column);\r\n                    ImGui::Text(\"%c%c\", 'A' + row, '0' + column);\r\n\r\n                    // Change background of Cells B1->C2\r\n                    // Demonstrate setting a cell background color with 'ImGui::TableSetBgColor(ImGuiTableBgTarget_CellBg, ...)'\r\n                    // (the CellBg color will be blended over the RowBg and ColumnBg colors)\r\n                    // We can also pass a column number as a third parameter to TableSetBgColor() and do this outside the column loop.\r\n                    if (row >= 1 && row <= 2 && column >= 1 && column <= 2 && cell_bg_type == 1)\r\n                    {\r\n                        ImU32 cell_bg_color = ImGui::GetColorU32(ImVec4(0.3f, 0.3f, 0.7f, 0.65f));\r\n                        ImGui::TableSetBgColor(ImGuiTableBgTarget_CellBg, cell_bg_color);\r\n                    }\r\n                }\r\n            }\r\n            ImGui::EndTable();\r\n        }\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    if (open_action != -1)\r\n        ImGui::SetNextItemOpen(open_action != 0);\r\n    IMGUI_DEMO_MARKER(\"Tables/Tree view\");\r\n    if (ImGui::TreeNode(\"Tree view\"))\r\n    {\r\n        static ImGuiTableFlags flags = ImGuiTableFlags_BordersV | ImGuiTableFlags_BordersOuterH | ImGuiTableFlags_Resizable | ImGuiTableFlags_RowBg | ImGuiTableFlags_NoBordersInBody;\r\n\r\n        if (ImGui::BeginTable(\"3ways\", 3, flags))\r\n        {\r\n            // The first column will use the default _WidthStretch when ScrollX is Off and _WidthFixed when ScrollX is On\r\n            ImGui::TableSetupColumn(\"Name\", ImGuiTableColumnFlags_NoHide);\r\n            ImGui::TableSetupColumn(\"Size\", ImGuiTableColumnFlags_WidthFixed, TEXT_BASE_WIDTH * 12.0f);\r\n            ImGui::TableSetupColumn(\"Type\", ImGuiTableColumnFlags_WidthFixed, TEXT_BASE_WIDTH * 18.0f);\r\n            ImGui::TableHeadersRow();\r\n\r\n            // Simple storage to output a dummy file-system.\r\n            struct MyTreeNode\r\n            {\r\n                const char*     Name;\r\n                const char*     Type;\r\n                int             Size;\r\n                int             ChildIdx;\r\n                int             ChildCount;\r\n                static void DisplayNode(const MyTreeNode* node, const MyTreeNode* all_nodes)\r\n                {\r\n                    ImGui::TableNextRow();\r\n                    ImGui::TableNextColumn();\r\n                    const bool is_folder = (node->ChildCount > 0);\r\n                    if (is_folder)\r\n                    {\r\n                        bool open = ImGui::TreeNodeEx(node->Name, ImGuiTreeNodeFlags_SpanFullWidth);\r\n                        ImGui::TableNextColumn();\r\n                        ImGui::TextDisabled(\"--\");\r\n                        ImGui::TableNextColumn();\r\n                        ImGui::TextUnformatted(node->Type);\r\n                        if (open)\r\n                        {\r\n                            for (int child_n = 0; child_n < node->ChildCount; child_n++)\r\n                                DisplayNode(&all_nodes[node->ChildIdx + child_n], all_nodes);\r\n                            ImGui::TreePop();\r\n                        }\r\n                    }\r\n                    else\r\n                    {\r\n                        ImGui::TreeNodeEx(node->Name, ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_Bullet | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_SpanFullWidth);\r\n                        ImGui::TableNextColumn();\r\n                        ImGui::Text(\"%d\", node->Size);\r\n                        ImGui::TableNextColumn();\r\n                        ImGui::TextUnformatted(node->Type);\r\n                    }\r\n                }\r\n            };\r\n            static const MyTreeNode nodes[] =\r\n            {\r\n                { \"Root\",                         \"Folder\",       -1,       1, 3    }, // 0\r\n                { \"Music\",                        \"Folder\",       -1,       4, 2    }, // 1\r\n                { \"Textures\",                     \"Folder\",       -1,       6, 3    }, // 2\r\n                { \"desktop.ini\",                  \"System file\",  1024,    -1,-1    }, // 3\r\n                { \"File1_a.wav\",                  \"Audio file\",   123000,  -1,-1    }, // 4\r\n                { \"File1_b.wav\",                  \"Audio file\",   456000,  -1,-1    }, // 5\r\n                { \"Image001.png\",                 \"Image file\",   203128,  -1,-1    }, // 6\r\n                { \"Copy of Image001.png\",         \"Image file\",   203256,  -1,-1    }, // 7\r\n                { \"Copy of Image001 (Final2).png\",\"Image file\",   203512,  -1,-1    }, // 8\r\n            };\r\n\r\n            MyTreeNode::DisplayNode(&nodes[0], nodes);\r\n\r\n            ImGui::EndTable();\r\n        }\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    if (open_action != -1)\r\n        ImGui::SetNextItemOpen(open_action != 0);\r\n    IMGUI_DEMO_MARKER(\"Tables/Item width\");\r\n    if (ImGui::TreeNode(\"Item width\"))\r\n    {\r\n        HelpMarker(\r\n            \"Showcase using PushItemWidth() and how it is preserved on a per-column basis.\\n\\n\"\r\n            \"Note that on auto-resizing non-resizable fixed columns, querying the content width for e.g. right-alignment doesn't make sense.\");\r\n        if (ImGui::BeginTable(\"table_item_width\", 3, ImGuiTableFlags_Borders))\r\n        {\r\n            ImGui::TableSetupColumn(\"small\");\r\n            ImGui::TableSetupColumn(\"half\");\r\n            ImGui::TableSetupColumn(\"right-align\");\r\n            ImGui::TableHeadersRow();\r\n\r\n            for (int row = 0; row < 3; row++)\r\n            {\r\n                ImGui::TableNextRow();\r\n                if (row == 0)\r\n                {\r\n                    // Setup ItemWidth once (instead of setting up every time, which is also possible but less efficient)\r\n                    ImGui::TableSetColumnIndex(0);\r\n                    ImGui::PushItemWidth(TEXT_BASE_WIDTH * 3.0f); // Small\r\n                    ImGui::TableSetColumnIndex(1);\r\n                    ImGui::PushItemWidth(-ImGui::GetContentRegionAvail().x * 0.5f);\r\n                    ImGui::TableSetColumnIndex(2);\r\n                    ImGui::PushItemWidth(-FLT_MIN); // Right-aligned\r\n                }\r\n\r\n                // Draw our contents\r\n                static float dummy_f = 0.0f;\r\n                ImGui::PushID(row);\r\n                ImGui::TableSetColumnIndex(0);\r\n                ImGui::SliderFloat(\"float0\", &dummy_f, 0.0f, 1.0f);\r\n                ImGui::TableSetColumnIndex(1);\r\n                ImGui::SliderFloat(\"float1\", &dummy_f, 0.0f, 1.0f);\r\n                ImGui::TableSetColumnIndex(2);\r\n                ImGui::SliderFloat(\"float2\", &dummy_f, 0.0f, 1.0f);\r\n                ImGui::PopID();\r\n            }\r\n            ImGui::EndTable();\r\n        }\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    // Demonstrate using TableHeader() calls instead of TableHeadersRow()\r\n    if (open_action != -1)\r\n        ImGui::SetNextItemOpen(open_action != 0);\r\n    IMGUI_DEMO_MARKER(\"Tables/Custom headers\");\r\n    if (ImGui::TreeNode(\"Custom headers\"))\r\n    {\r\n        const int COLUMNS_COUNT = 3;\r\n        if (ImGui::BeginTable(\"table_custom_headers\", COLUMNS_COUNT, ImGuiTableFlags_Borders | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable))\r\n        {\r\n            ImGui::TableSetupColumn(\"Apricot\");\r\n            ImGui::TableSetupColumn(\"Banana\");\r\n            ImGui::TableSetupColumn(\"Cherry\");\r\n\r\n            // Dummy entire-column selection storage\r\n            // FIXME: It would be nice to actually demonstrate full-featured selection using those checkbox.\r\n            static bool column_selected[3] = {};\r\n\r\n            // Instead of calling TableHeadersRow() we'll submit custom headers ourselves\r\n            ImGui::TableNextRow(ImGuiTableRowFlags_Headers);\r\n            for (int column = 0; column < COLUMNS_COUNT; column++)\r\n            {\r\n                ImGui::TableSetColumnIndex(column);\r\n                const char* column_name = ImGui::TableGetColumnName(column); // Retrieve name passed to TableSetupColumn()\r\n                ImGui::PushID(column);\r\n                ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));\r\n                ImGui::Checkbox(\"##checkall\", &column_selected[column]);\r\n                ImGui::PopStyleVar();\r\n                ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x);\r\n                ImGui::TableHeader(column_name);\r\n                ImGui::PopID();\r\n            }\r\n\r\n            for (int row = 0; row < 5; row++)\r\n            {\r\n                ImGui::TableNextRow();\r\n                for (int column = 0; column < 3; column++)\r\n                {\r\n                    char buf[32];\r\n                    sprintf(buf, \"Cell %d,%d\", column, row);\r\n                    ImGui::TableSetColumnIndex(column);\r\n                    ImGui::Selectable(buf, column_selected[column]);\r\n                }\r\n            }\r\n            ImGui::EndTable();\r\n        }\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    // Demonstrate creating custom context menus inside columns, while playing it nice with context menus provided by TableHeadersRow()/TableHeader()\r\n    if (open_action != -1)\r\n        ImGui::SetNextItemOpen(open_action != 0);\r\n    IMGUI_DEMO_MARKER(\"Tables/Context menus\");\r\n    if (ImGui::TreeNode(\"Context menus\"))\r\n    {\r\n        HelpMarker(\"By default, right-clicking over a TableHeadersRow()/TableHeader() line will open the default context-menu.\\nUsing ImGuiTableFlags_ContextMenuInBody we also allow right-clicking over columns body.\");\r\n        static ImGuiTableFlags flags1 = ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Borders | ImGuiTableFlags_ContextMenuInBody;\r\n\r\n        PushStyleCompact();\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_ContextMenuInBody\", &flags1, ImGuiTableFlags_ContextMenuInBody);\r\n        PopStyleCompact();\r\n\r\n        // Context Menus: first example\r\n        // [1.1] Right-click on the TableHeadersRow() line to open the default table context menu.\r\n        // [1.2] Right-click in columns also open the default table context menu (if ImGuiTableFlags_ContextMenuInBody is set)\r\n        const int COLUMNS_COUNT = 3;\r\n        if (ImGui::BeginTable(\"table_context_menu\", COLUMNS_COUNT, flags1))\r\n        {\r\n            ImGui::TableSetupColumn(\"One\");\r\n            ImGui::TableSetupColumn(\"Two\");\r\n            ImGui::TableSetupColumn(\"Three\");\r\n\r\n            // [1.1]] Right-click on the TableHeadersRow() line to open the default table context menu.\r\n            ImGui::TableHeadersRow();\r\n\r\n            // Submit dummy contents\r\n            for (int row = 0; row < 4; row++)\r\n            {\r\n                ImGui::TableNextRow();\r\n                for (int column = 0; column < COLUMNS_COUNT; column++)\r\n                {\r\n                    ImGui::TableSetColumnIndex(column);\r\n                    ImGui::Text(\"Cell %d,%d\", column, row);\r\n                }\r\n            }\r\n            ImGui::EndTable();\r\n        }\r\n\r\n        // Context Menus: second example\r\n        // [2.1] Right-click on the TableHeadersRow() line to open the default table context menu.\r\n        // [2.2] Right-click on the \"..\" to open a custom popup\r\n        // [2.3] Right-click in columns to open another custom popup\r\n        HelpMarker(\"Demonstrate mixing table context menu (over header), item context button (over button) and custom per-colum context menu (over column body).\");\r\n        ImGuiTableFlags flags2 = ImGuiTableFlags_Resizable | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Borders;\r\n        if (ImGui::BeginTable(\"table_context_menu_2\", COLUMNS_COUNT, flags2))\r\n        {\r\n            ImGui::TableSetupColumn(\"One\");\r\n            ImGui::TableSetupColumn(\"Two\");\r\n            ImGui::TableSetupColumn(\"Three\");\r\n\r\n            // [2.1] Right-click on the TableHeadersRow() line to open the default table context menu.\r\n            ImGui::TableHeadersRow();\r\n            for (int row = 0; row < 4; row++)\r\n            {\r\n                ImGui::TableNextRow();\r\n                for (int column = 0; column < COLUMNS_COUNT; column++)\r\n                {\r\n                    // Submit dummy contents\r\n                    ImGui::TableSetColumnIndex(column);\r\n                    ImGui::Text(\"Cell %d,%d\", column, row);\r\n                    ImGui::SameLine();\r\n\r\n                    // [2.2] Right-click on the \"..\" to open a custom popup\r\n                    ImGui::PushID(row * COLUMNS_COUNT + column);\r\n                    ImGui::SmallButton(\"..\");\r\n                    if (ImGui::BeginPopupContextItem())\r\n                    {\r\n                        ImGui::Text(\"This is the popup for Button(\\\"..\\\") in Cell %d,%d\", column, row);\r\n                        if (ImGui::Button(\"Close\"))\r\n                            ImGui::CloseCurrentPopup();\r\n                        ImGui::EndPopup();\r\n                    }\r\n                    ImGui::PopID();\r\n                }\r\n            }\r\n\r\n            // [2.3] Right-click anywhere in columns to open another custom popup\r\n            // (instead of testing for !IsAnyItemHovered() we could also call OpenPopup() with ImGuiPopupFlags_NoOpenOverExistingPopup\r\n            // to manage popup priority as the popups triggers, here \"are we hovering a column\" are overlapping)\r\n            int hovered_column = -1;\r\n            for (int column = 0; column < COLUMNS_COUNT + 1; column++)\r\n            {\r\n                ImGui::PushID(column);\r\n                if (ImGui::TableGetColumnFlags(column) & ImGuiTableColumnFlags_IsHovered)\r\n                    hovered_column = column;\r\n                if (hovered_column == column && !ImGui::IsAnyItemHovered() && ImGui::IsMouseReleased(1))\r\n                    ImGui::OpenPopup(\"MyPopup\");\r\n                if (ImGui::BeginPopup(\"MyPopup\"))\r\n                {\r\n                    if (column == COLUMNS_COUNT)\r\n                        ImGui::Text(\"This is a custom popup for unused space after the last column.\");\r\n                    else\r\n                        ImGui::Text(\"This is a custom popup for Column %d\", column);\r\n                    if (ImGui::Button(\"Close\"))\r\n                        ImGui::CloseCurrentPopup();\r\n                    ImGui::EndPopup();\r\n                }\r\n                ImGui::PopID();\r\n            }\r\n\r\n            ImGui::EndTable();\r\n            ImGui::Text(\"Hovered column: %d\", hovered_column);\r\n        }\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    // Demonstrate creating multiple tables with the same ID\r\n    if (open_action != -1)\r\n        ImGui::SetNextItemOpen(open_action != 0);\r\n    IMGUI_DEMO_MARKER(\"Tables/Synced instances\");\r\n    if (ImGui::TreeNode(\"Synced instances\"))\r\n    {\r\n        HelpMarker(\"Multiple tables with the same identifier will share their settings, width, visibility, order etc.\");\r\n        for (int n = 0; n < 3; n++)\r\n        {\r\n            char buf[32];\r\n            sprintf(buf, \"Synced Table %d\", n);\r\n            bool open = ImGui::CollapsingHeader(buf, ImGuiTreeNodeFlags_DefaultOpen);\r\n            if (open && ImGui::BeginTable(\"Table\", 3, ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Borders | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_NoSavedSettings))\r\n            {\r\n                ImGui::TableSetupColumn(\"One\");\r\n                ImGui::TableSetupColumn(\"Two\");\r\n                ImGui::TableSetupColumn(\"Three\");\r\n                ImGui::TableHeadersRow();\r\n                for (int cell = 0; cell < 9; cell++)\r\n                {\r\n                    ImGui::TableNextColumn();\r\n                    ImGui::Text(\"this cell %d\", cell);\r\n                }\r\n                ImGui::EndTable();\r\n            }\r\n        }\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    // Demonstrate using Sorting facilities\r\n    // This is a simplified version of the \"Advanced\" example, where we mostly focus on the code necessary to handle sorting.\r\n    // Note that the \"Advanced\" example also showcase manually triggering a sort (e.g. if item quantities have been modified)\r\n    static const char* template_items_names[] =\r\n    {\r\n        \"Banana\", \"Apple\", \"Cherry\", \"Watermelon\", \"Grapefruit\", \"Strawberry\", \"Mango\",\r\n        \"Kiwi\", \"Orange\", \"Pineapple\", \"Blueberry\", \"Plum\", \"Coconut\", \"Pear\", \"Apricot\"\r\n    };\r\n    if (open_action != -1)\r\n        ImGui::SetNextItemOpen(open_action != 0);\r\n    IMGUI_DEMO_MARKER(\"Tables/Sorting\");\r\n    if (ImGui::TreeNode(\"Sorting\"))\r\n    {\r\n        // Create item list\r\n        static ImVector<MyItem> items;\r\n        if (items.Size == 0)\r\n        {\r\n            items.resize(50, MyItem());\r\n            for (int n = 0; n < items.Size; n++)\r\n            {\r\n                const int template_n = n % IM_ARRAYSIZE(template_items_names);\r\n                MyItem& item = items[n];\r\n                item.ID = n;\r\n                item.Name = template_items_names[template_n];\r\n                item.Quantity = (n * n - n) % 20; // Assign default quantities\r\n            }\r\n        }\r\n\r\n        // Options\r\n        static ImGuiTableFlags flags =\r\n            ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Sortable | ImGuiTableFlags_SortMulti\r\n            | ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV | ImGuiTableFlags_NoBordersInBody\r\n            | ImGuiTableFlags_ScrollY;\r\n        PushStyleCompact();\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_SortMulti\", &flags, ImGuiTableFlags_SortMulti);\r\n        ImGui::SameLine(); HelpMarker(\"When sorting is enabled: hold shift when clicking headers to sort on multiple column. TableGetSortSpecs() may return specs where (SpecsCount > 1).\");\r\n        ImGui::CheckboxFlags(\"ImGuiTableFlags_SortTristate\", &flags, ImGuiTableFlags_SortTristate);\r\n        ImGui::SameLine(); HelpMarker(\"When sorting is enabled: allow no sorting, disable default sorting. TableGetSortSpecs() may return specs where (SpecsCount == 0).\");\r\n        PopStyleCompact();\r\n\r\n        if (ImGui::BeginTable(\"table_sorting\", 4, flags, ImVec2(0.0f, TEXT_BASE_HEIGHT * 15), 0.0f))\r\n        {\r\n            // Declare columns\r\n            // We use the \"user_id\" parameter of TableSetupColumn() to specify a user id that will be stored in the sort specifications.\r\n            // This is so our sort function can identify a column given our own identifier. We could also identify them based on their index!\r\n            // Demonstrate using a mixture of flags among available sort-related flags:\r\n            // - ImGuiTableColumnFlags_DefaultSort\r\n            // - ImGuiTableColumnFlags_NoSort / ImGuiTableColumnFlags_NoSortAscending / ImGuiTableColumnFlags_NoSortDescending\r\n            // - ImGuiTableColumnFlags_PreferSortAscending / ImGuiTableColumnFlags_PreferSortDescending\r\n            ImGui::TableSetupColumn(\"ID\",       ImGuiTableColumnFlags_DefaultSort          | ImGuiTableColumnFlags_WidthFixed,   0.0f, MyItemColumnID_ID);\r\n            ImGui::TableSetupColumn(\"Name\",                                                  ImGuiTableColumnFlags_WidthFixed,   0.0f, MyItemColumnID_Name);\r\n            ImGui::TableSetupColumn(\"Action\",   ImGuiTableColumnFlags_NoSort               | ImGuiTableColumnFlags_WidthFixed,   0.0f, MyItemColumnID_Action);\r\n            ImGui::TableSetupColumn(\"Quantity\", ImGuiTableColumnFlags_PreferSortDescending | ImGuiTableColumnFlags_WidthStretch, 0.0f, MyItemColumnID_Quantity);\r\n            ImGui::TableSetupScrollFreeze(0, 1); // Make row always visible\r\n            ImGui::TableHeadersRow();\r\n\r\n            // Sort our data if sort specs have been changed!\r\n            if (ImGuiTableSortSpecs* sorts_specs = ImGui::TableGetSortSpecs())\r\n                if (sorts_specs->SpecsDirty)\r\n                {\r\n                    MyItem::s_current_sort_specs = sorts_specs; // Store in variable accessible by the sort function.\r\n                    if (items.Size > 1)\r\n                        qsort(&items[0], (size_t)items.Size, sizeof(items[0]), MyItem::CompareWithSortSpecs);\r\n                    MyItem::s_current_sort_specs = NULL;\r\n                    sorts_specs->SpecsDirty = false;\r\n                }\r\n\r\n            // Demonstrate using clipper for large vertical lists\r\n            ImGuiListClipper clipper;\r\n            clipper.Begin(items.Size);\r\n            while (clipper.Step())\r\n                for (int row_n = clipper.DisplayStart; row_n < clipper.DisplayEnd; row_n++)\r\n                {\r\n                    // Display a data item\r\n                    MyItem* item = &items[row_n];\r\n                    ImGui::PushID(item->ID);\r\n                    ImGui::TableNextRow();\r\n                    ImGui::TableNextColumn();\r\n                    ImGui::Text(\"%04d\", item->ID);\r\n                    ImGui::TableNextColumn();\r\n                    ImGui::TextUnformatted(item->Name);\r\n                    ImGui::TableNextColumn();\r\n                    ImGui::SmallButton(\"None\");\r\n                    ImGui::TableNextColumn();\r\n                    ImGui::Text(\"%d\", item->Quantity);\r\n                    ImGui::PopID();\r\n                }\r\n            ImGui::EndTable();\r\n        }\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    // In this example we'll expose most table flags and settings.\r\n    // For specific flags and settings refer to the corresponding section for more detailed explanation.\r\n    // This section is mostly useful to experiment with combining certain flags or settings with each others.\r\n    //ImGui::SetNextItemOpen(true, ImGuiCond_Once); // [DEBUG]\r\n    if (open_action != -1)\r\n        ImGui::SetNextItemOpen(open_action != 0);\r\n    IMGUI_DEMO_MARKER(\"Tables/Advanced\");\r\n    if (ImGui::TreeNode(\"Advanced\"))\r\n    {\r\n        static ImGuiTableFlags flags =\r\n            ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable\r\n            | ImGuiTableFlags_Sortable | ImGuiTableFlags_SortMulti\r\n            | ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders | ImGuiTableFlags_NoBordersInBody\r\n            | ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY\r\n            | ImGuiTableFlags_SizingFixedFit;\r\n\r\n        enum ContentsType { CT_Text, CT_Button, CT_SmallButton, CT_FillButton, CT_Selectable, CT_SelectableSpanRow };\r\n        static int contents_type = CT_SelectableSpanRow;\r\n        const char* contents_type_names[] = { \"Text\", \"Button\", \"SmallButton\", \"FillButton\", \"Selectable\", \"Selectable (span row)\" };\r\n        static int freeze_cols = 1;\r\n        static int freeze_rows = 1;\r\n        static int items_count = IM_ARRAYSIZE(template_items_names) * 2;\r\n        static ImVec2 outer_size_value = ImVec2(0.0f, TEXT_BASE_HEIGHT * 12);\r\n        static float row_min_height = 0.0f; // Auto\r\n        static float inner_width_with_scroll = 0.0f; // Auto-extend\r\n        static bool outer_size_enabled = true;\r\n        static bool show_headers = true;\r\n        static bool show_wrapped_text = false;\r\n        //static ImGuiTextFilter filter;\r\n        //ImGui::SetNextItemOpen(true, ImGuiCond_Once); // FIXME-TABLE: Enabling this results in initial clipped first pass on table which tend to affects column sizing\r\n        if (ImGui::TreeNode(\"Options\"))\r\n        {\r\n            // Make the UI compact because there are so many fields\r\n            PushStyleCompact();\r\n            ImGui::PushItemWidth(TEXT_BASE_WIDTH * 28.0f);\r\n\r\n            if (ImGui::TreeNodeEx(\"Features:\", ImGuiTreeNodeFlags_DefaultOpen))\r\n            {\r\n                ImGui::CheckboxFlags(\"ImGuiTableFlags_Resizable\", &flags, ImGuiTableFlags_Resizable);\r\n                ImGui::CheckboxFlags(\"ImGuiTableFlags_Reorderable\", &flags, ImGuiTableFlags_Reorderable);\r\n                ImGui::CheckboxFlags(\"ImGuiTableFlags_Hideable\", &flags, ImGuiTableFlags_Hideable);\r\n                ImGui::CheckboxFlags(\"ImGuiTableFlags_Sortable\", &flags, ImGuiTableFlags_Sortable);\r\n                ImGui::CheckboxFlags(\"ImGuiTableFlags_NoSavedSettings\", &flags, ImGuiTableFlags_NoSavedSettings);\r\n                ImGui::CheckboxFlags(\"ImGuiTableFlags_ContextMenuInBody\", &flags, ImGuiTableFlags_ContextMenuInBody);\r\n                ImGui::TreePop();\r\n            }\r\n\r\n            if (ImGui::TreeNodeEx(\"Decorations:\", ImGuiTreeNodeFlags_DefaultOpen))\r\n            {\r\n                ImGui::CheckboxFlags(\"ImGuiTableFlags_RowBg\", &flags, ImGuiTableFlags_RowBg);\r\n                ImGui::CheckboxFlags(\"ImGuiTableFlags_BordersV\", &flags, ImGuiTableFlags_BordersV);\r\n                ImGui::CheckboxFlags(\"ImGuiTableFlags_BordersOuterV\", &flags, ImGuiTableFlags_BordersOuterV);\r\n                ImGui::CheckboxFlags(\"ImGuiTableFlags_BordersInnerV\", &flags, ImGuiTableFlags_BordersInnerV);\r\n                ImGui::CheckboxFlags(\"ImGuiTableFlags_BordersH\", &flags, ImGuiTableFlags_BordersH);\r\n                ImGui::CheckboxFlags(\"ImGuiTableFlags_BordersOuterH\", &flags, ImGuiTableFlags_BordersOuterH);\r\n                ImGui::CheckboxFlags(\"ImGuiTableFlags_BordersInnerH\", &flags, ImGuiTableFlags_BordersInnerH);\r\n                ImGui::CheckboxFlags(\"ImGuiTableFlags_NoBordersInBody\", &flags, ImGuiTableFlags_NoBordersInBody); ImGui::SameLine(); HelpMarker(\"Disable vertical borders in columns Body (borders will always appears in Headers\");\r\n                ImGui::CheckboxFlags(\"ImGuiTableFlags_NoBordersInBodyUntilResize\", &flags, ImGuiTableFlags_NoBordersInBodyUntilResize); ImGui::SameLine(); HelpMarker(\"Disable vertical borders in columns Body until hovered for resize (borders will always appears in Headers)\");\r\n                ImGui::TreePop();\r\n            }\r\n\r\n            if (ImGui::TreeNodeEx(\"Sizing:\", ImGuiTreeNodeFlags_DefaultOpen))\r\n            {\r\n                EditTableSizingFlags(&flags);\r\n                ImGui::SameLine(); HelpMarker(\"In the Advanced demo we override the policy of each column so those table-wide settings have less effect that typical.\");\r\n                ImGui::CheckboxFlags(\"ImGuiTableFlags_NoHostExtendX\", &flags, ImGuiTableFlags_NoHostExtendX);\r\n                ImGui::SameLine(); HelpMarker(\"Make outer width auto-fit to columns, overriding outer_size.x value.\\n\\nOnly available when ScrollX/ScrollY are disabled and Stretch columns are not used.\");\r\n                ImGui::CheckboxFlags(\"ImGuiTableFlags_NoHostExtendY\", &flags, ImGuiTableFlags_NoHostExtendY);\r\n                ImGui::SameLine(); HelpMarker(\"Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit).\\n\\nOnly available when ScrollX/ScrollY are disabled. Data below the limit will be clipped and not visible.\");\r\n                ImGui::CheckboxFlags(\"ImGuiTableFlags_NoKeepColumnsVisible\", &flags, ImGuiTableFlags_NoKeepColumnsVisible);\r\n                ImGui::SameLine(); HelpMarker(\"Only available if ScrollX is disabled.\");\r\n                ImGui::CheckboxFlags(\"ImGuiTableFlags_PreciseWidths\", &flags, ImGuiTableFlags_PreciseWidths);\r\n                ImGui::SameLine(); HelpMarker(\"Disable distributing remainder width to stretched columns (width allocation on a 100-wide table with 3 columns: Without this flag: 33,33,34. With this flag: 33,33,33). With larger number of columns, resizing will appear to be less smooth.\");\r\n                ImGui::CheckboxFlags(\"ImGuiTableFlags_NoClip\", &flags, ImGuiTableFlags_NoClip);\r\n                ImGui::SameLine(); HelpMarker(\"Disable clipping rectangle for every individual columns (reduce draw command count, items will be able to overflow into other columns). Generally incompatible with ScrollFreeze options.\");\r\n                ImGui::TreePop();\r\n            }\r\n\r\n            if (ImGui::TreeNodeEx(\"Padding:\", ImGuiTreeNodeFlags_DefaultOpen))\r\n            {\r\n                ImGui::CheckboxFlags(\"ImGuiTableFlags_PadOuterX\", &flags, ImGuiTableFlags_PadOuterX);\r\n                ImGui::CheckboxFlags(\"ImGuiTableFlags_NoPadOuterX\", &flags, ImGuiTableFlags_NoPadOuterX);\r\n                ImGui::CheckboxFlags(\"ImGuiTableFlags_NoPadInnerX\", &flags, ImGuiTableFlags_NoPadInnerX);\r\n                ImGui::TreePop();\r\n            }\r\n\r\n            if (ImGui::TreeNodeEx(\"Scrolling:\", ImGuiTreeNodeFlags_DefaultOpen))\r\n            {\r\n                ImGui::CheckboxFlags(\"ImGuiTableFlags_ScrollX\", &flags, ImGuiTableFlags_ScrollX);\r\n                ImGui::SameLine();\r\n                ImGui::SetNextItemWidth(ImGui::GetFrameHeight());\r\n                ImGui::DragInt(\"freeze_cols\", &freeze_cols, 0.2f, 0, 9, NULL, ImGuiSliderFlags_NoInput);\r\n                ImGui::CheckboxFlags(\"ImGuiTableFlags_ScrollY\", &flags, ImGuiTableFlags_ScrollY);\r\n                ImGui::SameLine();\r\n                ImGui::SetNextItemWidth(ImGui::GetFrameHeight());\r\n                ImGui::DragInt(\"freeze_rows\", &freeze_rows, 0.2f, 0, 9, NULL, ImGuiSliderFlags_NoInput);\r\n                ImGui::TreePop();\r\n            }\r\n\r\n            if (ImGui::TreeNodeEx(\"Sorting:\", ImGuiTreeNodeFlags_DefaultOpen))\r\n            {\r\n                ImGui::CheckboxFlags(\"ImGuiTableFlags_SortMulti\", &flags, ImGuiTableFlags_SortMulti);\r\n                ImGui::SameLine(); HelpMarker(\"When sorting is enabled: hold shift when clicking headers to sort on multiple column. TableGetSortSpecs() may return specs where (SpecsCount > 1).\");\r\n                ImGui::CheckboxFlags(\"ImGuiTableFlags_SortTristate\", &flags, ImGuiTableFlags_SortTristate);\r\n                ImGui::SameLine(); HelpMarker(\"When sorting is enabled: allow no sorting, disable default sorting. TableGetSortSpecs() may return specs where (SpecsCount == 0).\");\r\n                ImGui::TreePop();\r\n            }\r\n\r\n            if (ImGui::TreeNodeEx(\"Other:\", ImGuiTreeNodeFlags_DefaultOpen))\r\n            {\r\n                ImGui::Checkbox(\"show_headers\", &show_headers);\r\n                ImGui::Checkbox(\"show_wrapped_text\", &show_wrapped_text);\r\n\r\n                ImGui::DragFloat2(\"##OuterSize\", &outer_size_value.x);\r\n                ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x);\r\n                ImGui::Checkbox(\"outer_size\", &outer_size_enabled);\r\n                ImGui::SameLine();\r\n                HelpMarker(\"If scrolling is disabled (ScrollX and ScrollY not set):\\n\"\r\n                    \"- The table is output directly in the parent window.\\n\"\r\n                    \"- OuterSize.x < 0.0f will right-align the table.\\n\"\r\n                    \"- OuterSize.x = 0.0f will narrow fit the table unless there are any Stretch column.\\n\"\r\n                    \"- OuterSize.y then becomes the minimum size for the table, which will extend vertically if there are more rows (unless NoHostExtendY is set).\");\r\n\r\n                // From a user point of view we will tend to use 'inner_width' differently depending on whether our table is embedding scrolling.\r\n                // To facilitate toying with this demo we will actually pass 0.0f to the BeginTable() when ScrollX is disabled.\r\n                ImGui::DragFloat(\"inner_width (when ScrollX active)\", &inner_width_with_scroll, 1.0f, 0.0f, FLT_MAX);\r\n\r\n                ImGui::DragFloat(\"row_min_height\", &row_min_height, 1.0f, 0.0f, FLT_MAX);\r\n                ImGui::SameLine(); HelpMarker(\"Specify height of the Selectable item.\");\r\n\r\n                ImGui::DragInt(\"items_count\", &items_count, 0.1f, 0, 9999);\r\n                ImGui::Combo(\"items_type (first column)\", &contents_type, contents_type_names, IM_ARRAYSIZE(contents_type_names));\r\n                //filter.Draw(\"filter\");\r\n                ImGui::TreePop();\r\n            }\r\n\r\n            ImGui::PopItemWidth();\r\n            PopStyleCompact();\r\n            ImGui::Spacing();\r\n            ImGui::TreePop();\r\n        }\r\n\r\n        // Update item list if we changed the number of items\r\n        static ImVector<MyItem> items;\r\n        static ImVector<int> selection;\r\n        static bool items_need_sort = false;\r\n        if (items.Size != items_count)\r\n        {\r\n            items.resize(items_count, MyItem());\r\n            for (int n = 0; n < items_count; n++)\r\n            {\r\n                const int template_n = n % IM_ARRAYSIZE(template_items_names);\r\n                MyItem& item = items[n];\r\n                item.ID = n;\r\n                item.Name = template_items_names[template_n];\r\n                item.Quantity = (template_n == 3) ? 10 : (template_n == 4) ? 20 : 0; // Assign default quantities\r\n            }\r\n        }\r\n\r\n        const ImDrawList* parent_draw_list = ImGui::GetWindowDrawList();\r\n        const int parent_draw_list_draw_cmd_count = parent_draw_list->CmdBuffer.Size;\r\n        ImVec2 table_scroll_cur, table_scroll_max; // For debug display\r\n        const ImDrawList* table_draw_list = NULL;  // \"\r\n\r\n        // Submit table\r\n        const float inner_width_to_use = (flags & ImGuiTableFlags_ScrollX) ? inner_width_with_scroll : 0.0f;\r\n        if (ImGui::BeginTable(\"table_advanced\", 6, flags, outer_size_enabled ? outer_size_value : ImVec2(0, 0), inner_width_to_use))\r\n        {\r\n            // Declare columns\r\n            // We use the \"user_id\" parameter of TableSetupColumn() to specify a user id that will be stored in the sort specifications.\r\n            // This is so our sort function can identify a column given our own identifier. We could also identify them based on their index!\r\n            ImGui::TableSetupColumn(\"ID\",           ImGuiTableColumnFlags_DefaultSort | ImGuiTableColumnFlags_WidthFixed | ImGuiTableColumnFlags_NoHide, 0.0f, MyItemColumnID_ID);\r\n            ImGui::TableSetupColumn(\"Name\",         ImGuiTableColumnFlags_WidthFixed, 0.0f, MyItemColumnID_Name);\r\n            ImGui::TableSetupColumn(\"Action\",       ImGuiTableColumnFlags_NoSort | ImGuiTableColumnFlags_WidthFixed, 0.0f, MyItemColumnID_Action);\r\n            ImGui::TableSetupColumn(\"Quantity\",     ImGuiTableColumnFlags_PreferSortDescending, 0.0f, MyItemColumnID_Quantity);\r\n            ImGui::TableSetupColumn(\"Description\",  (flags & ImGuiTableFlags_NoHostExtendX) ? 0 : ImGuiTableColumnFlags_WidthStretch, 0.0f, MyItemColumnID_Description);\r\n            ImGui::TableSetupColumn(\"Hidden\",       ImGuiTableColumnFlags_DefaultHide | ImGuiTableColumnFlags_NoSort);\r\n            ImGui::TableSetupScrollFreeze(freeze_cols, freeze_rows);\r\n\r\n            // Sort our data if sort specs have been changed!\r\n            ImGuiTableSortSpecs* sorts_specs = ImGui::TableGetSortSpecs();\r\n            if (sorts_specs && sorts_specs->SpecsDirty)\r\n                items_need_sort = true;\r\n            if (sorts_specs && items_need_sort && items.Size > 1)\r\n            {\r\n                MyItem::s_current_sort_specs = sorts_specs; // Store in variable accessible by the sort function.\r\n                qsort(&items[0], (size_t)items.Size, sizeof(items[0]), MyItem::CompareWithSortSpecs);\r\n                MyItem::s_current_sort_specs = NULL;\r\n                sorts_specs->SpecsDirty = false;\r\n            }\r\n            items_need_sort = false;\r\n\r\n            // Take note of whether we are currently sorting based on the Quantity field,\r\n            // we will use this to trigger sorting when we know the data of this column has been modified.\r\n            const bool sorts_specs_using_quantity = (ImGui::TableGetColumnFlags(3) & ImGuiTableColumnFlags_IsSorted) != 0;\r\n\r\n            // Show headers\r\n            if (show_headers)\r\n                ImGui::TableHeadersRow();\r\n\r\n            // Show data\r\n            // FIXME-TABLE FIXME-NAV: How we can get decent up/down even though we have the buttons here?\r\n            ImGui::PushButtonRepeat(true);\r\n#if 1\r\n            // Demonstrate using clipper for large vertical lists\r\n            ImGuiListClipper clipper;\r\n            clipper.Begin(items.Size);\r\n            while (clipper.Step())\r\n            {\r\n                for (int row_n = clipper.DisplayStart; row_n < clipper.DisplayEnd; row_n++)\r\n#else\r\n            // Without clipper\r\n            {\r\n                for (int row_n = 0; row_n < items.Size; row_n++)\r\n#endif\r\n                {\r\n                    MyItem* item = &items[row_n];\r\n                    //if (!filter.PassFilter(item->Name))\r\n                    //    continue;\r\n\r\n                    const bool item_is_selected = selection.contains(item->ID);\r\n                    ImGui::PushID(item->ID);\r\n                    ImGui::TableNextRow(ImGuiTableRowFlags_None, row_min_height);\r\n\r\n                    // For the demo purpose we can select among different type of items submitted in the first column\r\n                    ImGui::TableSetColumnIndex(0);\r\n                    char label[32];\r\n                    sprintf(label, \"%04d\", item->ID);\r\n                    if (contents_type == CT_Text)\r\n                        ImGui::TextUnformatted(label);\r\n                    else if (contents_type == CT_Button)\r\n                        ImGui::Button(label);\r\n                    else if (contents_type == CT_SmallButton)\r\n                        ImGui::SmallButton(label);\r\n                    else if (contents_type == CT_FillButton)\r\n                        ImGui::Button(label, ImVec2(-FLT_MIN, 0.0f));\r\n                    else if (contents_type == CT_Selectable || contents_type == CT_SelectableSpanRow)\r\n                    {\r\n                        ImGuiSelectableFlags selectable_flags = (contents_type == CT_SelectableSpanRow) ? ImGuiSelectableFlags_SpanAllColumns | ImGuiSelectableFlags_AllowItemOverlap : ImGuiSelectableFlags_None;\r\n                        if (ImGui::Selectable(label, item_is_selected, selectable_flags, ImVec2(0, row_min_height)))\r\n                        {\r\n                            if (ImGui::GetIO().KeyCtrl)\r\n                            {\r\n                                if (item_is_selected)\r\n                                    selection.find_erase_unsorted(item->ID);\r\n                                else\r\n                                    selection.push_back(item->ID);\r\n                            }\r\n                            else\r\n                            {\r\n                                selection.clear();\r\n                                selection.push_back(item->ID);\r\n                            }\r\n                        }\r\n                    }\r\n\r\n                    if (ImGui::TableSetColumnIndex(1))\r\n                        ImGui::TextUnformatted(item->Name);\r\n\r\n                    // Here we demonstrate marking our data set as needing to be sorted again if we modified a quantity,\r\n                    // and we are currently sorting on the column showing the Quantity.\r\n                    // To avoid triggering a sort while holding the button, we only trigger it when the button has been released.\r\n                    // You will probably need a more advanced system in your code if you want to automatically sort when a specific entry changes.\r\n                    if (ImGui::TableSetColumnIndex(2))\r\n                    {\r\n                        if (ImGui::SmallButton(\"Chop\")) { item->Quantity += 1; }\r\n                        if (sorts_specs_using_quantity && ImGui::IsItemDeactivated()) { items_need_sort = true; }\r\n                        ImGui::SameLine();\r\n                        if (ImGui::SmallButton(\"Eat\")) { item->Quantity -= 1; }\r\n                        if (sorts_specs_using_quantity && ImGui::IsItemDeactivated()) { items_need_sort = true; }\r\n                    }\r\n\r\n                    if (ImGui::TableSetColumnIndex(3))\r\n                        ImGui::Text(\"%d\", item->Quantity);\r\n\r\n                    ImGui::TableSetColumnIndex(4);\r\n                    if (show_wrapped_text)\r\n                        ImGui::TextWrapped(\"Lorem ipsum dolor sit amet\");\r\n                    else\r\n                        ImGui::Text(\"Lorem ipsum dolor sit amet\");\r\n\r\n                    if (ImGui::TableSetColumnIndex(5))\r\n                        ImGui::Text(\"1234\");\r\n\r\n                    ImGui::PopID();\r\n                }\r\n            }\r\n            ImGui::PopButtonRepeat();\r\n\r\n            // Store some info to display debug details below\r\n            table_scroll_cur = ImVec2(ImGui::GetScrollX(), ImGui::GetScrollY());\r\n            table_scroll_max = ImVec2(ImGui::GetScrollMaxX(), ImGui::GetScrollMaxY());\r\n            table_draw_list = ImGui::GetWindowDrawList();\r\n            ImGui::EndTable();\r\n        }\r\n        static bool show_debug_details = false;\r\n        ImGui::Checkbox(\"Debug details\", &show_debug_details);\r\n        if (show_debug_details && table_draw_list)\r\n        {\r\n            ImGui::SameLine(0.0f, 0.0f);\r\n            const int table_draw_list_draw_cmd_count = table_draw_list->CmdBuffer.Size;\r\n            if (table_draw_list == parent_draw_list)\r\n                ImGui::Text(\": DrawCmd: +%d (in same window)\",\r\n                    table_draw_list_draw_cmd_count - parent_draw_list_draw_cmd_count);\r\n            else\r\n                ImGui::Text(\": DrawCmd: +%d (in child window), Scroll: (%.f/%.f) (%.f/%.f)\",\r\n                    table_draw_list_draw_cmd_count - 1, table_scroll_cur.x, table_scroll_max.x, table_scroll_cur.y, table_scroll_max.y);\r\n        }\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    ImGui::PopID();\r\n\r\n    ShowDemoWindowColumns();\r\n\r\n    if (disable_indent)\r\n        ImGui::PopStyleVar();\r\n}\r\n\r\n// Demonstrate old/legacy Columns API!\r\n// [2020: Columns are under-featured and not maintained. Prefer using the more flexible and powerful BeginTable() API!]\r\nstatic void ShowDemoWindowColumns()\r\n{\r\n    IMGUI_DEMO_MARKER(\"Columns (legacy API)\");\r\n    bool open = ImGui::TreeNode(\"Legacy Columns API\");\r\n    ImGui::SameLine();\r\n    HelpMarker(\"Columns() is an old API! Prefer using the more flexible and powerful BeginTable() API!\");\r\n    if (!open)\r\n        return;\r\n\r\n    // Basic columns\r\n    IMGUI_DEMO_MARKER(\"Columns (legacy API)/Basic\");\r\n    if (ImGui::TreeNode(\"Basic\"))\r\n    {\r\n        ImGui::Text(\"Without border:\");\r\n        ImGui::Columns(3, \"mycolumns3\", false);  // 3-ways, no border\r\n        ImGui::Separator();\r\n        for (int n = 0; n < 14; n++)\r\n        {\r\n            char label[32];\r\n            sprintf(label, \"Item %d\", n);\r\n            if (ImGui::Selectable(label)) {}\r\n            //if (ImGui::Button(label, ImVec2(-FLT_MIN,0.0f))) {}\r\n            ImGui::NextColumn();\r\n        }\r\n        ImGui::Columns(1);\r\n        ImGui::Separator();\r\n\r\n        ImGui::Text(\"With border:\");\r\n        ImGui::Columns(4, \"mycolumns\"); // 4-ways, with border\r\n        ImGui::Separator();\r\n        ImGui::Text(\"ID\"); ImGui::NextColumn();\r\n        ImGui::Text(\"Name\"); ImGui::NextColumn();\r\n        ImGui::Text(\"Path\"); ImGui::NextColumn();\r\n        ImGui::Text(\"Hovered\"); ImGui::NextColumn();\r\n        ImGui::Separator();\r\n        const char* names[3] = { \"One\", \"Two\", \"Three\" };\r\n        const char* paths[3] = { \"/path/one\", \"/path/two\", \"/path/three\" };\r\n        static int selected = -1;\r\n        for (int i = 0; i < 3; i++)\r\n        {\r\n            char label[32];\r\n            sprintf(label, \"%04d\", i);\r\n            if (ImGui::Selectable(label, selected == i, ImGuiSelectableFlags_SpanAllColumns))\r\n                selected = i;\r\n            bool hovered = ImGui::IsItemHovered();\r\n            ImGui::NextColumn();\r\n            ImGui::Text(names[i]); ImGui::NextColumn();\r\n            ImGui::Text(paths[i]); ImGui::NextColumn();\r\n            ImGui::Text(\"%d\", hovered); ImGui::NextColumn();\r\n        }\r\n        ImGui::Columns(1);\r\n        ImGui::Separator();\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    IMGUI_DEMO_MARKER(\"Columns (legacy API)/Borders\");\r\n    if (ImGui::TreeNode(\"Borders\"))\r\n    {\r\n        // NB: Future columns API should allow automatic horizontal borders.\r\n        static bool h_borders = true;\r\n        static bool v_borders = true;\r\n        static int columns_count = 4;\r\n        const int lines_count = 3;\r\n        ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8);\r\n        ImGui::DragInt(\"##columns_count\", &columns_count, 0.1f, 2, 10, \"%d columns\");\r\n        if (columns_count < 2)\r\n            columns_count = 2;\r\n        ImGui::SameLine();\r\n        ImGui::Checkbox(\"horizontal\", &h_borders);\r\n        ImGui::SameLine();\r\n        ImGui::Checkbox(\"vertical\", &v_borders);\r\n        ImGui::Columns(columns_count, NULL, v_borders);\r\n        for (int i = 0; i < columns_count * lines_count; i++)\r\n        {\r\n            if (h_borders && ImGui::GetColumnIndex() == 0)\r\n                ImGui::Separator();\r\n            ImGui::Text(\"%c%c%c\", 'a' + i, 'a' + i, 'a' + i);\r\n            ImGui::Text(\"Width %.2f\", ImGui::GetColumnWidth());\r\n            ImGui::Text(\"Avail %.2f\", ImGui::GetContentRegionAvail().x);\r\n            ImGui::Text(\"Offset %.2f\", ImGui::GetColumnOffset());\r\n            ImGui::Text(\"Long text that is likely to clip\");\r\n            ImGui::Button(\"Button\", ImVec2(-FLT_MIN, 0.0f));\r\n            ImGui::NextColumn();\r\n        }\r\n        ImGui::Columns(1);\r\n        if (h_borders)\r\n            ImGui::Separator();\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    // Create multiple items in a same cell before switching to next column\r\n    IMGUI_DEMO_MARKER(\"Columns (legacy API)/Mixed items\");\r\n    if (ImGui::TreeNode(\"Mixed items\"))\r\n    {\r\n        ImGui::Columns(3, \"mixed\");\r\n        ImGui::Separator();\r\n\r\n        ImGui::Text(\"Hello\");\r\n        ImGui::Button(\"Banana\");\r\n        ImGui::NextColumn();\r\n\r\n        ImGui::Text(\"ImGui\");\r\n        ImGui::Button(\"Apple\");\r\n        static float foo = 1.0f;\r\n        ImGui::InputFloat(\"red\", &foo, 0.05f, 0, \"%.3f\");\r\n        ImGui::Text(\"An extra line here.\");\r\n        ImGui::NextColumn();\r\n\r\n        ImGui::Text(\"Sailor\");\r\n        ImGui::Button(\"Corniflower\");\r\n        static float bar = 1.0f;\r\n        ImGui::InputFloat(\"blue\", &bar, 0.05f, 0, \"%.3f\");\r\n        ImGui::NextColumn();\r\n\r\n        if (ImGui::CollapsingHeader(\"Category A\")) { ImGui::Text(\"Blah blah blah\"); } ImGui::NextColumn();\r\n        if (ImGui::CollapsingHeader(\"Category B\")) { ImGui::Text(\"Blah blah blah\"); } ImGui::NextColumn();\r\n        if (ImGui::CollapsingHeader(\"Category C\")) { ImGui::Text(\"Blah blah blah\"); } ImGui::NextColumn();\r\n        ImGui::Columns(1);\r\n        ImGui::Separator();\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    // Word wrapping\r\n    IMGUI_DEMO_MARKER(\"Columns (legacy API)/Word-wrapping\");\r\n    if (ImGui::TreeNode(\"Word-wrapping\"))\r\n    {\r\n        ImGui::Columns(2, \"word-wrapping\");\r\n        ImGui::Separator();\r\n        ImGui::TextWrapped(\"The quick brown fox jumps over the lazy dog.\");\r\n        ImGui::TextWrapped(\"Hello Left\");\r\n        ImGui::NextColumn();\r\n        ImGui::TextWrapped(\"The quick brown fox jumps over the lazy dog.\");\r\n        ImGui::TextWrapped(\"Hello Right\");\r\n        ImGui::Columns(1);\r\n        ImGui::Separator();\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    IMGUI_DEMO_MARKER(\"Columns (legacy API)/Horizontal Scrolling\");\r\n    if (ImGui::TreeNode(\"Horizontal Scrolling\"))\r\n    {\r\n        ImGui::SetNextWindowContentSize(ImVec2(1500.0f, 0.0f));\r\n        ImVec2 child_size = ImVec2(0, ImGui::GetFontSize() * 20.0f);\r\n        ImGui::BeginChild(\"##ScrollingRegion\", child_size, false, ImGuiWindowFlags_HorizontalScrollbar);\r\n        ImGui::Columns(10);\r\n\r\n        // Also demonstrate using clipper for large vertical lists\r\n        int ITEMS_COUNT = 2000;\r\n        ImGuiListClipper clipper;\r\n        clipper.Begin(ITEMS_COUNT);\r\n        while (clipper.Step())\r\n        {\r\n            for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)\r\n                for (int j = 0; j < 10; j++)\r\n                {\r\n                    ImGui::Text(\"Line %d Column %d...\", i, j);\r\n                    ImGui::NextColumn();\r\n                }\r\n        }\r\n        ImGui::Columns(1);\r\n        ImGui::EndChild();\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    IMGUI_DEMO_MARKER(\"Columns (legacy API)/Tree\");\r\n    if (ImGui::TreeNode(\"Tree\"))\r\n    {\r\n        ImGui::Columns(2, \"tree\", true);\r\n        for (int x = 0; x < 3; x++)\r\n        {\r\n            bool open1 = ImGui::TreeNode((void*)(intptr_t)x, \"Node%d\", x);\r\n            ImGui::NextColumn();\r\n            ImGui::Text(\"Node contents\");\r\n            ImGui::NextColumn();\r\n            if (open1)\r\n            {\r\n                for (int y = 0; y < 3; y++)\r\n                {\r\n                    bool open2 = ImGui::TreeNode((void*)(intptr_t)y, \"Node%d.%d\", x, y);\r\n                    ImGui::NextColumn();\r\n                    ImGui::Text(\"Node contents\");\r\n                    if (open2)\r\n                    {\r\n                        ImGui::Text(\"Even more contents\");\r\n                        if (ImGui::TreeNode(\"Tree in column\"))\r\n                        {\r\n                            ImGui::Text(\"The quick brown fox jumps over the lazy dog\");\r\n                            ImGui::TreePop();\r\n                        }\r\n                    }\r\n                    ImGui::NextColumn();\r\n                    if (open2)\r\n                        ImGui::TreePop();\r\n                }\r\n                ImGui::TreePop();\r\n            }\r\n        }\r\n        ImGui::Columns(1);\r\n        ImGui::TreePop();\r\n    }\r\n\r\n    ImGui::TreePop();\r\n}\r\n\r\nnamespace ImGui { extern ImGuiKeyData* GetKeyData(ImGuiKey key); }\r\n\r\nstatic void ShowDemoWindowMisc()\r\n{\r\n    IMGUI_DEMO_MARKER(\"Filtering\");\r\n    if (ImGui::CollapsingHeader(\"Filtering\"))\r\n    {\r\n        // Helper class to easy setup a text filter.\r\n        // You may want to implement a more feature-full filtering scheme in your own application.\r\n        static ImGuiTextFilter filter;\r\n        ImGui::Text(\"Filter usage:\\n\"\r\n                    \"  \\\"\\\"         display all lines\\n\"\r\n                    \"  \\\"xxx\\\"      display lines containing \\\"xxx\\\"\\n\"\r\n                    \"  \\\"xxx,yyy\\\"  display lines containing \\\"xxx\\\" or \\\"yyy\\\"\\n\"\r\n                    \"  \\\"-xxx\\\"     hide lines containing \\\"xxx\\\"\");\r\n        filter.Draw();\r\n        const char* lines[] = { \"aaa1.c\", \"bbb1.c\", \"ccc1.c\", \"aaa2.cpp\", \"bbb2.cpp\", \"ccc2.cpp\", \"abc.h\", \"hello, world\" };\r\n        for (int i = 0; i < IM_ARRAYSIZE(lines); i++)\r\n            if (filter.PassFilter(lines[i]))\r\n                ImGui::BulletText(\"%s\", lines[i]);\r\n    }\r\n\r\n    IMGUI_DEMO_MARKER(\"Inputs, Navigation & Focus\");\r\n    if (ImGui::CollapsingHeader(\"Inputs, Navigation & Focus\"))\r\n    {\r\n        ImGuiIO& io = ImGui::GetIO();\r\n\r\n        // Display ImGuiIO output flags\r\n        ImGui::Text(\"WantCaptureMouse: %d\", io.WantCaptureMouse);\r\n        ImGui::Text(\"WantCaptureMouseUnlessPopupClose: %d\", io.WantCaptureMouseUnlessPopupClose);\r\n        ImGui::Text(\"WantCaptureKeyboard: %d\", io.WantCaptureKeyboard);\r\n        ImGui::Text(\"WantTextInput: %d\", io.WantTextInput);\r\n        ImGui::Text(\"WantSetMousePos: %d\", io.WantSetMousePos);\r\n        ImGui::Text(\"NavActive: %d, NavVisible: %d\", io.NavActive, io.NavVisible);\r\n\r\n        // Display Mouse state\r\n        IMGUI_DEMO_MARKER(\"Inputs, Navigation & Focus/Mouse State\");\r\n        if (ImGui::TreeNode(\"Mouse State\"))\r\n        {\r\n            if (ImGui::IsMousePosValid())\r\n                ImGui::Text(\"Mouse pos: (%g, %g)\", io.MousePos.x, io.MousePos.y);\r\n            else\r\n                ImGui::Text(\"Mouse pos: <INVALID>\");\r\n            ImGui::Text(\"Mouse delta: (%g, %g)\", io.MouseDelta.x, io.MouseDelta.y);\r\n\r\n            int count = IM_ARRAYSIZE(io.MouseDown);\r\n            ImGui::Text(\"Mouse down:\");         for (int i = 0; i < count; i++) if (ImGui::IsMouseDown(i))      { ImGui::SameLine(); ImGui::Text(\"b%d (%.02f secs)\", i, io.MouseDownDuration[i]); }\r\n            ImGui::Text(\"Mouse clicked:\");      for (int i = 0; i < count; i++) if (ImGui::IsMouseClicked(i))   { ImGui::SameLine(); ImGui::Text(\"b%d (%d)\", i, ImGui::GetMouseClickedCount(i)); }\r\n            ImGui::Text(\"Mouse released:\");     for (int i = 0; i < count; i++) if (ImGui::IsMouseReleased(i))  { ImGui::SameLine(); ImGui::Text(\"b%d\", i); }\r\n            ImGui::Text(\"Mouse wheel: %.1f\", io.MouseWheel);\r\n            ImGui::Text(\"Pen Pressure: %.1f\", io.PenPressure); // Note: currently unused\r\n            ImGui::TreePop();\r\n        }\r\n\r\n        // Display Keyboard/Mouse state\r\n        IMGUI_DEMO_MARKER(\"Inputs, Navigation & Focus/Keyboard, Gamepad & Navigation State\");\r\n        if (ImGui::TreeNode(\"Keyboard, Gamepad & Navigation State\"))\r\n        {\r\n            // We iterate both legacy native range and named ImGuiKey ranges, which is a little odd but this allow displaying the data for old/new backends.\r\n            // User code should never have to go through such hoops: old code may use native keycodes, new code may use ImGuiKey codes.\r\n#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO\r\n            struct funcs { static bool IsLegacyNativeDupe(ImGuiKey) { return false; } };\r\n            const ImGuiKey key_first = ImGuiKey_NamedKey_BEGIN;\r\n#else\r\n            struct funcs { static bool IsLegacyNativeDupe(ImGuiKey key) { return key < 512 && ImGui::GetIO().KeyMap[key] != -1; } }; // Hide Native<>ImGuiKey duplicates when both exists in the array\r\n            const ImGuiKey key_first = 0;\r\n#endif\r\n            ImGui::Text(\"Keys down:\");          for (ImGuiKey key = key_first; key < ImGuiKey_COUNT; key++) { if (funcs::IsLegacyNativeDupe(key)) continue; if (ImGui::IsKeyDown(key)) { ImGui::SameLine(); ImGui::Text(\"\\\"%s\\\" %d (%.02f secs)\", ImGui::GetKeyName(key), key, ImGui::GetKeyData(key)->DownDuration); } }\r\n            ImGui::Text(\"Keys pressed:\");       for (ImGuiKey key = key_first; key < ImGuiKey_COUNT; key++) { if (funcs::IsLegacyNativeDupe(key)) continue; if (ImGui::IsKeyPressed(key)) { ImGui::SameLine(); ImGui::Text(\"\\\"%s\\\" %d\", ImGui::GetKeyName(key), key); } }\r\n            ImGui::Text(\"Keys released:\");      for (ImGuiKey key = key_first; key < ImGuiKey_COUNT; key++) { if (funcs::IsLegacyNativeDupe(key)) continue; if (ImGui::IsKeyReleased(key)) { ImGui::SameLine(); ImGui::Text(\"\\\"%s\\\" %d\", ImGui::GetKeyName(key), key); } }\r\n            ImGui::Text(\"Keys mods: %s%s%s%s\", io.KeyCtrl ? \"CTRL \" : \"\", io.KeyShift ? \"SHIFT \" : \"\", io.KeyAlt ? \"ALT \" : \"\", io.KeySuper ? \"SUPER \" : \"\");\r\n            ImGui::Text(\"Chars queue:\");        for (int i = 0; i < io.InputQueueCharacters.Size; i++) { ImWchar c = io.InputQueueCharacters[i]; ImGui::SameLine();  ImGui::Text(\"\\'%c\\' (0x%04X)\", (c > ' ' && c <= 255) ? (char)c : '?', c); } // FIXME: We should convert 'c' to UTF-8 here but the functions are not public.\r\n            ImGui::Text(\"NavInputs down:\");     for (int i = 0; i < IM_ARRAYSIZE(io.NavInputs); i++) if (io.NavInputs[i] > 0.0f)              { ImGui::SameLine(); ImGui::Text(\"[%d] %.2f (%.02f secs)\", i, io.NavInputs[i], io.NavInputsDownDuration[i]); }\r\n            ImGui::Text(\"NavInputs pressed:\");  for (int i = 0; i < IM_ARRAYSIZE(io.NavInputs); i++) if (io.NavInputsDownDuration[i] == 0.0f) { ImGui::SameLine(); ImGui::Text(\"[%d]\", i); }\r\n\r\n            // Draw an arbitrary US keyboard layout to visualize translated keys\r\n            {\r\n                const ImVec2 key_size = ImVec2(35.0f, 35.0f);\r\n                const float  key_rounding = 3.0f;\r\n                const ImVec2 key_face_size = ImVec2(25.0f, 25.0f);\r\n                const ImVec2 key_face_pos = ImVec2(5.0f, 3.0f);\r\n                const float  key_face_rounding = 2.0f;\r\n                const ImVec2 key_label_pos = ImVec2(7.0f, 4.0f);\r\n                const ImVec2 key_step = ImVec2(key_size.x - 1.0f, key_size.y - 1.0f);\r\n                const float  key_row_offset = 9.0f;\r\n\r\n                ImVec2 board_min = ImGui::GetCursorScreenPos();\r\n                ImVec2 board_max = ImVec2(board_min.x + 3 * key_step.x + 2 * key_row_offset + 10.0f, board_min.y + 3 * key_step.y + 10.0f);\r\n                ImVec2 start_pos = ImVec2(board_min.x + 5.0f - key_step.x, board_min.y);\r\n\r\n                struct KeyLayoutData { int Row, Col; const char* Label; ImGuiKey Key; };\r\n                const KeyLayoutData keys_to_display[] =\r\n                {\r\n                    { 0, 0, \"\", ImGuiKey_Tab },      { 0, 1, \"Q\", ImGuiKey_Q }, { 0, 2, \"W\", ImGuiKey_W }, { 0, 3, \"E\", ImGuiKey_E }, { 0, 4, \"R\", ImGuiKey_R },\r\n                    { 1, 0, \"\", ImGuiKey_CapsLock }, { 1, 1, \"A\", ImGuiKey_A }, { 1, 2, \"S\", ImGuiKey_S }, { 1, 3, \"D\", ImGuiKey_D }, { 1, 4, \"F\", ImGuiKey_F },\r\n                    { 2, 0, \"\", ImGuiKey_LeftShift },{ 2, 1, \"Z\", ImGuiKey_Z }, { 2, 2, \"X\", ImGuiKey_X }, { 2, 3, \"C\", ImGuiKey_C }, { 2, 4, \"V\", ImGuiKey_V }\r\n                };\r\n\r\n                ImDrawList* draw_list = ImGui::GetWindowDrawList();\r\n                draw_list->PushClipRect(board_min, board_max, true);\r\n                for (int n = 0; n < IM_ARRAYSIZE(keys_to_display); n++)\r\n                {\r\n                    const KeyLayoutData* key_data = &keys_to_display[n];\r\n                    ImVec2 key_min = ImVec2(start_pos.x + key_data->Col * key_step.x + key_data->Row * key_row_offset, start_pos.y + key_data->Row * key_step.y);\r\n                    ImVec2 key_max = ImVec2(key_min.x + key_size.x, key_min.y + key_size.y);\r\n                    draw_list->AddRectFilled(key_min, key_max, IM_COL32(204, 204, 204, 255), key_rounding);\r\n                    draw_list->AddRect(key_min, key_max, IM_COL32(24, 24, 24, 255), key_rounding);\r\n                    ImVec2 face_min = ImVec2(key_min.x + key_face_pos.x, key_min.y + key_face_pos.y);\r\n                    ImVec2 face_max = ImVec2(face_min.x + key_face_size.x, face_min.y + key_face_size.y);\r\n                    draw_list->AddRect(face_min, face_max, IM_COL32(193, 193, 193, 255), key_face_rounding, ImDrawFlags_None, 2.0f);\r\n                    draw_list->AddRectFilled(face_min, face_max, IM_COL32(252, 252, 252, 255), key_face_rounding);\r\n                    ImVec2 label_min = ImVec2(key_min.x + key_label_pos.x, key_min.y + key_label_pos.y);\r\n                    draw_list->AddText(label_min, IM_COL32(64, 64, 64, 255), key_data->Label);\r\n                    if (ImGui::IsKeyDown(key_data->Key))\r\n                        draw_list->AddRectFilled(key_min, key_max, IM_COL32(255, 0, 0, 128), key_rounding);\r\n                }\r\n                draw_list->PopClipRect();\r\n                ImGui::Dummy(ImVec2(board_max.x - board_min.x, board_max.y - board_min.y));\r\n            }\r\n            ImGui::TreePop();\r\n        }\r\n\r\n        if (ImGui::TreeNode(\"Capture override\"))\r\n        {\r\n            ImGui::Button(\"Hovering me sets the\\nkeyboard capture flag\");\r\n            if (ImGui::IsItemHovered())\r\n                ImGui::CaptureKeyboardFromApp(true);\r\n            ImGui::SameLine();\r\n            ImGui::Button(\"Holding me clears the\\nthe keyboard capture flag\");\r\n            if (ImGui::IsItemActive())\r\n                ImGui::CaptureKeyboardFromApp(false);\r\n            ImGui::TreePop();\r\n        }\r\n\r\n        IMGUI_DEMO_MARKER(\"Inputs, Navigation & Focus/Tabbing\");\r\n        if (ImGui::TreeNode(\"Tabbing\"))\r\n        {\r\n            ImGui::Text(\"Use TAB/SHIFT+TAB to cycle through keyboard editable fields.\");\r\n            static char buf[32] = \"hello\";\r\n            ImGui::InputText(\"1\", buf, IM_ARRAYSIZE(buf));\r\n            ImGui::InputText(\"2\", buf, IM_ARRAYSIZE(buf));\r\n            ImGui::InputText(\"3\", buf, IM_ARRAYSIZE(buf));\r\n            ImGui::PushAllowKeyboardFocus(false);\r\n            ImGui::InputText(\"4 (tab skip)\", buf, IM_ARRAYSIZE(buf));\r\n            ImGui::SameLine(); HelpMarker(\"Item won't be cycled through when using TAB or Shift+Tab.\");\r\n            ImGui::PopAllowKeyboardFocus();\r\n            ImGui::InputText(\"5\", buf, IM_ARRAYSIZE(buf));\r\n            ImGui::TreePop();\r\n        }\r\n\r\n        IMGUI_DEMO_MARKER(\"Inputs, Navigation & Focus/Focus from code\");\r\n        if (ImGui::TreeNode(\"Focus from code\"))\r\n        {\r\n            bool focus_1 = ImGui::Button(\"Focus on 1\"); ImGui::SameLine();\r\n            bool focus_2 = ImGui::Button(\"Focus on 2\"); ImGui::SameLine();\r\n            bool focus_3 = ImGui::Button(\"Focus on 3\");\r\n            int has_focus = 0;\r\n            static char buf[128] = \"click on a button to set focus\";\r\n\r\n            if (focus_1) ImGui::SetKeyboardFocusHere();\r\n            ImGui::InputText(\"1\", buf, IM_ARRAYSIZE(buf));\r\n            if (ImGui::IsItemActive()) has_focus = 1;\r\n\r\n            if (focus_2) ImGui::SetKeyboardFocusHere();\r\n            ImGui::InputText(\"2\", buf, IM_ARRAYSIZE(buf));\r\n            if (ImGui::IsItemActive()) has_focus = 2;\r\n\r\n            ImGui::PushAllowKeyboardFocus(false);\r\n            if (focus_3) ImGui::SetKeyboardFocusHere();\r\n            ImGui::InputText(\"3 (tab skip)\", buf, IM_ARRAYSIZE(buf));\r\n            if (ImGui::IsItemActive()) has_focus = 3;\r\n            ImGui::SameLine(); HelpMarker(\"Item won't be cycled through when using TAB or Shift+Tab.\");\r\n            ImGui::PopAllowKeyboardFocus();\r\n\r\n            if (has_focus)\r\n                ImGui::Text(\"Item with focus: %d\", has_focus);\r\n            else\r\n                ImGui::Text(\"Item with focus: <none>\");\r\n\r\n            // Use >= 0 parameter to SetKeyboardFocusHere() to focus an upcoming item\r\n            static float f3[3] = { 0.0f, 0.0f, 0.0f };\r\n            int focus_ahead = -1;\r\n            if (ImGui::Button(\"Focus on X\")) { focus_ahead = 0; } ImGui::SameLine();\r\n            if (ImGui::Button(\"Focus on Y\")) { focus_ahead = 1; } ImGui::SameLine();\r\n            if (ImGui::Button(\"Focus on Z\")) { focus_ahead = 2; }\r\n            if (focus_ahead != -1) ImGui::SetKeyboardFocusHere(focus_ahead);\r\n            ImGui::SliderFloat3(\"Float3\", &f3[0], 0.0f, 1.0f);\r\n\r\n            ImGui::TextWrapped(\"NB: Cursor & selection are preserved when refocusing last used item in code.\");\r\n            ImGui::TreePop();\r\n        }\r\n\r\n        IMGUI_DEMO_MARKER(\"Inputs, Navigation & Focus/Dragging\");\r\n        if (ImGui::TreeNode(\"Dragging\"))\r\n        {\r\n            ImGui::TextWrapped(\"You can use ImGui::GetMouseDragDelta(0) to query for the dragged amount on any widget.\");\r\n            for (int button = 0; button < 3; button++)\r\n            {\r\n                ImGui::Text(\"IsMouseDragging(%d):\", button);\r\n                ImGui::Text(\"  w/ default threshold: %d,\", ImGui::IsMouseDragging(button));\r\n                ImGui::Text(\"  w/ zero threshold: %d,\", ImGui::IsMouseDragging(button, 0.0f));\r\n                ImGui::Text(\"  w/ large threshold: %d,\", ImGui::IsMouseDragging(button, 20.0f));\r\n            }\r\n\r\n            ImGui::Button(\"Drag Me\");\r\n            if (ImGui::IsItemActive())\r\n                ImGui::GetForegroundDrawList()->AddLine(io.MouseClickedPos[0], io.MousePos, ImGui::GetColorU32(ImGuiCol_Button), 4.0f); // Draw a line between the button and the mouse cursor\r\n\r\n            // Drag operations gets \"unlocked\" when the mouse has moved past a certain threshold\r\n            // (the default threshold is stored in io.MouseDragThreshold). You can request a lower or higher\r\n            // threshold using the second parameter of IsMouseDragging() and GetMouseDragDelta().\r\n            ImVec2 value_raw = ImGui::GetMouseDragDelta(0, 0.0f);\r\n            ImVec2 value_with_lock_threshold = ImGui::GetMouseDragDelta(0);\r\n            ImVec2 mouse_delta = io.MouseDelta;\r\n            ImGui::Text(\"GetMouseDragDelta(0):\");\r\n            ImGui::Text(\"  w/ default threshold: (%.1f, %.1f)\", value_with_lock_threshold.x, value_with_lock_threshold.y);\r\n            ImGui::Text(\"  w/ zero threshold: (%.1f, %.1f)\", value_raw.x, value_raw.y);\r\n            ImGui::Text(\"io.MouseDelta: (%.1f, %.1f)\", mouse_delta.x, mouse_delta.y);\r\n            ImGui::TreePop();\r\n        }\r\n\r\n        IMGUI_DEMO_MARKER(\"Inputs, Navigation & Focus/Mouse cursors\");\r\n        if (ImGui::TreeNode(\"Mouse cursors\"))\r\n        {\r\n            const char* mouse_cursors_names[] = { \"Arrow\", \"TextInput\", \"ResizeAll\", \"ResizeNS\", \"ResizeEW\", \"ResizeNESW\", \"ResizeNWSE\", \"Hand\", \"NotAllowed\" };\r\n            IM_ASSERT(IM_ARRAYSIZE(mouse_cursors_names) == ImGuiMouseCursor_COUNT);\r\n\r\n            ImGuiMouseCursor current = ImGui::GetMouseCursor();\r\n            ImGui::Text(\"Current mouse cursor = %d: %s\", current, mouse_cursors_names[current]);\r\n            ImGui::Text(\"Hover to see mouse cursors:\");\r\n            ImGui::SameLine(); HelpMarker(\r\n                \"Your application can render a different mouse cursor based on what ImGui::GetMouseCursor() returns. \"\r\n                \"If software cursor rendering (io.MouseDrawCursor) is set ImGui will draw the right cursor for you, \"\r\n                \"otherwise your backend needs to handle it.\");\r\n            for (int i = 0; i < ImGuiMouseCursor_COUNT; i++)\r\n            {\r\n                char label[32];\r\n                sprintf(label, \"Mouse cursor %d: %s\", i, mouse_cursors_names[i]);\r\n                ImGui::Bullet(); ImGui::Selectable(label, false);\r\n                if (ImGui::IsItemHovered())\r\n                    ImGui::SetMouseCursor(i);\r\n            }\r\n            ImGui::TreePop();\r\n        }\r\n    }\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] About Window / ShowAboutWindow()\r\n// Access from Dear ImGui Demo -> Tools -> About\r\n//-----------------------------------------------------------------------------\r\n\r\nvoid ImGui::ShowAboutWindow(bool* p_open)\r\n{\r\n    if (!ImGui::Begin(\"About Dear ImGui\", p_open, ImGuiWindowFlags_AlwaysAutoResize))\r\n    {\r\n        ImGui::End();\r\n        return;\r\n    }\r\n    IMGUI_DEMO_MARKER(\"Tools/About Dear ImGui\");\r\n    ImGui::Text(\"Dear ImGui %s\", ImGui::GetVersion());\r\n    ImGui::Separator();\r\n    ImGui::Text(\"By Omar Cornut and all Dear ImGui contributors.\");\r\n    ImGui::Text(\"Dear ImGui is licensed under the MIT License, see LICENSE for more information.\");\r\n\r\n    static bool show_config_info = false;\r\n    ImGui::Checkbox(\"Config/Build Information\", &show_config_info);\r\n    if (show_config_info)\r\n    {\r\n        ImGuiIO& io = ImGui::GetIO();\r\n        ImGuiStyle& style = ImGui::GetStyle();\r\n\r\n        bool copy_to_clipboard = ImGui::Button(\"Copy to clipboard\");\r\n        ImVec2 child_size = ImVec2(0, ImGui::GetTextLineHeightWithSpacing() * 18);\r\n        ImGui::BeginChildFrame(ImGui::GetID(\"cfg_infos\"), child_size, ImGuiWindowFlags_NoMove);\r\n        if (copy_to_clipboard)\r\n        {\r\n            ImGui::LogToClipboard();\r\n            ImGui::LogText(\"```\\n\"); // Back quotes will make text appears without formatting when pasting on GitHub\r\n        }\r\n\r\n        ImGui::Text(\"Dear ImGui %s (%d)\", IMGUI_VERSION, IMGUI_VERSION_NUM);\r\n        ImGui::Separator();\r\n        ImGui::Text(\"sizeof(size_t): %d, sizeof(ImDrawIdx): %d, sizeof(ImDrawVert): %d\", (int)sizeof(size_t), (int)sizeof(ImDrawIdx), (int)sizeof(ImDrawVert));\r\n        ImGui::Text(\"define: __cplusplus=%d\", (int)__cplusplus);\r\n#ifdef IMGUI_DISABLE_OBSOLETE_FUNCTIONS\r\n        ImGui::Text(\"define: IMGUI_DISABLE_OBSOLETE_FUNCTIONS\");\r\n#endif\r\n#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO\r\n        ImGui::Text(\"define: IMGUI_DISABLE_OBSOLETE_KEYIO\");\r\n#endif\r\n#ifdef IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS\r\n        ImGui::Text(\"define: IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS\");\r\n#endif\r\n#ifdef IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS\r\n        ImGui::Text(\"define: IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS\");\r\n#endif\r\n#ifdef IMGUI_DISABLE_WIN32_FUNCTIONS\r\n        ImGui::Text(\"define: IMGUI_DISABLE_WIN32_FUNCTIONS\");\r\n#endif\r\n#ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS\r\n        ImGui::Text(\"define: IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS\");\r\n#endif\r\n#ifdef IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS\r\n        ImGui::Text(\"define: IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS\");\r\n#endif\r\n#ifdef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS\r\n        ImGui::Text(\"define: IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS\");\r\n#endif\r\n#ifdef IMGUI_DISABLE_FILE_FUNCTIONS\r\n        ImGui::Text(\"define: IMGUI_DISABLE_FILE_FUNCTIONS\");\r\n#endif\r\n#ifdef IMGUI_DISABLE_DEFAULT_ALLOCATORS\r\n        ImGui::Text(\"define: IMGUI_DISABLE_DEFAULT_ALLOCATORS\");\r\n#endif\r\n#ifdef IMGUI_USE_BGRA_PACKED_COLOR\r\n        ImGui::Text(\"define: IMGUI_USE_BGRA_PACKED_COLOR\");\r\n#endif\r\n#ifdef _WIN32\r\n        ImGui::Text(\"define: _WIN32\");\r\n#endif\r\n#ifdef _WIN64\r\n        ImGui::Text(\"define: _WIN64\");\r\n#endif\r\n#ifdef __linux__\r\n        ImGui::Text(\"define: __linux__\");\r\n#endif\r\n#ifdef __APPLE__\r\n        ImGui::Text(\"define: __APPLE__\");\r\n#endif\r\n#ifdef _MSC_VER\r\n        ImGui::Text(\"define: _MSC_VER=%d\", _MSC_VER);\r\n#endif\r\n#ifdef _MSVC_LANG\r\n        ImGui::Text(\"define: _MSVC_LANG=%d\", (int)_MSVC_LANG);\r\n#endif\r\n#ifdef __MINGW32__\r\n        ImGui::Text(\"define: __MINGW32__\");\r\n#endif\r\n#ifdef __MINGW64__\r\n        ImGui::Text(\"define: __MINGW64__\");\r\n#endif\r\n#ifdef __GNUC__\r\n        ImGui::Text(\"define: __GNUC__=%d\", (int)__GNUC__);\r\n#endif\r\n#ifdef __clang_version__\r\n        ImGui::Text(\"define: __clang_version__=%s\", __clang_version__);\r\n#endif\r\n        ImGui::Separator();\r\n        ImGui::Text(\"io.BackendPlatformName: %s\", io.BackendPlatformName ? io.BackendPlatformName : \"NULL\");\r\n        ImGui::Text(\"io.BackendRendererName: %s\", io.BackendRendererName ? io.BackendRendererName : \"NULL\");\r\n        ImGui::Text(\"io.ConfigFlags: 0x%08X\", io.ConfigFlags);\r\n        if (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard)        ImGui::Text(\" NavEnableKeyboard\");\r\n        if (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad)         ImGui::Text(\" NavEnableGamepad\");\r\n        if (io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos)     ImGui::Text(\" NavEnableSetMousePos\");\r\n        if (io.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard)     ImGui::Text(\" NavNoCaptureKeyboard\");\r\n        if (io.ConfigFlags & ImGuiConfigFlags_NoMouse)                  ImGui::Text(\" NoMouse\");\r\n        if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange)      ImGui::Text(\" NoMouseCursorChange\");\r\n        if (io.MouseDrawCursor)                                         ImGui::Text(\"io.MouseDrawCursor\");\r\n        if (io.ConfigMacOSXBehaviors)                                   ImGui::Text(\"io.ConfigMacOSXBehaviors\");\r\n        if (io.ConfigInputTextCursorBlink)                              ImGui::Text(\"io.ConfigInputTextCursorBlink\");\r\n        if (io.ConfigWindowsResizeFromEdges)                            ImGui::Text(\"io.ConfigWindowsResizeFromEdges\");\r\n        if (io.ConfigWindowsMoveFromTitleBarOnly)                       ImGui::Text(\"io.ConfigWindowsMoveFromTitleBarOnly\");\r\n        if (io.ConfigMemoryCompactTimer >= 0.0f)                        ImGui::Text(\"io.ConfigMemoryCompactTimer = %.1f\", io.ConfigMemoryCompactTimer);\r\n        ImGui::Text(\"io.BackendFlags: 0x%08X\", io.BackendFlags);\r\n        if (io.BackendFlags & ImGuiBackendFlags_HasGamepad)             ImGui::Text(\" HasGamepad\");\r\n        if (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors)        ImGui::Text(\" HasMouseCursors\");\r\n        if (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos)         ImGui::Text(\" HasSetMousePos\");\r\n        if (io.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)   ImGui::Text(\" RendererHasVtxOffset\");\r\n        ImGui::Separator();\r\n        ImGui::Text(\"io.Fonts: %d fonts, Flags: 0x%08X, TexSize: %d,%d\", io.Fonts->Fonts.Size, io.Fonts->Flags, io.Fonts->TexWidth, io.Fonts->TexHeight);\r\n        ImGui::Text(\"io.DisplaySize: %.2f,%.2f\", io.DisplaySize.x, io.DisplaySize.y);\r\n        ImGui::Text(\"io.DisplayFramebufferScale: %.2f,%.2f\", io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y);\r\n        ImGui::Separator();\r\n        ImGui::Text(\"style.WindowPadding: %.2f,%.2f\", style.WindowPadding.x, style.WindowPadding.y);\r\n        ImGui::Text(\"style.WindowBorderSize: %.2f\", style.WindowBorderSize);\r\n        ImGui::Text(\"style.FramePadding: %.2f,%.2f\", style.FramePadding.x, style.FramePadding.y);\r\n        ImGui::Text(\"style.FrameRounding: %.2f\", style.FrameRounding);\r\n        ImGui::Text(\"style.FrameBorderSize: %.2f\", style.FrameBorderSize);\r\n        ImGui::Text(\"style.ItemSpacing: %.2f,%.2f\", style.ItemSpacing.x, style.ItemSpacing.y);\r\n        ImGui::Text(\"style.ItemInnerSpacing: %.2f,%.2f\", style.ItemInnerSpacing.x, style.ItemInnerSpacing.y);\r\n\r\n        if (copy_to_clipboard)\r\n        {\r\n            ImGui::LogText(\"\\n```\\n\");\r\n            ImGui::LogFinish();\r\n        }\r\n        ImGui::EndChildFrame();\r\n    }\r\n    ImGui::End();\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Style Editor / ShowStyleEditor()\r\n//-----------------------------------------------------------------------------\r\n// - ShowFontSelector()\r\n// - ShowStyleSelector()\r\n// - ShowStyleEditor()\r\n//-----------------------------------------------------------------------------\r\n\r\n// Forward declare ShowFontAtlas() which isn't worth putting in public API yet\r\nnamespace ImGui { IMGUI_API void ShowFontAtlas(ImFontAtlas* atlas); }\r\n\r\n// Demo helper function to select among loaded fonts.\r\n// Here we use the regular BeginCombo()/EndCombo() api which is the more flexible one.\r\nvoid ImGui::ShowFontSelector(const char* label)\r\n{\r\n    ImGuiIO& io = ImGui::GetIO();\r\n    ImFont* font_current = ImGui::GetFont();\r\n    if (ImGui::BeginCombo(label, font_current->GetDebugName()))\r\n    {\r\n        for (int n = 0; n < io.Fonts->Fonts.Size; n++)\r\n        {\r\n            ImFont* font = io.Fonts->Fonts[n];\r\n            ImGui::PushID((void*)font);\r\n            if (ImGui::Selectable(font->GetDebugName(), font == font_current))\r\n                io.FontDefault = font;\r\n            ImGui::PopID();\r\n        }\r\n        ImGui::EndCombo();\r\n    }\r\n    ImGui::SameLine();\r\n    HelpMarker(\r\n        \"- Load additional fonts with io.Fonts->AddFontFromFileTTF().\\n\"\r\n        \"- The font atlas is built when calling io.Fonts->GetTexDataAsXXXX() or io.Fonts->Build().\\n\"\r\n        \"- Read FAQ and docs/FONTS.md for more details.\\n\"\r\n        \"- If you need to add/remove fonts at runtime (e.g. for DPI change), do it before calling NewFrame().\");\r\n}\r\n\r\n// Demo helper function to select among default colors. See ShowStyleEditor() for more advanced options.\r\n// Here we use the simplified Combo() api that packs items into a single literal string.\r\n// Useful for quick combo boxes where the choices are known locally.\r\nbool ImGui::ShowStyleSelector(const char* label)\r\n{\r\n    static int style_idx = -1;\r\n    if (ImGui::Combo(label, &style_idx, \"Dark\\0Light\\0Classic\\0\"))\r\n    {\r\n        switch (style_idx)\r\n        {\r\n        case 0: ImGui::StyleColorsDark(); break;\r\n        case 1: ImGui::StyleColorsLight(); break;\r\n        case 2: ImGui::StyleColorsClassic(); break;\r\n        }\r\n        return true;\r\n    }\r\n    return false;\r\n}\r\n\r\nvoid ImGui::ShowStyleEditor(ImGuiStyle* ref)\r\n{\r\n    IMGUI_DEMO_MARKER(\"Tools/Style Editor\");\r\n    // You can pass in a reference ImGuiStyle structure to compare to, revert to and save to\r\n    // (without a reference style pointer, we will use one compared locally as a reference)\r\n    ImGuiStyle& style = ImGui::GetStyle();\r\n    static ImGuiStyle ref_saved_style;\r\n\r\n    // Default to using internal storage as reference\r\n    static bool init = true;\r\n    if (init && ref == NULL)\r\n        ref_saved_style = style;\r\n    init = false;\r\n    if (ref == NULL)\r\n        ref = &ref_saved_style;\r\n\r\n    ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.50f);\r\n\r\n    if (ImGui::ShowStyleSelector(\"Colors##Selector\"))\r\n        ref_saved_style = style;\r\n    ImGui::ShowFontSelector(\"Fonts##Selector\");\r\n\r\n    // Simplified Settings (expose floating-pointer border sizes as boolean representing 0.0f or 1.0f)\r\n    if (ImGui::SliderFloat(\"FrameRounding\", &style.FrameRounding, 0.0f, 12.0f, \"%.0f\"))\r\n        style.GrabRounding = style.FrameRounding; // Make GrabRounding always the same value as FrameRounding\r\n    { bool border = (style.WindowBorderSize > 0.0f); if (ImGui::Checkbox(\"WindowBorder\", &border)) { style.WindowBorderSize = border ? 1.0f : 0.0f; } }\r\n    ImGui::SameLine();\r\n    { bool border = (style.FrameBorderSize > 0.0f);  if (ImGui::Checkbox(\"FrameBorder\",  &border)) { style.FrameBorderSize  = border ? 1.0f : 0.0f; } }\r\n    ImGui::SameLine();\r\n    { bool border = (style.PopupBorderSize > 0.0f);  if (ImGui::Checkbox(\"PopupBorder\",  &border)) { style.PopupBorderSize  = border ? 1.0f : 0.0f; } }\r\n\r\n    // Save/Revert button\r\n    if (ImGui::Button(\"Save Ref\"))\r\n        *ref = ref_saved_style = style;\r\n    ImGui::SameLine();\r\n    if (ImGui::Button(\"Revert Ref\"))\r\n        style = *ref;\r\n    ImGui::SameLine();\r\n    HelpMarker(\r\n        \"Save/Revert in local non-persistent storage. Default Colors definition are not affected. \"\r\n        \"Use \\\"Export\\\" below to save them somewhere.\");\r\n\r\n    ImGui::Separator();\r\n\r\n    if (ImGui::BeginTabBar(\"##tabs\", ImGuiTabBarFlags_None))\r\n    {\r\n        if (ImGui::BeginTabItem(\"Sizes\"))\r\n        {\r\n            ImGui::Text(\"Main\");\r\n            ImGui::SliderFloat2(\"WindowPadding\", (float*)&style.WindowPadding, 0.0f, 20.0f, \"%.0f\");\r\n            ImGui::SliderFloat2(\"FramePadding\", (float*)&style.FramePadding, 0.0f, 20.0f, \"%.0f\");\r\n            ImGui::SliderFloat2(\"CellPadding\", (float*)&style.CellPadding, 0.0f, 20.0f, \"%.0f\");\r\n            ImGui::SliderFloat2(\"ItemSpacing\", (float*)&style.ItemSpacing, 0.0f, 20.0f, \"%.0f\");\r\n            ImGui::SliderFloat2(\"ItemInnerSpacing\", (float*)&style.ItemInnerSpacing, 0.0f, 20.0f, \"%.0f\");\r\n            ImGui::SliderFloat2(\"TouchExtraPadding\", (float*)&style.TouchExtraPadding, 0.0f, 10.0f, \"%.0f\");\r\n            ImGui::SliderFloat(\"IndentSpacing\", &style.IndentSpacing, 0.0f, 30.0f, \"%.0f\");\r\n            ImGui::SliderFloat(\"ScrollbarSize\", &style.ScrollbarSize, 1.0f, 20.0f, \"%.0f\");\r\n            ImGui::SliderFloat(\"GrabMinSize\", &style.GrabMinSize, 1.0f, 20.0f, \"%.0f\");\r\n            ImGui::Text(\"Borders\");\r\n            ImGui::SliderFloat(\"WindowBorderSize\", &style.WindowBorderSize, 0.0f, 1.0f, \"%.0f\");\r\n            ImGui::SliderFloat(\"ChildBorderSize\", &style.ChildBorderSize, 0.0f, 1.0f, \"%.0f\");\r\n            ImGui::SliderFloat(\"PopupBorderSize\", &style.PopupBorderSize, 0.0f, 1.0f, \"%.0f\");\r\n            ImGui::SliderFloat(\"FrameBorderSize\", &style.FrameBorderSize, 0.0f, 1.0f, \"%.0f\");\r\n            ImGui::SliderFloat(\"TabBorderSize\", &style.TabBorderSize, 0.0f, 1.0f, \"%.0f\");\r\n            ImGui::Text(\"Rounding\");\r\n            ImGui::SliderFloat(\"WindowRounding\", &style.WindowRounding, 0.0f, 12.0f, \"%.0f\");\r\n            ImGui::SliderFloat(\"ChildRounding\", &style.ChildRounding, 0.0f, 12.0f, \"%.0f\");\r\n            ImGui::SliderFloat(\"FrameRounding\", &style.FrameRounding, 0.0f, 12.0f, \"%.0f\");\r\n            ImGui::SliderFloat(\"PopupRounding\", &style.PopupRounding, 0.0f, 12.0f, \"%.0f\");\r\n            ImGui::SliderFloat(\"ScrollbarRounding\", &style.ScrollbarRounding, 0.0f, 12.0f, \"%.0f\");\r\n            ImGui::SliderFloat(\"GrabRounding\", &style.GrabRounding, 0.0f, 12.0f, \"%.0f\");\r\n            ImGui::SliderFloat(\"LogSliderDeadzone\", &style.LogSliderDeadzone, 0.0f, 12.0f, \"%.0f\");\r\n            ImGui::SliderFloat(\"TabRounding\", &style.TabRounding, 0.0f, 12.0f, \"%.0f\");\r\n            ImGui::Text(\"Alignment\");\r\n            ImGui::SliderFloat2(\"WindowTitleAlign\", (float*)&style.WindowTitleAlign, 0.0f, 1.0f, \"%.2f\");\r\n            int window_menu_button_position = style.WindowMenuButtonPosition + 1;\r\n            if (ImGui::Combo(\"WindowMenuButtonPosition\", (int*)&window_menu_button_position, \"None\\0Left\\0Right\\0\"))\r\n                style.WindowMenuButtonPosition = window_menu_button_position - 1;\r\n            ImGui::Combo(\"ColorButtonPosition\", (int*)&style.ColorButtonPosition, \"Left\\0Right\\0\");\r\n            ImGui::SliderFloat2(\"ButtonTextAlign\", (float*)&style.ButtonTextAlign, 0.0f, 1.0f, \"%.2f\");\r\n            ImGui::SameLine(); HelpMarker(\"Alignment applies when a button is larger than its text content.\");\r\n            ImGui::SliderFloat2(\"SelectableTextAlign\", (float*)&style.SelectableTextAlign, 0.0f, 1.0f, \"%.2f\");\r\n            ImGui::SameLine(); HelpMarker(\"Alignment applies when a selectable is larger than its text content.\");\r\n            ImGui::Text(\"Safe Area Padding\");\r\n            ImGui::SameLine(); HelpMarker(\"Adjust if you cannot see the edges of your screen (e.g. on a TV where scaling has not been configured).\");\r\n            ImGui::SliderFloat2(\"DisplaySafeAreaPadding\", (float*)&style.DisplaySafeAreaPadding, 0.0f, 30.0f, \"%.0f\");\r\n            ImGui::EndTabItem();\r\n        }\r\n\r\n        if (ImGui::BeginTabItem(\"Colors\"))\r\n        {\r\n            static int output_dest = 0;\r\n            static bool output_only_modified = true;\r\n            if (ImGui::Button(\"Export\"))\r\n            {\r\n                if (output_dest == 0)\r\n                    ImGui::LogToClipboard();\r\n                else\r\n                    ImGui::LogToTTY();\r\n                ImGui::LogText(\"ImVec4* colors = ImGui::GetStyle().Colors;\" IM_NEWLINE);\r\n                for (int i = 0; i < ImGuiCol_COUNT; i++)\r\n                {\r\n                    const ImVec4& col = style.Colors[i];\r\n                    const char* name = ImGui::GetStyleColorName(i);\r\n                    if (!output_only_modified || memcmp(&col, &ref->Colors[i], sizeof(ImVec4)) != 0)\r\n                        ImGui::LogText(\"colors[ImGuiCol_%s]%*s= ImVec4(%.2ff, %.2ff, %.2ff, %.2ff);\" IM_NEWLINE,\r\n                            name, 23 - (int)strlen(name), \"\", col.x, col.y, col.z, col.w);\r\n                }\r\n                ImGui::LogFinish();\r\n            }\r\n            ImGui::SameLine(); ImGui::SetNextItemWidth(120); ImGui::Combo(\"##output_type\", &output_dest, \"To Clipboard\\0To TTY\\0\");\r\n            ImGui::SameLine(); ImGui::Checkbox(\"Only Modified Colors\", &output_only_modified);\r\n\r\n            static ImGuiTextFilter filter;\r\n            filter.Draw(\"Filter colors\", ImGui::GetFontSize() * 16);\r\n\r\n            static ImGuiColorEditFlags alpha_flags = 0;\r\n            if (ImGui::RadioButton(\"Opaque\", alpha_flags == ImGuiColorEditFlags_None))             { alpha_flags = ImGuiColorEditFlags_None; } ImGui::SameLine();\r\n            if (ImGui::RadioButton(\"Alpha\",  alpha_flags == ImGuiColorEditFlags_AlphaPreview))     { alpha_flags = ImGuiColorEditFlags_AlphaPreview; } ImGui::SameLine();\r\n            if (ImGui::RadioButton(\"Both\",   alpha_flags == ImGuiColorEditFlags_AlphaPreviewHalf)) { alpha_flags = ImGuiColorEditFlags_AlphaPreviewHalf; } ImGui::SameLine();\r\n            HelpMarker(\r\n                \"In the color list:\\n\"\r\n                \"Left-click on color square to open color picker,\\n\"\r\n                \"Right-click to open edit options menu.\");\r\n\r\n            ImGui::BeginChild(\"##colors\", ImVec2(0, 0), true, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar | ImGuiWindowFlags_NavFlattened);\r\n            ImGui::PushItemWidth(-160);\r\n            for (int i = 0; i < ImGuiCol_COUNT; i++)\r\n            {\r\n                const char* name = ImGui::GetStyleColorName(i);\r\n                if (!filter.PassFilter(name))\r\n                    continue;\r\n                ImGui::PushID(i);\r\n                ImGui::ColorEdit4(\"##color\", (float*)&style.Colors[i], ImGuiColorEditFlags_AlphaBar | alpha_flags);\r\n                if (memcmp(&style.Colors[i], &ref->Colors[i], sizeof(ImVec4)) != 0)\r\n                {\r\n                    // Tips: in a real user application, you may want to merge and use an icon font into the main font,\r\n                    // so instead of \"Save\"/\"Revert\" you'd use icons!\r\n                    // Read the FAQ and docs/FONTS.md about using icon fonts. It's really easy and super convenient!\r\n                    ImGui::SameLine(0.0f, style.ItemInnerSpacing.x); if (ImGui::Button(\"Save\")) { ref->Colors[i] = style.Colors[i]; }\r\n                    ImGui::SameLine(0.0f, style.ItemInnerSpacing.x); if (ImGui::Button(\"Revert\")) { style.Colors[i] = ref->Colors[i]; }\r\n                }\r\n                ImGui::SameLine(0.0f, style.ItemInnerSpacing.x);\r\n                ImGui::TextUnformatted(name);\r\n                ImGui::PopID();\r\n            }\r\n            ImGui::PopItemWidth();\r\n            ImGui::EndChild();\r\n\r\n            ImGui::EndTabItem();\r\n        }\r\n\r\n        if (ImGui::BeginTabItem(\"Fonts\"))\r\n        {\r\n            ImGuiIO& io = ImGui::GetIO();\r\n            ImFontAtlas* atlas = io.Fonts;\r\n            HelpMarker(\"Read FAQ and docs/FONTS.md for details on font loading.\");\r\n            ImGui::ShowFontAtlas(atlas);\r\n\r\n            // Post-baking font scaling. Note that this is NOT the nice way of scaling fonts, read below.\r\n            // (we enforce hard clamping manually as by default DragFloat/SliderFloat allows CTRL+Click text to get out of bounds).\r\n            const float MIN_SCALE = 0.3f;\r\n            const float MAX_SCALE = 2.0f;\r\n            HelpMarker(\r\n                \"Those are old settings provided for convenience.\\n\"\r\n                \"However, the _correct_ way of scaling your UI is currently to reload your font at the designed size, \"\r\n                \"rebuild the font atlas, and call style.ScaleAllSizes() on a reference ImGuiStyle structure.\\n\"\r\n                \"Using those settings here will give you poor quality results.\");\r\n            static float window_scale = 1.0f;\r\n            ImGui::PushItemWidth(ImGui::GetFontSize() * 8);\r\n            if (ImGui::DragFloat(\"window scale\", &window_scale, 0.005f, MIN_SCALE, MAX_SCALE, \"%.2f\", ImGuiSliderFlags_AlwaysClamp)) // Scale only this window\r\n                ImGui::SetWindowFontScale(window_scale);\r\n            ImGui::DragFloat(\"global scale\", &io.FontGlobalScale, 0.005f, MIN_SCALE, MAX_SCALE, \"%.2f\", ImGuiSliderFlags_AlwaysClamp); // Scale everything\r\n            ImGui::PopItemWidth();\r\n\r\n            ImGui::EndTabItem();\r\n        }\r\n\r\n        if (ImGui::BeginTabItem(\"Rendering\"))\r\n        {\r\n            ImGui::Checkbox(\"Anti-aliased lines\", &style.AntiAliasedLines);\r\n            ImGui::SameLine();\r\n            HelpMarker(\"When disabling anti-aliasing lines, you'll probably want to disable borders in your style as well.\");\r\n\r\n            ImGui::Checkbox(\"Anti-aliased lines use texture\", &style.AntiAliasedLinesUseTex);\r\n            ImGui::SameLine();\r\n            HelpMarker(\"Faster lines using texture data. Require backend to render with bilinear filtering (not point/nearest filtering).\");\r\n\r\n            ImGui::Checkbox(\"Anti-aliased fill\", &style.AntiAliasedFill);\r\n            ImGui::PushItemWidth(ImGui::GetFontSize() * 8);\r\n            ImGui::DragFloat(\"Curve Tessellation Tolerance\", &style.CurveTessellationTol, 0.02f, 0.10f, 10.0f, \"%.2f\");\r\n            if (style.CurveTessellationTol < 0.10f) style.CurveTessellationTol = 0.10f;\r\n\r\n            // When editing the \"Circle Segment Max Error\" value, draw a preview of its effect on auto-tessellated circles.\r\n            ImGui::DragFloat(\"Circle Tessellation Max Error\", &style.CircleTessellationMaxError , 0.005f, 0.10f, 5.0f, \"%.2f\", ImGuiSliderFlags_AlwaysClamp);\r\n            if (ImGui::IsItemActive())\r\n            {\r\n                ImGui::SetNextWindowPos(ImGui::GetCursorScreenPos());\r\n                ImGui::BeginTooltip();\r\n                ImGui::TextUnformatted(\"(R = radius, N = number of segments)\");\r\n                ImGui::Spacing();\r\n                ImDrawList* draw_list = ImGui::GetWindowDrawList();\r\n                const float min_widget_width = ImGui::CalcTextSize(\"N: MMM\\nR: MMM\").x;\r\n                for (int n = 0; n < 8; n++)\r\n                {\r\n                    const float RAD_MIN = 5.0f;\r\n                    const float RAD_MAX = 70.0f;\r\n                    const float rad = RAD_MIN + (RAD_MAX - RAD_MIN) * (float)n / (8.0f - 1.0f);\r\n\r\n                    ImGui::BeginGroup();\r\n\r\n                    ImGui::Text(\"R: %.f\\nN: %d\", rad, draw_list->_CalcCircleAutoSegmentCount(rad));\r\n\r\n                    const float canvas_width = IM_MAX(min_widget_width, rad * 2.0f);\r\n                    const float offset_x     = floorf(canvas_width * 0.5f);\r\n                    const float offset_y     = floorf(RAD_MAX);\r\n\r\n                    const ImVec2 p1 = ImGui::GetCursorScreenPos();\r\n                    draw_list->AddCircle(ImVec2(p1.x + offset_x, p1.y + offset_y), rad, ImGui::GetColorU32(ImGuiCol_Text));\r\n                    ImGui::Dummy(ImVec2(canvas_width, RAD_MAX * 2));\r\n\r\n                    /*\r\n                    const ImVec2 p2 = ImGui::GetCursorScreenPos();\r\n                    draw_list->AddCircleFilled(ImVec2(p2.x + offset_x, p2.y + offset_y), rad, ImGui::GetColorU32(ImGuiCol_Text));\r\n                    ImGui::Dummy(ImVec2(canvas_width, RAD_MAX * 2));\r\n                    */\r\n\r\n                    ImGui::EndGroup();\r\n                    ImGui::SameLine();\r\n                }\r\n                ImGui::EndTooltip();\r\n            }\r\n            ImGui::SameLine();\r\n            HelpMarker(\"When drawing circle primitives with \\\"num_segments == 0\\\" tesselation will be calculated automatically.\");\r\n\r\n            ImGui::DragFloat(\"Global Alpha\", &style.Alpha, 0.005f, 0.20f, 1.0f, \"%.2f\"); // Not exposing zero here so user doesn't \"lose\" the UI (zero alpha clips all widgets). But application code could have a toggle to switch between zero and non-zero.\r\n            ImGui::DragFloat(\"Disabled Alpha\", &style.DisabledAlpha, 0.005f, 0.0f, 1.0f, \"%.2f\"); ImGui::SameLine(); HelpMarker(\"Additional alpha multiplier for disabled items (multiply over current value of Alpha).\");\r\n            ImGui::PopItemWidth();\r\n\r\n            ImGui::EndTabItem();\r\n        }\r\n\r\n        ImGui::EndTabBar();\r\n    }\r\n\r\n    ImGui::PopItemWidth();\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Example App: Main Menu Bar / ShowExampleAppMainMenuBar()\r\n//-----------------------------------------------------------------------------\r\n// - ShowExampleAppMainMenuBar()\r\n// - ShowExampleMenuFile()\r\n//-----------------------------------------------------------------------------\r\n\r\n// Demonstrate creating a \"main\" fullscreen menu bar and populating it.\r\n// Note the difference between BeginMainMenuBar() and BeginMenuBar():\r\n// - BeginMenuBar() = menu-bar inside current window (which needs the ImGuiWindowFlags_MenuBar flag!)\r\n// - BeginMainMenuBar() = helper to create menu-bar-sized window at the top of the main viewport + call BeginMenuBar() into it.\r\nstatic void ShowExampleAppMainMenuBar()\r\n{\r\n    if (ImGui::BeginMainMenuBar())\r\n    {\r\n        if (ImGui::BeginMenu(\"File\"))\r\n        {\r\n            ShowExampleMenuFile();\r\n            ImGui::EndMenu();\r\n        }\r\n        if (ImGui::BeginMenu(\"Edit\"))\r\n        {\r\n            if (ImGui::MenuItem(\"Undo\", \"CTRL+Z\")) {}\r\n            if (ImGui::MenuItem(\"Redo\", \"CTRL+Y\", false, false)) {}  // Disabled item\r\n            ImGui::Separator();\r\n            if (ImGui::MenuItem(\"Cut\", \"CTRL+X\")) {}\r\n            if (ImGui::MenuItem(\"Copy\", \"CTRL+C\")) {}\r\n            if (ImGui::MenuItem(\"Paste\", \"CTRL+V\")) {}\r\n            ImGui::EndMenu();\r\n        }\r\n        ImGui::EndMainMenuBar();\r\n    }\r\n}\r\n\r\n// Note that shortcuts are currently provided for display only\r\n// (future version will add explicit flags to BeginMenu() to request processing shortcuts)\r\nstatic void ShowExampleMenuFile()\r\n{\r\n    IMGUI_DEMO_MARKER(\"Examples/Menu\");\r\n    ImGui::MenuItem(\"(demo menu)\", NULL, false, false);\r\n    if (ImGui::MenuItem(\"New\")) {}\r\n    if (ImGui::MenuItem(\"Open\", \"Ctrl+O\")) {}\r\n    if (ImGui::BeginMenu(\"Open Recent\"))\r\n    {\r\n        ImGui::MenuItem(\"fish_hat.c\");\r\n        ImGui::MenuItem(\"fish_hat.inl\");\r\n        ImGui::MenuItem(\"fish_hat.h\");\r\n        if (ImGui::BeginMenu(\"More..\"))\r\n        {\r\n            ImGui::MenuItem(\"Hello\");\r\n            ImGui::MenuItem(\"Sailor\");\r\n            if (ImGui::BeginMenu(\"Recurse..\"))\r\n            {\r\n                ShowExampleMenuFile();\r\n                ImGui::EndMenu();\r\n            }\r\n            ImGui::EndMenu();\r\n        }\r\n        ImGui::EndMenu();\r\n    }\r\n    if (ImGui::MenuItem(\"Save\", \"Ctrl+S\")) {}\r\n    if (ImGui::MenuItem(\"Save As..\")) {}\r\n\r\n    ImGui::Separator();\r\n    IMGUI_DEMO_MARKER(\"Examples/Menu/Options\");\r\n    if (ImGui::BeginMenu(\"Options\"))\r\n    {\r\n        static bool enabled = true;\r\n        ImGui::MenuItem(\"Enabled\", \"\", &enabled);\r\n        ImGui::BeginChild(\"child\", ImVec2(0, 60), true);\r\n        for (int i = 0; i < 10; i++)\r\n            ImGui::Text(\"Scrolling Text %d\", i);\r\n        ImGui::EndChild();\r\n        static float f = 0.5f;\r\n        static int n = 0;\r\n        ImGui::SliderFloat(\"Value\", &f, 0.0f, 1.0f);\r\n        ImGui::InputFloat(\"Input\", &f, 0.1f);\r\n        ImGui::Combo(\"Combo\", &n, \"Yes\\0No\\0Maybe\\0\\0\");\r\n        ImGui::EndMenu();\r\n    }\r\n\r\n    IMGUI_DEMO_MARKER(\"Examples/Menu/Colors\");\r\n    if (ImGui::BeginMenu(\"Colors\"))\r\n    {\r\n        float sz = ImGui::GetTextLineHeight();\r\n        for (int i = 0; i < ImGuiCol_COUNT; i++)\r\n        {\r\n            const char* name = ImGui::GetStyleColorName((ImGuiCol)i);\r\n            ImVec2 p = ImGui::GetCursorScreenPos();\r\n            ImGui::GetWindowDrawList()->AddRectFilled(p, ImVec2(p.x + sz, p.y + sz), ImGui::GetColorU32((ImGuiCol)i));\r\n            ImGui::Dummy(ImVec2(sz, sz));\r\n            ImGui::SameLine();\r\n            ImGui::MenuItem(name);\r\n        }\r\n        ImGui::EndMenu();\r\n    }\r\n\r\n    // Here we demonstrate appending again to the \"Options\" menu (which we already created above)\r\n    // Of course in this demo it is a little bit silly that this function calls BeginMenu(\"Options\") twice.\r\n    // In a real code-base using it would make senses to use this feature from very different code locations.\r\n    if (ImGui::BeginMenu(\"Options\")) // <-- Append!\r\n    {\r\n        IMGUI_DEMO_MARKER(\"Examples/Menu/Append to an existing menu\");\r\n        static bool b = true;\r\n        ImGui::Checkbox(\"SomeOption\", &b);\r\n        ImGui::EndMenu();\r\n    }\r\n\r\n    if (ImGui::BeginMenu(\"Disabled\", false)) // Disabled\r\n    {\r\n        IM_ASSERT(0);\r\n    }\r\n    if (ImGui::MenuItem(\"Checked\", NULL, true)) {}\r\n    if (ImGui::MenuItem(\"Quit\", \"Alt+F4\")) {}\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Example App: Debug Console / ShowExampleAppConsole()\r\n//-----------------------------------------------------------------------------\r\n\r\n// Demonstrate creating a simple console window, with scrolling, filtering, completion and history.\r\n// For the console example, we are using a more C++ like approach of declaring a class to hold both data and functions.\r\nstruct ExampleAppConsole\r\n{\r\n    char                  InputBuf[256];\r\n    ImVector<char*>       Items;\r\n    ImVector<const char*> Commands;\r\n    ImVector<char*>       History;\r\n    int                   HistoryPos;    // -1: new line, 0..History.Size-1 browsing history.\r\n    ImGuiTextFilter       Filter;\r\n    bool                  AutoScroll;\r\n    bool                  ScrollToBottom;\r\n\r\n    ExampleAppConsole()\r\n    {\r\n        IMGUI_DEMO_MARKER(\"Examples/Console\");\r\n        ClearLog();\r\n        memset(InputBuf, 0, sizeof(InputBuf));\r\n        HistoryPos = -1;\r\n\r\n        // \"CLASSIFY\" is here to provide the test case where \"C\"+[tab] completes to \"CL\" and display multiple matches.\r\n        Commands.push_back(\"HELP\");\r\n        Commands.push_back(\"HISTORY\");\r\n        Commands.push_back(\"CLEAR\");\r\n        Commands.push_back(\"CLASSIFY\");\r\n        AutoScroll = true;\r\n        ScrollToBottom = false;\r\n        AddLog(\"Welcome to Dear ImGui!\");\r\n    }\r\n    ~ExampleAppConsole()\r\n    {\r\n        ClearLog();\r\n        for (int i = 0; i < History.Size; i++)\r\n            free(History[i]);\r\n    }\r\n\r\n    // Portable helpers\r\n    static int   Stricmp(const char* s1, const char* s2)         { int d; while ((d = toupper(*s2) - toupper(*s1)) == 0 && *s1) { s1++; s2++; } return d; }\r\n    static int   Strnicmp(const char* s1, const char* s2, int n) { int d = 0; while (n > 0 && (d = toupper(*s2) - toupper(*s1)) == 0 && *s1) { s1++; s2++; n--; } return d; }\r\n    static char* Strdup(const char* s)                           { IM_ASSERT(s); size_t len = strlen(s) + 1; void* buf = malloc(len); IM_ASSERT(buf); return (char*)memcpy(buf, (const void*)s, len); }\r\n    static void  Strtrim(char* s)                                { char* str_end = s + strlen(s); while (str_end > s && str_end[-1] == ' ') str_end--; *str_end = 0; }\r\n\r\n    void    ClearLog()\r\n    {\r\n        for (int i = 0; i < Items.Size; i++)\r\n            free(Items[i]);\r\n        Items.clear();\r\n    }\r\n\r\n    void    AddLog(const char* fmt, ...) IM_FMTARGS(2)\r\n    {\r\n        // FIXME-OPT\r\n        char buf[1024];\r\n        va_list args;\r\n        va_start(args, fmt);\r\n        vsnprintf(buf, IM_ARRAYSIZE(buf), fmt, args);\r\n        buf[IM_ARRAYSIZE(buf)-1] = 0;\r\n        va_end(args);\r\n        Items.push_back(Strdup(buf));\r\n    }\r\n\r\n    void    Draw(const char* title, bool* p_open)\r\n    {\r\n        ImGui::SetNextWindowSize(ImVec2(520, 600), ImGuiCond_FirstUseEver);\r\n        if (!ImGui::Begin(title, p_open))\r\n        {\r\n            ImGui::End();\r\n            return;\r\n        }\r\n\r\n        // As a specific feature guaranteed by the library, after calling Begin() the last Item represent the title bar.\r\n        // So e.g. IsItemHovered() will return true when hovering the title bar.\r\n        // Here we create a context menu only available from the title bar.\r\n        if (ImGui::BeginPopupContextItem())\r\n        {\r\n            if (ImGui::MenuItem(\"Close Console\"))\r\n                *p_open = false;\r\n            ImGui::EndPopup();\r\n        }\r\n\r\n        ImGui::TextWrapped(\r\n            \"This example implements a console with basic coloring, completion (TAB key) and history (Up/Down keys). A more elaborate \"\r\n            \"implementation may want to store entries along with extra data such as timestamp, emitter, etc.\");\r\n        ImGui::TextWrapped(\"Enter 'HELP' for help.\");\r\n\r\n        // TODO: display items starting from the bottom\r\n\r\n        if (ImGui::SmallButton(\"Add Debug Text\"))  { AddLog(\"%d some text\", Items.Size); AddLog(\"some more text\"); AddLog(\"display very important message here!\"); }\r\n        ImGui::SameLine();\r\n        if (ImGui::SmallButton(\"Add Debug Error\")) { AddLog(\"[error] something went wrong\"); }\r\n        ImGui::SameLine();\r\n        if (ImGui::SmallButton(\"Clear\"))           { ClearLog(); }\r\n        ImGui::SameLine();\r\n        bool copy_to_clipboard = ImGui::SmallButton(\"Copy\");\r\n        //static float t = 0.0f; if (ImGui::GetTime() - t > 0.02f) { t = ImGui::GetTime(); AddLog(\"Spam %f\", t); }\r\n\r\n        ImGui::Separator();\r\n\r\n        // Options menu\r\n        if (ImGui::BeginPopup(\"Options\"))\r\n        {\r\n            ImGui::Checkbox(\"Auto-scroll\", &AutoScroll);\r\n            ImGui::EndPopup();\r\n        }\r\n\r\n        // Options, Filter\r\n        if (ImGui::Button(\"Options\"))\r\n            ImGui::OpenPopup(\"Options\");\r\n        ImGui::SameLine();\r\n        Filter.Draw(\"Filter (\\\"incl,-excl\\\") (\\\"error\\\")\", 180);\r\n        ImGui::Separator();\r\n\r\n        // Reserve enough left-over height for 1 separator + 1 input text\r\n        const float footer_height_to_reserve = ImGui::GetStyle().ItemSpacing.y + ImGui::GetFrameHeightWithSpacing();\r\n        ImGui::BeginChild(\"ScrollingRegion\", ImVec2(0, -footer_height_to_reserve), false, ImGuiWindowFlags_HorizontalScrollbar);\r\n        if (ImGui::BeginPopupContextWindow())\r\n        {\r\n            if (ImGui::Selectable(\"Clear\")) ClearLog();\r\n            ImGui::EndPopup();\r\n        }\r\n\r\n        // Display every line as a separate entry so we can change their color or add custom widgets.\r\n        // If you only want raw text you can use ImGui::TextUnformatted(log.begin(), log.end());\r\n        // NB- if you have thousands of entries this approach may be too inefficient and may require user-side clipping\r\n        // to only process visible items. The clipper will automatically measure the height of your first item and then\r\n        // \"seek\" to display only items in the visible area.\r\n        // To use the clipper we can replace your standard loop:\r\n        //      for (int i = 0; i < Items.Size; i++)\r\n        //   With:\r\n        //      ImGuiListClipper clipper;\r\n        //      clipper.Begin(Items.Size);\r\n        //      while (clipper.Step())\r\n        //         for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)\r\n        // - That your items are evenly spaced (same height)\r\n        // - That you have cheap random access to your elements (you can access them given their index,\r\n        //   without processing all the ones before)\r\n        // You cannot this code as-is if a filter is active because it breaks the 'cheap random-access' property.\r\n        // We would need random-access on the post-filtered list.\r\n        // A typical application wanting coarse clipping and filtering may want to pre-compute an array of indices\r\n        // or offsets of items that passed the filtering test, recomputing this array when user changes the filter,\r\n        // and appending newly elements as they are inserted. This is left as a task to the user until we can manage\r\n        // to improve this example code!\r\n        // If your items are of variable height:\r\n        // - Split them into same height items would be simpler and facilitate random-seeking into your list.\r\n        // - Consider using manual call to IsRectVisible() and skipping extraneous decoration from your items.\r\n        ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4, 1)); // Tighten spacing\r\n        if (copy_to_clipboard)\r\n            ImGui::LogToClipboard();\r\n        for (int i = 0; i < Items.Size; i++)\r\n        {\r\n            const char* item = Items[i];\r\n            if (!Filter.PassFilter(item))\r\n                continue;\r\n\r\n            // Normally you would store more information in your item than just a string.\r\n            // (e.g. make Items[] an array of structure, store color/type etc.)\r\n            ImVec4 color;\r\n            bool has_color = false;\r\n            if (strstr(item, \"[error]\"))          { color = ImVec4(1.0f, 0.4f, 0.4f, 1.0f); has_color = true; }\r\n            else if (strncmp(item, \"# \", 2) == 0) { color = ImVec4(1.0f, 0.8f, 0.6f, 1.0f); has_color = true; }\r\n            if (has_color)\r\n                ImGui::PushStyleColor(ImGuiCol_Text, color);\r\n            ImGui::TextUnformatted(item);\r\n            if (has_color)\r\n                ImGui::PopStyleColor();\r\n        }\r\n        if (copy_to_clipboard)\r\n            ImGui::LogFinish();\r\n\r\n        if (ScrollToBottom || (AutoScroll && ImGui::GetScrollY() >= ImGui::GetScrollMaxY()))\r\n            ImGui::SetScrollHereY(1.0f);\r\n        ScrollToBottom = false;\r\n\r\n        ImGui::PopStyleVar();\r\n        ImGui::EndChild();\r\n        ImGui::Separator();\r\n\r\n        // Command-line\r\n        bool reclaim_focus = false;\r\n        ImGuiInputTextFlags input_text_flags = ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory;\r\n        if (ImGui::InputText(\"Input\", InputBuf, IM_ARRAYSIZE(InputBuf), input_text_flags, &TextEditCallbackStub, (void*)this))\r\n        {\r\n            char* s = InputBuf;\r\n            Strtrim(s);\r\n            if (s[0])\r\n                ExecCommand(s);\r\n            strcpy(s, \"\");\r\n            reclaim_focus = true;\r\n        }\r\n\r\n        // Auto-focus on window apparition\r\n        ImGui::SetItemDefaultFocus();\r\n        if (reclaim_focus)\r\n            ImGui::SetKeyboardFocusHere(-1); // Auto focus previous widget\r\n\r\n        ImGui::End();\r\n    }\r\n\r\n    void    ExecCommand(const char* command_line)\r\n    {\r\n        AddLog(\"# %s\\n\", command_line);\r\n\r\n        // Insert into history. First find match and delete it so it can be pushed to the back.\r\n        // This isn't trying to be smart or optimal.\r\n        HistoryPos = -1;\r\n        for (int i = History.Size - 1; i >= 0; i--)\r\n            if (Stricmp(History[i], command_line) == 0)\r\n            {\r\n                free(History[i]);\r\n                History.erase(History.begin() + i);\r\n                break;\r\n            }\r\n        History.push_back(Strdup(command_line));\r\n\r\n        // Process command\r\n        if (Stricmp(command_line, \"CLEAR\") == 0)\r\n        {\r\n            ClearLog();\r\n        }\r\n        else if (Stricmp(command_line, \"HELP\") == 0)\r\n        {\r\n            AddLog(\"Commands:\");\r\n            for (int i = 0; i < Commands.Size; i++)\r\n                AddLog(\"- %s\", Commands[i]);\r\n        }\r\n        else if (Stricmp(command_line, \"HISTORY\") == 0)\r\n        {\r\n            int first = History.Size - 10;\r\n            for (int i = first > 0 ? first : 0; i < History.Size; i++)\r\n                AddLog(\"%3d: %s\\n\", i, History[i]);\r\n        }\r\n        else\r\n        {\r\n            AddLog(\"Unknown command: '%s'\\n\", command_line);\r\n        }\r\n\r\n        // On command input, we scroll to bottom even if AutoScroll==false\r\n        ScrollToBottom = true;\r\n    }\r\n\r\n    // In C++11 you'd be better off using lambdas for this sort of forwarding callbacks\r\n    static int TextEditCallbackStub(ImGuiInputTextCallbackData* data)\r\n    {\r\n        ExampleAppConsole* console = (ExampleAppConsole*)data->UserData;\r\n        return console->TextEditCallback(data);\r\n    }\r\n\r\n    int     TextEditCallback(ImGuiInputTextCallbackData* data)\r\n    {\r\n        //AddLog(\"cursor: %d, selection: %d-%d\", data->CursorPos, data->SelectionStart, data->SelectionEnd);\r\n        switch (data->EventFlag)\r\n        {\r\n        case ImGuiInputTextFlags_CallbackCompletion:\r\n            {\r\n                // Example of TEXT COMPLETION\r\n\r\n                // Locate beginning of current word\r\n                const char* word_end = data->Buf + data->CursorPos;\r\n                const char* word_start = word_end;\r\n                while (word_start > data->Buf)\r\n                {\r\n                    const char c = word_start[-1];\r\n                    if (c == ' ' || c == '\\t' || c == ',' || c == ';')\r\n                        break;\r\n                    word_start--;\r\n                }\r\n\r\n                // Build a list of candidates\r\n                ImVector<const char*> candidates;\r\n                for (int i = 0; i < Commands.Size; i++)\r\n                    if (Strnicmp(Commands[i], word_start, (int)(word_end - word_start)) == 0)\r\n                        candidates.push_back(Commands[i]);\r\n\r\n                if (candidates.Size == 0)\r\n                {\r\n                    // No match\r\n                    AddLog(\"No match for \\\"%.*s\\\"!\\n\", (int)(word_end - word_start), word_start);\r\n                }\r\n                else if (candidates.Size == 1)\r\n                {\r\n                    // Single match. Delete the beginning of the word and replace it entirely so we've got nice casing.\r\n                    data->DeleteChars((int)(word_start - data->Buf), (int)(word_end - word_start));\r\n                    data->InsertChars(data->CursorPos, candidates[0]);\r\n                    data->InsertChars(data->CursorPos, \" \");\r\n                }\r\n                else\r\n                {\r\n                    // Multiple matches. Complete as much as we can..\r\n                    // So inputing \"C\"+Tab will complete to \"CL\" then display \"CLEAR\" and \"CLASSIFY\" as matches.\r\n                    int match_len = (int)(word_end - word_start);\r\n                    for (;;)\r\n                    {\r\n                        int c = 0;\r\n                        bool all_candidates_matches = true;\r\n                        for (int i = 0; i < candidates.Size && all_candidates_matches; i++)\r\n                            if (i == 0)\r\n                                c = toupper(candidates[i][match_len]);\r\n                            else if (c == 0 || c != toupper(candidates[i][match_len]))\r\n                                all_candidates_matches = false;\r\n                        if (!all_candidates_matches)\r\n                            break;\r\n                        match_len++;\r\n                    }\r\n\r\n                    if (match_len > 0)\r\n                    {\r\n                        data->DeleteChars((int)(word_start - data->Buf), (int)(word_end - word_start));\r\n                        data->InsertChars(data->CursorPos, candidates[0], candidates[0] + match_len);\r\n                    }\r\n\r\n                    // List matches\r\n                    AddLog(\"Possible matches:\\n\");\r\n                    for (int i = 0; i < candidates.Size; i++)\r\n                        AddLog(\"- %s\\n\", candidates[i]);\r\n                }\r\n\r\n                break;\r\n            }\r\n        case ImGuiInputTextFlags_CallbackHistory:\r\n            {\r\n                // Example of HISTORY\r\n                const int prev_history_pos = HistoryPos;\r\n                if (data->EventKey == ImGuiKey_UpArrow)\r\n                {\r\n                    if (HistoryPos == -1)\r\n                        HistoryPos = History.Size - 1;\r\n                    else if (HistoryPos > 0)\r\n                        HistoryPos--;\r\n                }\r\n                else if (data->EventKey == ImGuiKey_DownArrow)\r\n                {\r\n                    if (HistoryPos != -1)\r\n                        if (++HistoryPos >= History.Size)\r\n                            HistoryPos = -1;\r\n                }\r\n\r\n                // A better implementation would preserve the data on the current input line along with cursor position.\r\n                if (prev_history_pos != HistoryPos)\r\n                {\r\n                    const char* history_str = (HistoryPos >= 0) ? History[HistoryPos] : \"\";\r\n                    data->DeleteChars(0, data->BufTextLen);\r\n                    data->InsertChars(0, history_str);\r\n                }\r\n            }\r\n        }\r\n        return 0;\r\n    }\r\n};\r\n\r\nstatic void ShowExampleAppConsole(bool* p_open)\r\n{\r\n    static ExampleAppConsole console;\r\n    console.Draw(\"Example: Console\", p_open);\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Example App: Debug Log / ShowExampleAppLog()\r\n//-----------------------------------------------------------------------------\r\n\r\n// Usage:\r\n//  static ExampleAppLog my_log;\r\n//  my_log.AddLog(\"Hello %d world\\n\", 123);\r\n//  my_log.Draw(\"title\");\r\nstruct ExampleAppLog\r\n{\r\n    ImGuiTextBuffer     Buf;\r\n    ImGuiTextFilter     Filter;\r\n    ImVector<int>       LineOffsets; // Index to lines offset. We maintain this with AddLog() calls.\r\n    bool                AutoScroll;  // Keep scrolling if already at the bottom.\r\n\r\n    ExampleAppLog()\r\n    {\r\n        AutoScroll = true;\r\n        Clear();\r\n    }\r\n\r\n    void    Clear()\r\n    {\r\n        Buf.clear();\r\n        LineOffsets.clear();\r\n        LineOffsets.push_back(0);\r\n    }\r\n\r\n    void    AddLog(const char* fmt, ...) IM_FMTARGS(2)\r\n    {\r\n        int old_size = Buf.size();\r\n        va_list args;\r\n        va_start(args, fmt);\r\n        Buf.appendfv(fmt, args);\r\n        va_end(args);\r\n        for (int new_size = Buf.size(); old_size < new_size; old_size++)\r\n            if (Buf[old_size] == '\\n')\r\n                LineOffsets.push_back(old_size + 1);\r\n    }\r\n\r\n    void    Draw(const char* title, bool* p_open = NULL)\r\n    {\r\n        if (!ImGui::Begin(title, p_open))\r\n        {\r\n            ImGui::End();\r\n            return;\r\n        }\r\n\r\n        // Options menu\r\n        if (ImGui::BeginPopup(\"Options\"))\r\n        {\r\n            ImGui::Checkbox(\"Auto-scroll\", &AutoScroll);\r\n            ImGui::EndPopup();\r\n        }\r\n\r\n        // Main window\r\n        if (ImGui::Button(\"Options\"))\r\n            ImGui::OpenPopup(\"Options\");\r\n        ImGui::SameLine();\r\n        bool clear = ImGui::Button(\"Clear\");\r\n        ImGui::SameLine();\r\n        bool copy = ImGui::Button(\"Copy\");\r\n        ImGui::SameLine();\r\n        Filter.Draw(\"Filter\", -100.0f);\r\n\r\n        ImGui::Separator();\r\n        ImGui::BeginChild(\"scrolling\", ImVec2(0, 0), false, ImGuiWindowFlags_HorizontalScrollbar);\r\n\r\n        if (clear)\r\n            Clear();\r\n        if (copy)\r\n            ImGui::LogToClipboard();\r\n\r\n        ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0));\r\n        const char* buf = Buf.begin();\r\n        const char* buf_end = Buf.end();\r\n        if (Filter.IsActive())\r\n        {\r\n            // In this example we don't use the clipper when Filter is enabled.\r\n            // This is because we don't have a random access on the result on our filter.\r\n            // A real application processing logs with ten of thousands of entries may want to store the result of\r\n            // search/filter.. especially if the filtering function is not trivial (e.g. reg-exp).\r\n            for (int line_no = 0; line_no < LineOffsets.Size; line_no++)\r\n            {\r\n                const char* line_start = buf + LineOffsets[line_no];\r\n                const char* line_end = (line_no + 1 < LineOffsets.Size) ? (buf + LineOffsets[line_no + 1] - 1) : buf_end;\r\n                if (Filter.PassFilter(line_start, line_end))\r\n                    ImGui::TextUnformatted(line_start, line_end);\r\n            }\r\n        }\r\n        else\r\n        {\r\n            // The simplest and easy way to display the entire buffer:\r\n            //   ImGui::TextUnformatted(buf_begin, buf_end);\r\n            // And it'll just work. TextUnformatted() has specialization for large blob of text and will fast-forward\r\n            // to skip non-visible lines. Here we instead demonstrate using the clipper to only process lines that are\r\n            // within the visible area.\r\n            // If you have tens of thousands of items and their processing cost is non-negligible, coarse clipping them\r\n            // on your side is recommended. Using ImGuiListClipper requires\r\n            // - A) random access into your data\r\n            // - B) items all being the  same height,\r\n            // both of which we can handle since we an array pointing to the beginning of each line of text.\r\n            // When using the filter (in the block of code above) we don't have random access into the data to display\r\n            // anymore, which is why we don't use the clipper. Storing or skimming through the search result would make\r\n            // it possible (and would be recommended if you want to search through tens of thousands of entries).\r\n            ImGuiListClipper clipper;\r\n            clipper.Begin(LineOffsets.Size);\r\n            while (clipper.Step())\r\n            {\r\n                for (int line_no = clipper.DisplayStart; line_no < clipper.DisplayEnd; line_no++)\r\n                {\r\n                    const char* line_start = buf + LineOffsets[line_no];\r\n                    const char* line_end = (line_no + 1 < LineOffsets.Size) ? (buf + LineOffsets[line_no + 1] - 1) : buf_end;\r\n                    ImGui::TextUnformatted(line_start, line_end);\r\n                }\r\n            }\r\n            clipper.End();\r\n        }\r\n        ImGui::PopStyleVar();\r\n\r\n        if (AutoScroll && ImGui::GetScrollY() >= ImGui::GetScrollMaxY())\r\n            ImGui::SetScrollHereY(1.0f);\r\n\r\n        ImGui::EndChild();\r\n        ImGui::End();\r\n    }\r\n};\r\n\r\n// Demonstrate creating a simple log window with basic filtering.\r\nstatic void ShowExampleAppLog(bool* p_open)\r\n{\r\n    static ExampleAppLog log;\r\n\r\n    // For the demo: add a debug button _BEFORE_ the normal log window contents\r\n    // We take advantage of a rarely used feature: multiple calls to Begin()/End() are appending to the _same_ window.\r\n    // Most of the contents of the window will be added by the log.Draw() call.\r\n    ImGui::SetNextWindowSize(ImVec2(500, 400), ImGuiCond_FirstUseEver);\r\n    ImGui::Begin(\"Example: Log\", p_open);\r\n    IMGUI_DEMO_MARKER(\"Examples/Log\");\r\n    if (ImGui::SmallButton(\"[Debug] Add 5 entries\"))\r\n    {\r\n        static int counter = 0;\r\n        const char* categories[3] = { \"info\", \"warn\", \"error\" };\r\n        const char* words[] = { \"Bumfuzzled\", \"Cattywampus\", \"Snickersnee\", \"Abibliophobia\", \"Absquatulate\", \"Nincompoop\", \"Pauciloquent\" };\r\n        for (int n = 0; n < 5; n++)\r\n        {\r\n            const char* category = categories[counter % IM_ARRAYSIZE(categories)];\r\n            const char* word = words[counter % IM_ARRAYSIZE(words)];\r\n            log.AddLog(\"[%05d] [%s] Hello, current time is %.1f, here's a word: '%s'\\n\",\r\n                ImGui::GetFrameCount(), category, ImGui::GetTime(), word);\r\n            counter++;\r\n        }\r\n    }\r\n    ImGui::End();\r\n\r\n    // Actually call in the regular Log helper (which will Begin() into the same window as we just did)\r\n    log.Draw(\"Example: Log\", p_open);\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Example App: Simple Layout / ShowExampleAppLayout()\r\n//-----------------------------------------------------------------------------\r\n\r\n// Demonstrate create a window with multiple child windows.\r\nstatic void ShowExampleAppLayout(bool* p_open)\r\n{\r\n    ImGui::SetNextWindowSize(ImVec2(500, 440), ImGuiCond_FirstUseEver);\r\n    if (ImGui::Begin(\"Example: Simple layout\", p_open, ImGuiWindowFlags_MenuBar))\r\n    {\r\n        IMGUI_DEMO_MARKER(\"Examples/Simple layout\");\r\n        if (ImGui::BeginMenuBar())\r\n        {\r\n            if (ImGui::BeginMenu(\"File\"))\r\n            {\r\n                if (ImGui::MenuItem(\"Close\")) *p_open = false;\r\n                ImGui::EndMenu();\r\n            }\r\n            ImGui::EndMenuBar();\r\n        }\r\n\r\n        // Left\r\n        static int selected = 0;\r\n        {\r\n            ImGui::BeginChild(\"left pane\", ImVec2(150, 0), true);\r\n            for (int i = 0; i < 100; i++)\r\n            {\r\n                // FIXME: Good candidate to use ImGuiSelectableFlags_SelectOnNav\r\n                char label[128];\r\n                sprintf(label, \"MyObject %d\", i);\r\n                if (ImGui::Selectable(label, selected == i))\r\n                    selected = i;\r\n            }\r\n            ImGui::EndChild();\r\n        }\r\n        ImGui::SameLine();\r\n\r\n        // Right\r\n        {\r\n            ImGui::BeginGroup();\r\n            ImGui::BeginChild(\"item view\", ImVec2(0, -ImGui::GetFrameHeightWithSpacing())); // Leave room for 1 line below us\r\n            ImGui::Text(\"MyObject: %d\", selected);\r\n            ImGui::Separator();\r\n            if (ImGui::BeginTabBar(\"##Tabs\", ImGuiTabBarFlags_None))\r\n            {\r\n                if (ImGui::BeginTabItem(\"Description\"))\r\n                {\r\n                    ImGui::TextWrapped(\"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. \");\r\n                    ImGui::EndTabItem();\r\n                }\r\n                if (ImGui::BeginTabItem(\"Details\"))\r\n                {\r\n                    ImGui::Text(\"ID: 0123456789\");\r\n                    ImGui::EndTabItem();\r\n                }\r\n                ImGui::EndTabBar();\r\n            }\r\n            ImGui::EndChild();\r\n            if (ImGui::Button(\"Revert\")) {}\r\n            ImGui::SameLine();\r\n            if (ImGui::Button(\"Save\")) {}\r\n            ImGui::EndGroup();\r\n        }\r\n    }\r\n    ImGui::End();\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Example App: Property Editor / ShowExampleAppPropertyEditor()\r\n//-----------------------------------------------------------------------------\r\n\r\nstatic void ShowPlaceholderObject(const char* prefix, int uid)\r\n{\r\n    // Use object uid as identifier. Most commonly you could also use the object pointer as a base ID.\r\n    ImGui::PushID(uid);\r\n\r\n    // Text and Tree nodes are less high than framed widgets, using AlignTextToFramePadding() we add vertical spacing to make the tree lines equal high.\r\n    ImGui::TableNextRow();\r\n    ImGui::TableSetColumnIndex(0);\r\n    ImGui::AlignTextToFramePadding();\r\n    bool node_open = ImGui::TreeNode(\"Object\", \"%s_%u\", prefix, uid);\r\n    ImGui::TableSetColumnIndex(1);\r\n    ImGui::Text(\"my sailor is rich\");\r\n\r\n    if (node_open)\r\n    {\r\n        static float placeholder_members[8] = { 0.0f, 0.0f, 1.0f, 3.1416f, 100.0f, 999.0f };\r\n        for (int i = 0; i < 8; i++)\r\n        {\r\n            ImGui::PushID(i); // Use field index as identifier.\r\n            if (i < 2)\r\n            {\r\n                ShowPlaceholderObject(\"Child\", 424242);\r\n            }\r\n            else\r\n            {\r\n                // Here we use a TreeNode to highlight on hover (we could use e.g. Selectable as well)\r\n                ImGui::TableNextRow();\r\n                ImGui::TableSetColumnIndex(0);\r\n                ImGui::AlignTextToFramePadding();\r\n                ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_Bullet;\r\n                ImGui::TreeNodeEx(\"Field\", flags, \"Field_%d\", i);\r\n\r\n                ImGui::TableSetColumnIndex(1);\r\n                ImGui::SetNextItemWidth(-FLT_MIN);\r\n                if (i >= 5)\r\n                    ImGui::InputFloat(\"##value\", &placeholder_members[i], 1.0f);\r\n                else\r\n                    ImGui::DragFloat(\"##value\", &placeholder_members[i], 0.01f);\r\n                ImGui::NextColumn();\r\n            }\r\n            ImGui::PopID();\r\n        }\r\n        ImGui::TreePop();\r\n    }\r\n    ImGui::PopID();\r\n}\r\n\r\n// Demonstrate create a simple property editor.\r\nstatic void ShowExampleAppPropertyEditor(bool* p_open)\r\n{\r\n    ImGui::SetNextWindowSize(ImVec2(430, 450), ImGuiCond_FirstUseEver);\r\n    if (!ImGui::Begin(\"Example: Property editor\", p_open))\r\n    {\r\n        ImGui::End();\r\n        return;\r\n    }\r\n    IMGUI_DEMO_MARKER(\"Examples/Property Editor\");\r\n\r\n    HelpMarker(\r\n        \"This example shows how you may implement a property editor using two columns.\\n\"\r\n        \"All objects/fields data are dummies here.\\n\"\r\n        \"Remember that in many simple cases, you can use ImGui::SameLine(xxx) to position\\n\"\r\n        \"your cursor horizontally instead of using the Columns() API.\");\r\n\r\n    ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2, 2));\r\n    if (ImGui::BeginTable(\"split\", 2, ImGuiTableFlags_BordersOuter | ImGuiTableFlags_Resizable))\r\n    {\r\n        // Iterate placeholder objects (all the same data)\r\n        for (int obj_i = 0; obj_i < 4; obj_i++)\r\n        {\r\n            ShowPlaceholderObject(\"Object\", obj_i);\r\n            //ImGui::Separator();\r\n        }\r\n        ImGui::EndTable();\r\n    }\r\n    ImGui::PopStyleVar();\r\n    ImGui::End();\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Example App: Long Text / ShowExampleAppLongText()\r\n//-----------------------------------------------------------------------------\r\n\r\n// Demonstrate/test rendering huge amount of text, and the incidence of clipping.\r\nstatic void ShowExampleAppLongText(bool* p_open)\r\n{\r\n    ImGui::SetNextWindowSize(ImVec2(520, 600), ImGuiCond_FirstUseEver);\r\n    if (!ImGui::Begin(\"Example: Long text display\", p_open))\r\n    {\r\n        ImGui::End();\r\n        return;\r\n    }\r\n    IMGUI_DEMO_MARKER(\"Examples/Long text display\");\r\n\r\n    static int test_type = 0;\r\n    static ImGuiTextBuffer log;\r\n    static int lines = 0;\r\n    ImGui::Text(\"Printing unusually long amount of text.\");\r\n    ImGui::Combo(\"Test type\", &test_type,\r\n        \"Single call to TextUnformatted()\\0\"\r\n        \"Multiple calls to Text(), clipped\\0\"\r\n        \"Multiple calls to Text(), not clipped (slow)\\0\");\r\n    ImGui::Text(\"Buffer contents: %d lines, %d bytes\", lines, log.size());\r\n    if (ImGui::Button(\"Clear\")) { log.clear(); lines = 0; }\r\n    ImGui::SameLine();\r\n    if (ImGui::Button(\"Add 1000 lines\"))\r\n    {\r\n        for (int i = 0; i < 1000; i++)\r\n            log.appendf(\"%i The quick brown fox jumps over the lazy dog\\n\", lines + i);\r\n        lines += 1000;\r\n    }\r\n    ImGui::BeginChild(\"Log\");\r\n    switch (test_type)\r\n    {\r\n    case 0:\r\n        // Single call to TextUnformatted() with a big buffer\r\n        ImGui::TextUnformatted(log.begin(), log.end());\r\n        break;\r\n    case 1:\r\n        {\r\n            // Multiple calls to Text(), manually coarsely clipped - demonstrate how to use the ImGuiListClipper helper.\r\n            ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0));\r\n            ImGuiListClipper clipper;\r\n            clipper.Begin(lines);\r\n            while (clipper.Step())\r\n                for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)\r\n                    ImGui::Text(\"%i The quick brown fox jumps over the lazy dog\", i);\r\n            ImGui::PopStyleVar();\r\n            break;\r\n        }\r\n    case 2:\r\n        // Multiple calls to Text(), not clipped (slow)\r\n        ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0));\r\n        for (int i = 0; i < lines; i++)\r\n            ImGui::Text(\"%i The quick brown fox jumps over the lazy dog\", i);\r\n        ImGui::PopStyleVar();\r\n        break;\r\n    }\r\n    ImGui::EndChild();\r\n    ImGui::End();\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Example App: Auto Resize / ShowExampleAppAutoResize()\r\n//-----------------------------------------------------------------------------\r\n\r\n// Demonstrate creating a window which gets auto-resized according to its content.\r\nstatic void ShowExampleAppAutoResize(bool* p_open)\r\n{\r\n    if (!ImGui::Begin(\"Example: Auto-resizing window\", p_open, ImGuiWindowFlags_AlwaysAutoResize))\r\n    {\r\n        ImGui::End();\r\n        return;\r\n    }\r\n    IMGUI_DEMO_MARKER(\"Examples/Auto-resizing window\");\r\n\r\n    static int lines = 10;\r\n    ImGui::TextUnformatted(\r\n        \"Window will resize every-frame to the size of its content.\\n\"\r\n        \"Note that you probably don't want to query the window size to\\n\"\r\n        \"output your content because that would create a feedback loop.\");\r\n    ImGui::SliderInt(\"Number of lines\", &lines, 1, 20);\r\n    for (int i = 0; i < lines; i++)\r\n        ImGui::Text(\"%*sThis is line %d\", i * 4, \"\", i); // Pad with space to extend size horizontally\r\n    ImGui::End();\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Example App: Constrained Resize / ShowExampleAppConstrainedResize()\r\n//-----------------------------------------------------------------------------\r\n\r\n// Demonstrate creating a window with custom resize constraints.\r\nstatic void ShowExampleAppConstrainedResize(bool* p_open)\r\n{\r\n    struct CustomConstraints\r\n    {\r\n        // Helper functions to demonstrate programmatic constraints\r\n        static void Square(ImGuiSizeCallbackData* data) { data->DesiredSize.x = data->DesiredSize.y = IM_MAX(data->DesiredSize.x, data->DesiredSize.y); }\r\n        static void Step(ImGuiSizeCallbackData* data)   { float step = (float)(int)(intptr_t)data->UserData; data->DesiredSize = ImVec2((int)(data->DesiredSize.x / step + 0.5f) * step, (int)(data->DesiredSize.y / step + 0.5f) * step); }\r\n    };\r\n\r\n    const char* test_desc[] =\r\n    {\r\n        \"Resize vertical only\",\r\n        \"Resize horizontal only\",\r\n        \"Width > 100, Height > 100\",\r\n        \"Width 400-500\",\r\n        \"Height 400-500\",\r\n        \"Custom: Always Square\",\r\n        \"Custom: Fixed Steps (100)\",\r\n    };\r\n\r\n    static bool auto_resize = false;\r\n    static int type = 0;\r\n    static int display_lines = 10;\r\n    if (type == 0) ImGui::SetNextWindowSizeConstraints(ImVec2(-1, 0),    ImVec2(-1, FLT_MAX));      // Vertical only\r\n    if (type == 1) ImGui::SetNextWindowSizeConstraints(ImVec2(0, -1),    ImVec2(FLT_MAX, -1));      // Horizontal only\r\n    if (type == 2) ImGui::SetNextWindowSizeConstraints(ImVec2(100, 100), ImVec2(FLT_MAX, FLT_MAX)); // Width > 100, Height > 100\r\n    if (type == 3) ImGui::SetNextWindowSizeConstraints(ImVec2(400, -1),  ImVec2(500, -1));          // Width 400-500\r\n    if (type == 4) ImGui::SetNextWindowSizeConstraints(ImVec2(-1, 400),  ImVec2(-1, 500));          // Height 400-500\r\n    if (type == 5) ImGui::SetNextWindowSizeConstraints(ImVec2(0, 0),     ImVec2(FLT_MAX, FLT_MAX), CustomConstraints::Square);                     // Always Square\r\n    if (type == 6) ImGui::SetNextWindowSizeConstraints(ImVec2(0, 0),     ImVec2(FLT_MAX, FLT_MAX), CustomConstraints::Step, (void*)(intptr_t)100); // Fixed Step\r\n\r\n    ImGuiWindowFlags flags = auto_resize ? ImGuiWindowFlags_AlwaysAutoResize : 0;\r\n    if (ImGui::Begin(\"Example: Constrained Resize\", p_open, flags))\r\n    {\r\n        IMGUI_DEMO_MARKER(\"Examples/Constrained Resizing window\");\r\n        if (ImGui::Button(\"200x200\")) { ImGui::SetWindowSize(ImVec2(200, 200)); } ImGui::SameLine();\r\n        if (ImGui::Button(\"500x500\")) { ImGui::SetWindowSize(ImVec2(500, 500)); } ImGui::SameLine();\r\n        if (ImGui::Button(\"800x200\")) { ImGui::SetWindowSize(ImVec2(800, 200)); }\r\n        ImGui::SetNextItemWidth(200);\r\n        ImGui::Combo(\"Constraint\", &type, test_desc, IM_ARRAYSIZE(test_desc));\r\n        ImGui::SetNextItemWidth(200);\r\n        ImGui::DragInt(\"Lines\", &display_lines, 0.2f, 1, 100);\r\n        ImGui::Checkbox(\"Auto-resize\", &auto_resize);\r\n        for (int i = 0; i < display_lines; i++)\r\n            ImGui::Text(\"%*sHello, sailor! Making this line long enough for the example.\", i * 4, \"\");\r\n    }\r\n    ImGui::End();\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Example App: Simple overlay / ShowExampleAppSimpleOverlay()\r\n//-----------------------------------------------------------------------------\r\n\r\n// Demonstrate creating a simple static window with no decoration\r\n// + a context-menu to choose which corner of the screen to use.\r\nstatic void ShowExampleAppSimpleOverlay(bool* p_open)\r\n{\r\n    static int corner = 0;\r\n    ImGuiIO& io = ImGui::GetIO();\r\n    ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoNav;\r\n    if (corner != -1)\r\n    {\r\n        const float PAD = 10.0f;\r\n        const ImGuiViewport* viewport = ImGui::GetMainViewport();\r\n        ImVec2 work_pos = viewport->WorkPos; // Use work area to avoid menu-bar/task-bar, if any!\r\n        ImVec2 work_size = viewport->WorkSize;\r\n        ImVec2 window_pos, window_pos_pivot;\r\n        window_pos.x = (corner & 1) ? (work_pos.x + work_size.x - PAD) : (work_pos.x + PAD);\r\n        window_pos.y = (corner & 2) ? (work_pos.y + work_size.y - PAD) : (work_pos.y + PAD);\r\n        window_pos_pivot.x = (corner & 1) ? 1.0f : 0.0f;\r\n        window_pos_pivot.y = (corner & 2) ? 1.0f : 0.0f;\r\n        ImGui::SetNextWindowPos(window_pos, ImGuiCond_Always, window_pos_pivot);\r\n        window_flags |= ImGuiWindowFlags_NoMove;\r\n    }\r\n    ImGui::SetNextWindowBgAlpha(0.35f); // Transparent background\r\n    if (ImGui::Begin(\"Example: Simple overlay\", p_open, window_flags))\r\n    {\r\n        IMGUI_DEMO_MARKER(\"Examples/Simple Overlay\");\r\n        ImGui::Text(\"Simple overlay\\n\" \"in the corner of the screen.\\n\" \"(right-click to change position)\");\r\n        ImGui::Separator();\r\n        if (ImGui::IsMousePosValid())\r\n            ImGui::Text(\"Mouse Position: (%.1f,%.1f)\", io.MousePos.x, io.MousePos.y);\r\n        else\r\n            ImGui::Text(\"Mouse Position: <invalid>\");\r\n        if (ImGui::BeginPopupContextWindow())\r\n        {\r\n            if (ImGui::MenuItem(\"Custom\",       NULL, corner == -1)) corner = -1;\r\n            if (ImGui::MenuItem(\"Top-left\",     NULL, corner == 0)) corner = 0;\r\n            if (ImGui::MenuItem(\"Top-right\",    NULL, corner == 1)) corner = 1;\r\n            if (ImGui::MenuItem(\"Bottom-left\",  NULL, corner == 2)) corner = 2;\r\n            if (ImGui::MenuItem(\"Bottom-right\", NULL, corner == 3)) corner = 3;\r\n            if (p_open && ImGui::MenuItem(\"Close\")) *p_open = false;\r\n            ImGui::EndPopup();\r\n        }\r\n    }\r\n    ImGui::End();\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Example App: Fullscreen window / ShowExampleAppFullscreen()\r\n//-----------------------------------------------------------------------------\r\n\r\n// Demonstrate creating a window covering the entire screen/viewport\r\nstatic void ShowExampleAppFullscreen(bool* p_open)\r\n{\r\n    static bool use_work_area = true;\r\n    static ImGuiWindowFlags flags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings;\r\n\r\n    // We demonstrate using the full viewport area or the work area (without menu-bars, task-bars etc.)\r\n    // Based on your use case you may want one of the other.\r\n    const ImGuiViewport* viewport = ImGui::GetMainViewport();\r\n    ImGui::SetNextWindowPos(use_work_area ? viewport->WorkPos : viewport->Pos);\r\n    ImGui::SetNextWindowSize(use_work_area ? viewport->WorkSize : viewport->Size);\r\n\r\n    if (ImGui::Begin(\"Example: Fullscreen window\", p_open, flags))\r\n    {\r\n        ImGui::Checkbox(\"Use work area instead of main area\", &use_work_area);\r\n        ImGui::SameLine();\r\n        HelpMarker(\"Main Area = entire viewport,\\nWork Area = entire viewport minus sections used by the main menu bars, task bars etc.\\n\\nEnable the main-menu bar in Examples menu to see the difference.\");\r\n\r\n        ImGui::CheckboxFlags(\"ImGuiWindowFlags_NoBackground\", &flags, ImGuiWindowFlags_NoBackground);\r\n        ImGui::CheckboxFlags(\"ImGuiWindowFlags_NoDecoration\", &flags, ImGuiWindowFlags_NoDecoration);\r\n        ImGui::Indent();\r\n        ImGui::CheckboxFlags(\"ImGuiWindowFlags_NoTitleBar\", &flags, ImGuiWindowFlags_NoTitleBar);\r\n        ImGui::CheckboxFlags(\"ImGuiWindowFlags_NoCollapse\", &flags, ImGuiWindowFlags_NoCollapse);\r\n        ImGui::CheckboxFlags(\"ImGuiWindowFlags_NoScrollbar\", &flags, ImGuiWindowFlags_NoScrollbar);\r\n        ImGui::Unindent();\r\n\r\n        if (p_open && ImGui::Button(\"Close this window\"))\r\n            *p_open = false;\r\n    }\r\n    ImGui::End();\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Example App: Manipulating Window Titles / ShowExampleAppWindowTitles()\r\n//-----------------------------------------------------------------------------\r\n\r\n// Demonstrate using \"##\" and \"###\" in identifiers to manipulate ID generation.\r\n// This apply to all regular items as well.\r\n// Read FAQ section \"How can I have multiple widgets with the same label?\" for details.\r\nstatic void ShowExampleAppWindowTitles(bool*)\r\n{\r\n    const ImGuiViewport* viewport = ImGui::GetMainViewport();\r\n    const ImVec2 base_pos = viewport->Pos;\r\n\r\n    // By default, Windows are uniquely identified by their title.\r\n    // You can use the \"##\" and \"###\" markers to manipulate the display/ID.\r\n\r\n    // Using \"##\" to display same title but have unique identifier.\r\n    ImGui::SetNextWindowPos(ImVec2(base_pos.x + 100, base_pos.y + 100), ImGuiCond_FirstUseEver);\r\n    ImGui::Begin(\"Same title as another window##1\");\r\n    IMGUI_DEMO_MARKER(\"Examples/Manipulating window titles\");\r\n    ImGui::Text(\"This is window 1.\\nMy title is the same as window 2, but my identifier is unique.\");\r\n    ImGui::End();\r\n\r\n    ImGui::SetNextWindowPos(ImVec2(base_pos.x + 100, base_pos.y + 200), ImGuiCond_FirstUseEver);\r\n    ImGui::Begin(\"Same title as another window##2\");\r\n    ImGui::Text(\"This is window 2.\\nMy title is the same as window 1, but my identifier is unique.\");\r\n    ImGui::End();\r\n\r\n    // Using \"###\" to display a changing title but keep a static identifier \"AnimatedTitle\"\r\n    char buf[128];\r\n    sprintf(buf, \"Animated title %c %d###AnimatedTitle\", \"|/-\\\\\"[(int)(ImGui::GetTime() / 0.25f) & 3], ImGui::GetFrameCount());\r\n    ImGui::SetNextWindowPos(ImVec2(base_pos.x + 100, base_pos.y + 300), ImGuiCond_FirstUseEver);\r\n    ImGui::Begin(buf);\r\n    ImGui::Text(\"This window has a changing title.\");\r\n    ImGui::End();\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Example App: Custom Rendering using ImDrawList API / ShowExampleAppCustomRendering()\r\n//-----------------------------------------------------------------------------\r\n\r\n// Demonstrate using the low-level ImDrawList to draw custom shapes.\r\nstatic void ShowExampleAppCustomRendering(bool* p_open)\r\n{\r\n    if (!ImGui::Begin(\"Example: Custom rendering\", p_open))\r\n    {\r\n        ImGui::End();\r\n        return;\r\n    }\r\n    IMGUI_DEMO_MARKER(\"Examples/Custom Rendering\");\r\n\r\n    // Tip: If you do a lot of custom rendering, you probably want to use your own geometrical types and benefit of\r\n    // overloaded operators, etc. Define IM_VEC2_CLASS_EXTRA in imconfig.h to create implicit conversions between your\r\n    // types and ImVec2/ImVec4. Dear ImGui defines overloaded operators but they are internal to imgui.cpp and not\r\n    // exposed outside (to avoid messing with your types) In this example we are not using the maths operators!\r\n\r\n    if (ImGui::BeginTabBar(\"##TabBar\"))\r\n    {\r\n        if (ImGui::BeginTabItem(\"Primitives\"))\r\n        {\r\n            ImGui::PushItemWidth(-ImGui::GetFontSize() * 15);\r\n            ImDrawList* draw_list = ImGui::GetWindowDrawList();\r\n\r\n            // Draw gradients\r\n            // (note that those are currently exacerbating our sRGB/Linear issues)\r\n            // Calling ImGui::GetColorU32() multiplies the given colors by the current Style Alpha, but you may pass the IM_COL32() directly as well..\r\n            ImGui::Text(\"Gradients\");\r\n            ImVec2 gradient_size = ImVec2(ImGui::CalcItemWidth(), ImGui::GetFrameHeight());\r\n            {\r\n                ImVec2 p0 = ImGui::GetCursorScreenPos();\r\n                ImVec2 p1 = ImVec2(p0.x + gradient_size.x, p0.y + gradient_size.y);\r\n                ImU32 col_a = ImGui::GetColorU32(IM_COL32(0, 0, 0, 255));\r\n                ImU32 col_b = ImGui::GetColorU32(IM_COL32(255, 255, 255, 255));\r\n                draw_list->AddRectFilledMultiColor(p0, p1, col_a, col_b, col_b, col_a);\r\n                ImGui::InvisibleButton(\"##gradient1\", gradient_size);\r\n            }\r\n            {\r\n                ImVec2 p0 = ImGui::GetCursorScreenPos();\r\n                ImVec2 p1 = ImVec2(p0.x + gradient_size.x, p0.y + gradient_size.y);\r\n                ImU32 col_a = ImGui::GetColorU32(IM_COL32(0, 255, 0, 255));\r\n                ImU32 col_b = ImGui::GetColorU32(IM_COL32(255, 0, 0, 255));\r\n                draw_list->AddRectFilledMultiColor(p0, p1, col_a, col_b, col_b, col_a);\r\n                ImGui::InvisibleButton(\"##gradient2\", gradient_size);\r\n            }\r\n\r\n            // Draw a bunch of primitives\r\n            ImGui::Text(\"All primitives\");\r\n            static float sz = 36.0f;\r\n            static float thickness = 3.0f;\r\n            static int ngon_sides = 6;\r\n            static bool circle_segments_override = false;\r\n            static int circle_segments_override_v = 12;\r\n            static bool curve_segments_override = false;\r\n            static int curve_segments_override_v = 8;\r\n            static ImVec4 colf = ImVec4(1.0f, 1.0f, 0.4f, 1.0f);\r\n            ImGui::DragFloat(\"Size\", &sz, 0.2f, 2.0f, 100.0f, \"%.0f\");\r\n            ImGui::DragFloat(\"Thickness\", &thickness, 0.05f, 1.0f, 8.0f, \"%.02f\");\r\n            ImGui::SliderInt(\"N-gon sides\", &ngon_sides, 3, 12);\r\n            ImGui::Checkbox(\"##circlesegmentoverride\", &circle_segments_override);\r\n            ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x);\r\n            circle_segments_override |= ImGui::SliderInt(\"Circle segments override\", &circle_segments_override_v, 3, 40);\r\n            ImGui::Checkbox(\"##curvessegmentoverride\", &curve_segments_override);\r\n            ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x);\r\n            curve_segments_override |= ImGui::SliderInt(\"Curves segments override\", &curve_segments_override_v, 3, 40);\r\n            ImGui::ColorEdit4(\"Color\", &colf.x);\r\n\r\n            const ImVec2 p = ImGui::GetCursorScreenPos();\r\n            const ImU32 col = ImColor(colf);\r\n            const float spacing = 10.0f;\r\n            const ImDrawFlags corners_tl_br = ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersBottomRight;\r\n            const float rounding = sz / 5.0f;\r\n            const int circle_segments = circle_segments_override ? circle_segments_override_v : 0;\r\n            const int curve_segments = curve_segments_override ? curve_segments_override_v : 0;\r\n            float x = p.x + 4.0f;\r\n            float y = p.y + 4.0f;\r\n            for (int n = 0; n < 2; n++)\r\n            {\r\n                // First line uses a thickness of 1.0f, second line uses the configurable thickness\r\n                float th = (n == 0) ? 1.0f : thickness;\r\n                draw_list->AddNgon(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, ngon_sides, th);                 x += sz + spacing;  // N-gon\r\n                draw_list->AddCircle(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, circle_segments, th);          x += sz + spacing;  // Circle\r\n                draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 0.0f, ImDrawFlags_None, th);          x += sz + spacing;  // Square\r\n                draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding, ImDrawFlags_None, th);      x += sz + spacing;  // Square with all rounded corners\r\n                draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding, corners_tl_br, th);         x += sz + spacing;  // Square with two rounded corners\r\n                draw_list->AddTriangle(ImVec2(x+sz*0.5f,y), ImVec2(x+sz, y+sz-0.5f), ImVec2(x, y+sz-0.5f), col, th);x += sz + spacing;  // Triangle\r\n                //draw_list->AddTriangle(ImVec2(x+sz*0.2f,y), ImVec2(x, y+sz-0.5f), ImVec2(x+sz*0.4f, y+sz-0.5f), col, th);x+= sz*0.4f + spacing; // Thin triangle\r\n                draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y), col, th);                                       x += sz + spacing;  // Horizontal line (note: drawing a filled rectangle will be faster!)\r\n                draw_list->AddLine(ImVec2(x, y), ImVec2(x, y + sz), col, th);                                       x += spacing;       // Vertical line (note: drawing a filled rectangle will be faster!)\r\n                draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y + sz), col, th);                                  x += sz + spacing;  // Diagonal line\r\n\r\n                // Quadratic Bezier Curve (3 control points)\r\n                ImVec2 cp3[3] = { ImVec2(x, y + sz * 0.6f), ImVec2(x + sz * 0.5f, y - sz * 0.4f), ImVec2(x + sz, y + sz) };\r\n                draw_list->AddBezierQuadratic(cp3[0], cp3[1], cp3[2], col, th, curve_segments); x += sz + spacing;\r\n\r\n                // Cubic Bezier Curve (4 control points)\r\n                ImVec2 cp4[4] = { ImVec2(x, y), ImVec2(x + sz * 1.3f, y + sz * 0.3f), ImVec2(x + sz - sz * 1.3f, y + sz - sz * 0.3f), ImVec2(x + sz, y + sz) };\r\n                draw_list->AddBezierCubic(cp4[0], cp4[1], cp4[2], cp4[3], col, th, curve_segments);\r\n\r\n                x = p.x + 4;\r\n                y += sz + spacing;\r\n            }\r\n            draw_list->AddNgonFilled(ImVec2(x + sz * 0.5f, y + sz * 0.5f), sz*0.5f, col, ngon_sides);               x += sz + spacing;  // N-gon\r\n            draw_list->AddCircleFilled(ImVec2(x + sz*0.5f, y + sz*0.5f), sz*0.5f, col, circle_segments);            x += sz + spacing;  // Circle\r\n            draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col);                                    x += sz + spacing;  // Square\r\n            draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 10.0f);                             x += sz + spacing;  // Square with all rounded corners\r\n            draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 10.0f, corners_tl_br);              x += sz + spacing;  // Square with two rounded corners\r\n            draw_list->AddTriangleFilled(ImVec2(x+sz*0.5f,y), ImVec2(x+sz, y+sz-0.5f), ImVec2(x, y+sz-0.5f), col);  x += sz + spacing;  // Triangle\r\n            //draw_list->AddTriangleFilled(ImVec2(x+sz*0.2f,y), ImVec2(x, y+sz-0.5f), ImVec2(x+sz*0.4f, y+sz-0.5f), col); x += sz*0.4f + spacing; // Thin triangle\r\n            draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + thickness), col);                             x += sz + spacing;  // Horizontal line (faster than AddLine, but only handle integer thickness)\r\n            draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + thickness, y + sz), col);                             x += spacing * 2.0f;// Vertical line (faster than AddLine, but only handle integer thickness)\r\n            draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + 1, y + 1), col);                                      x += sz;            // Pixel (faster than AddLine)\r\n            draw_list->AddRectFilledMultiColor(ImVec2(x, y), ImVec2(x + sz, y + sz), IM_COL32(0, 0, 0, 255), IM_COL32(255, 0, 0, 255), IM_COL32(255, 255, 0, 255), IM_COL32(0, 255, 0, 255));\r\n\r\n            ImGui::Dummy(ImVec2((sz + spacing) * 10.2f, (sz + spacing) * 3.0f));\r\n            ImGui::PopItemWidth();\r\n            ImGui::EndTabItem();\r\n        }\r\n\r\n        if (ImGui::BeginTabItem(\"Canvas\"))\r\n        {\r\n            static ImVector<ImVec2> points;\r\n            static ImVec2 scrolling(0.0f, 0.0f);\r\n            static bool opt_enable_grid = true;\r\n            static bool opt_enable_context_menu = true;\r\n            static bool adding_line = false;\r\n\r\n            ImGui::Checkbox(\"Enable grid\", &opt_enable_grid);\r\n            ImGui::Checkbox(\"Enable context menu\", &opt_enable_context_menu);\r\n            ImGui::Text(\"Mouse Left: drag to add lines,\\nMouse Right: drag to scroll, click for context menu.\");\r\n\r\n            // Typically you would use a BeginChild()/EndChild() pair to benefit from a clipping region + own scrolling.\r\n            // Here we demonstrate that this can be replaced by simple offsetting + custom drawing + PushClipRect/PopClipRect() calls.\r\n            // To use a child window instead we could use, e.g:\r\n            //      ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));      // Disable padding\r\n            //      ImGui::PushStyleColor(ImGuiCol_ChildBg, IM_COL32(50, 50, 50, 255));  // Set a background color\r\n            //      ImGui::BeginChild(\"canvas\", ImVec2(0.0f, 0.0f), true, ImGuiWindowFlags_NoMove);\r\n            //      ImGui::PopStyleColor();\r\n            //      ImGui::PopStyleVar();\r\n            //      [...]\r\n            //      ImGui::EndChild();\r\n\r\n            // Using InvisibleButton() as a convenience 1) it will advance the layout cursor and 2) allows us to use IsItemHovered()/IsItemActive()\r\n            ImVec2 canvas_p0 = ImGui::GetCursorScreenPos();      // ImDrawList API uses screen coordinates!\r\n            ImVec2 canvas_sz = ImGui::GetContentRegionAvail();   // Resize canvas to what's available\r\n            if (canvas_sz.x < 50.0f) canvas_sz.x = 50.0f;\r\n            if (canvas_sz.y < 50.0f) canvas_sz.y = 50.0f;\r\n            ImVec2 canvas_p1 = ImVec2(canvas_p0.x + canvas_sz.x, canvas_p0.y + canvas_sz.y);\r\n\r\n            // Draw border and background color\r\n            ImGuiIO& io = ImGui::GetIO();\r\n            ImDrawList* draw_list = ImGui::GetWindowDrawList();\r\n            draw_list->AddRectFilled(canvas_p0, canvas_p1, IM_COL32(50, 50, 50, 255));\r\n            draw_list->AddRect(canvas_p0, canvas_p1, IM_COL32(255, 255, 255, 255));\r\n\r\n            // This will catch our interactions\r\n            ImGui::InvisibleButton(\"canvas\", canvas_sz, ImGuiButtonFlags_MouseButtonLeft | ImGuiButtonFlags_MouseButtonRight);\r\n            const bool is_hovered = ImGui::IsItemHovered(); // Hovered\r\n            const bool is_active = ImGui::IsItemActive();   // Held\r\n            const ImVec2 origin(canvas_p0.x + scrolling.x, canvas_p0.y + scrolling.y); // Lock scrolled origin\r\n            const ImVec2 mouse_pos_in_canvas(io.MousePos.x - origin.x, io.MousePos.y - origin.y);\r\n\r\n            // Add first and second point\r\n            if (is_hovered && !adding_line && ImGui::IsMouseClicked(ImGuiMouseButton_Left))\r\n            {\r\n                points.push_back(mouse_pos_in_canvas);\r\n                points.push_back(mouse_pos_in_canvas);\r\n                adding_line = true;\r\n            }\r\n            if (adding_line)\r\n            {\r\n                points.back() = mouse_pos_in_canvas;\r\n                if (!ImGui::IsMouseDown(ImGuiMouseButton_Left))\r\n                    adding_line = false;\r\n            }\r\n\r\n            // Pan (we use a zero mouse threshold when there's no context menu)\r\n            // You may decide to make that threshold dynamic based on whether the mouse is hovering something etc.\r\n            const float mouse_threshold_for_pan = opt_enable_context_menu ? -1.0f : 0.0f;\r\n            if (is_active && ImGui::IsMouseDragging(ImGuiMouseButton_Right, mouse_threshold_for_pan))\r\n            {\r\n                scrolling.x += io.MouseDelta.x;\r\n                scrolling.y += io.MouseDelta.y;\r\n            }\r\n\r\n            // Context menu (under default mouse threshold)\r\n            ImVec2 drag_delta = ImGui::GetMouseDragDelta(ImGuiMouseButton_Right);\r\n            if (opt_enable_context_menu && drag_delta.x == 0.0f && drag_delta.y == 0.0f)\r\n                ImGui::OpenPopupOnItemClick(\"context\", ImGuiPopupFlags_MouseButtonRight);\r\n            if (ImGui::BeginPopup(\"context\"))\r\n            {\r\n                if (adding_line)\r\n                    points.resize(points.size() - 2);\r\n                adding_line = false;\r\n                if (ImGui::MenuItem(\"Remove one\", NULL, false, points.Size > 0)) { points.resize(points.size() - 2); }\r\n                if (ImGui::MenuItem(\"Remove all\", NULL, false, points.Size > 0)) { points.clear(); }\r\n                ImGui::EndPopup();\r\n            }\r\n\r\n            // Draw grid + all lines in the canvas\r\n            draw_list->PushClipRect(canvas_p0, canvas_p1, true);\r\n            if (opt_enable_grid)\r\n            {\r\n                const float GRID_STEP = 64.0f;\r\n                for (float x = fmodf(scrolling.x, GRID_STEP); x < canvas_sz.x; x += GRID_STEP)\r\n                    draw_list->AddLine(ImVec2(canvas_p0.x + x, canvas_p0.y), ImVec2(canvas_p0.x + x, canvas_p1.y), IM_COL32(200, 200, 200, 40));\r\n                for (float y = fmodf(scrolling.y, GRID_STEP); y < canvas_sz.y; y += GRID_STEP)\r\n                    draw_list->AddLine(ImVec2(canvas_p0.x, canvas_p0.y + y), ImVec2(canvas_p1.x, canvas_p0.y + y), IM_COL32(200, 200, 200, 40));\r\n            }\r\n            for (int n = 0; n < points.Size; n += 2)\r\n                draw_list->AddLine(ImVec2(origin.x + points[n].x, origin.y + points[n].y), ImVec2(origin.x + points[n + 1].x, origin.y + points[n + 1].y), IM_COL32(255, 255, 0, 255), 2.0f);\r\n            draw_list->PopClipRect();\r\n\r\n            ImGui::EndTabItem();\r\n        }\r\n\r\n        if (ImGui::BeginTabItem(\"BG/FG draw lists\"))\r\n        {\r\n            static bool draw_bg = true;\r\n            static bool draw_fg = true;\r\n            ImGui::Checkbox(\"Draw in Background draw list\", &draw_bg);\r\n            ImGui::SameLine(); HelpMarker(\"The Background draw list will be rendered below every Dear ImGui windows.\");\r\n            ImGui::Checkbox(\"Draw in Foreground draw list\", &draw_fg);\r\n            ImGui::SameLine(); HelpMarker(\"The Foreground draw list will be rendered over every Dear ImGui windows.\");\r\n            ImVec2 window_pos = ImGui::GetWindowPos();\r\n            ImVec2 window_size = ImGui::GetWindowSize();\r\n            ImVec2 window_center = ImVec2(window_pos.x + window_size.x * 0.5f, window_pos.y + window_size.y * 0.5f);\r\n            if (draw_bg)\r\n                ImGui::GetBackgroundDrawList()->AddCircle(window_center, window_size.x * 0.6f, IM_COL32(255, 0, 0, 200), 0, 10 + 4);\r\n            if (draw_fg)\r\n                ImGui::GetForegroundDrawList()->AddCircle(window_center, window_size.y * 0.6f, IM_COL32(0, 255, 0, 200), 0, 10);\r\n            ImGui::EndTabItem();\r\n        }\r\n\r\n        ImGui::EndTabBar();\r\n    }\r\n\r\n    ImGui::End();\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Example App: Documents Handling / ShowExampleAppDocuments()\r\n//-----------------------------------------------------------------------------\r\n\r\n// Simplified structure to mimic a Document model\r\nstruct MyDocument\r\n{\r\n    const char* Name;       // Document title\r\n    bool        Open;       // Set when open (we keep an array of all available documents to simplify demo code!)\r\n    bool        OpenPrev;   // Copy of Open from last update.\r\n    bool        Dirty;      // Set when the document has been modified\r\n    bool        WantClose;  // Set when the document\r\n    ImVec4      Color;      // An arbitrary variable associated to the document\r\n\r\n    MyDocument(const char* name, bool open = true, const ImVec4& color = ImVec4(1.0f, 1.0f, 1.0f, 1.0f))\r\n    {\r\n        Name = name;\r\n        Open = OpenPrev = open;\r\n        Dirty = false;\r\n        WantClose = false;\r\n        Color = color;\r\n    }\r\n    void DoOpen()       { Open = true; }\r\n    void DoQueueClose() { WantClose = true; }\r\n    void DoForceClose() { Open = false; Dirty = false; }\r\n    void DoSave()       { Dirty = false; }\r\n\r\n    // Display placeholder contents for the Document\r\n    static void DisplayContents(MyDocument* doc)\r\n    {\r\n        ImGui::PushID(doc);\r\n        ImGui::Text(\"Document \\\"%s\\\"\", doc->Name);\r\n        ImGui::PushStyleColor(ImGuiCol_Text, doc->Color);\r\n        ImGui::TextWrapped(\"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\");\r\n        ImGui::PopStyleColor();\r\n        if (ImGui::Button(\"Modify\", ImVec2(100, 0)))\r\n            doc->Dirty = true;\r\n        ImGui::SameLine();\r\n        if (ImGui::Button(\"Save\", ImVec2(100, 0)))\r\n            doc->DoSave();\r\n        ImGui::ColorEdit3(\"color\", &doc->Color.x);  // Useful to test drag and drop and hold-dragged-to-open-tab behavior.\r\n        ImGui::PopID();\r\n    }\r\n\r\n    // Display context menu for the Document\r\n    static void DisplayContextMenu(MyDocument* doc)\r\n    {\r\n        if (!ImGui::BeginPopupContextItem())\r\n            return;\r\n\r\n        char buf[256];\r\n        sprintf(buf, \"Save %s\", doc->Name);\r\n        if (ImGui::MenuItem(buf, \"CTRL+S\", false, doc->Open))\r\n            doc->DoSave();\r\n        if (ImGui::MenuItem(\"Close\", \"CTRL+W\", false, doc->Open))\r\n            doc->DoQueueClose();\r\n        ImGui::EndPopup();\r\n    }\r\n};\r\n\r\nstruct ExampleAppDocuments\r\n{\r\n    ImVector<MyDocument> Documents;\r\n\r\n    ExampleAppDocuments()\r\n    {\r\n        Documents.push_back(MyDocument(\"Lettuce\",             true,  ImVec4(0.4f, 0.8f, 0.4f, 1.0f)));\r\n        Documents.push_back(MyDocument(\"Eggplant\",            true,  ImVec4(0.8f, 0.5f, 1.0f, 1.0f)));\r\n        Documents.push_back(MyDocument(\"Carrot\",              true,  ImVec4(1.0f, 0.8f, 0.5f, 1.0f)));\r\n        Documents.push_back(MyDocument(\"Tomato\",              false, ImVec4(1.0f, 0.3f, 0.4f, 1.0f)));\r\n        Documents.push_back(MyDocument(\"A Rather Long Title\", false));\r\n        Documents.push_back(MyDocument(\"Some Document\",       false));\r\n    }\r\n};\r\n\r\n// [Optional] Notify the system of Tabs/Windows closure that happened outside the regular tab interface.\r\n// If a tab has been closed programmatically (aka closed from another source such as the Checkbox() in the demo,\r\n// as opposed to clicking on the regular tab closing button) and stops being submitted, it will take a frame for\r\n// the tab bar to notice its absence. During this frame there will be a gap in the tab bar, and if the tab that has\r\n// disappeared was the selected one, the tab bar will report no selected tab during the frame. This will effectively\r\n// give the impression of a flicker for one frame.\r\n// We call SetTabItemClosed() to manually notify the Tab Bar or Docking system of removed tabs to avoid this glitch.\r\n// Note that this completely optional, and only affect tab bars with the ImGuiTabBarFlags_Reorderable flag.\r\nstatic void NotifyOfDocumentsClosedElsewhere(ExampleAppDocuments& app)\r\n{\r\n    for (int doc_n = 0; doc_n < app.Documents.Size; doc_n++)\r\n    {\r\n        MyDocument* doc = &app.Documents[doc_n];\r\n        if (!doc->Open && doc->OpenPrev)\r\n            ImGui::SetTabItemClosed(doc->Name);\r\n        doc->OpenPrev = doc->Open;\r\n    }\r\n}\r\n\r\nvoid ShowExampleAppDocuments(bool* p_open)\r\n{\r\n    static ExampleAppDocuments app;\r\n\r\n    // Options\r\n    static bool opt_reorderable = true;\r\n    static ImGuiTabBarFlags opt_fitting_flags = ImGuiTabBarFlags_FittingPolicyDefault_;\r\n\r\n    bool window_contents_visible = ImGui::Begin(\"Example: Documents\", p_open, ImGuiWindowFlags_MenuBar);\r\n    if (!window_contents_visible)\r\n    {\r\n        ImGui::End();\r\n        return;\r\n    }\r\n\r\n    // Menu\r\n    if (ImGui::BeginMenuBar())\r\n    {\r\n        if (ImGui::BeginMenu(\"File\"))\r\n        {\r\n            int open_count = 0;\r\n            for (int doc_n = 0; doc_n < app.Documents.Size; doc_n++)\r\n                open_count += app.Documents[doc_n].Open ? 1 : 0;\r\n\r\n            if (ImGui::BeginMenu(\"Open\", open_count < app.Documents.Size))\r\n            {\r\n                for (int doc_n = 0; doc_n < app.Documents.Size; doc_n++)\r\n                {\r\n                    MyDocument* doc = &app.Documents[doc_n];\r\n                    if (!doc->Open)\r\n                        if (ImGui::MenuItem(doc->Name))\r\n                            doc->DoOpen();\r\n                }\r\n                ImGui::EndMenu();\r\n            }\r\n            if (ImGui::MenuItem(\"Close All Documents\", NULL, false, open_count > 0))\r\n                for (int doc_n = 0; doc_n < app.Documents.Size; doc_n++)\r\n                    app.Documents[doc_n].DoQueueClose();\r\n            if (ImGui::MenuItem(\"Exit\", \"Alt+F4\")) {}\r\n            ImGui::EndMenu();\r\n        }\r\n        ImGui::EndMenuBar();\r\n    }\r\n\r\n    // [Debug] List documents with one checkbox for each\r\n    for (int doc_n = 0; doc_n < app.Documents.Size; doc_n++)\r\n    {\r\n        MyDocument* doc = &app.Documents[doc_n];\r\n        if (doc_n > 0)\r\n            ImGui::SameLine();\r\n        ImGui::PushID(doc);\r\n        if (ImGui::Checkbox(doc->Name, &doc->Open))\r\n            if (!doc->Open)\r\n                doc->DoForceClose();\r\n        ImGui::PopID();\r\n    }\r\n\r\n    ImGui::Separator();\r\n\r\n    // About the ImGuiWindowFlags_UnsavedDocument / ImGuiTabItemFlags_UnsavedDocument flags.\r\n    // They have multiple effects:\r\n    // - Display a dot next to the title.\r\n    // - Tab is selected when clicking the X close button.\r\n    // - Closure is not assumed (will wait for user to stop submitting the tab).\r\n    //   Otherwise closure is assumed when pressing the X, so if you keep submitting the tab may reappear at end of tab bar.\r\n    //   We need to assume closure by default otherwise waiting for \"lack of submission\" on the next frame would leave an empty\r\n    //   hole for one-frame, both in the tab-bar and in tab-contents when closing a tab/window.\r\n    //   The rarely used SetTabItemClosed() function is a way to notify of programmatic closure to avoid the one-frame hole.\r\n\r\n    // Submit Tab Bar and Tabs\r\n    {\r\n        ImGuiTabBarFlags tab_bar_flags = (opt_fitting_flags) | (opt_reorderable ? ImGuiTabBarFlags_Reorderable : 0);\r\n        if (ImGui::BeginTabBar(\"##tabs\", tab_bar_flags))\r\n        {\r\n            if (opt_reorderable)\r\n                NotifyOfDocumentsClosedElsewhere(app);\r\n\r\n            // [DEBUG] Stress tests\r\n            //if ((ImGui::GetFrameCount() % 30) == 0) docs[1].Open ^= 1;            // [DEBUG] Automatically show/hide a tab. Test various interactions e.g. dragging with this on.\r\n            //if (ImGui::GetIO().KeyCtrl) ImGui::SetTabItemSelected(docs[1].Name);  // [DEBUG] Test SetTabItemSelected(), probably not very useful as-is anyway..\r\n\r\n            // Submit Tabs\r\n            for (int doc_n = 0; doc_n < app.Documents.Size; doc_n++)\r\n            {\r\n                MyDocument* doc = &app.Documents[doc_n];\r\n                if (!doc->Open)\r\n                    continue;\r\n\r\n                ImGuiTabItemFlags tab_flags = (doc->Dirty ? ImGuiTabItemFlags_UnsavedDocument : 0);\r\n                bool visible = ImGui::BeginTabItem(doc->Name, &doc->Open, tab_flags);\r\n\r\n                // Cancel attempt to close when unsaved add to save queue so we can display a popup.\r\n                if (!doc->Open && doc->Dirty)\r\n                {\r\n                    doc->Open = true;\r\n                    doc->DoQueueClose();\r\n                }\r\n\r\n                MyDocument::DisplayContextMenu(doc);\r\n                if (visible)\r\n                {\r\n                    MyDocument::DisplayContents(doc);\r\n                    ImGui::EndTabItem();\r\n                }\r\n            }\r\n\r\n            ImGui::EndTabBar();\r\n        }\r\n    }\r\n\r\n    // Update closing queue\r\n    static ImVector<MyDocument*> close_queue;\r\n    if (close_queue.empty())\r\n    {\r\n        // Close queue is locked once we started a popup\r\n        for (int doc_n = 0; doc_n < app.Documents.Size; doc_n++)\r\n        {\r\n            MyDocument* doc = &app.Documents[doc_n];\r\n            if (doc->WantClose)\r\n            {\r\n                doc->WantClose = false;\r\n                close_queue.push_back(doc);\r\n            }\r\n        }\r\n    }\r\n\r\n    // Display closing confirmation UI\r\n    if (!close_queue.empty())\r\n    {\r\n        int close_queue_unsaved_documents = 0;\r\n        for (int n = 0; n < close_queue.Size; n++)\r\n            if (close_queue[n]->Dirty)\r\n                close_queue_unsaved_documents++;\r\n\r\n        if (close_queue_unsaved_documents == 0)\r\n        {\r\n            // Close documents when all are unsaved\r\n            for (int n = 0; n < close_queue.Size; n++)\r\n                close_queue[n]->DoForceClose();\r\n            close_queue.clear();\r\n        }\r\n        else\r\n        {\r\n            if (!ImGui::IsPopupOpen(\"Save?\"))\r\n                ImGui::OpenPopup(\"Save?\");\r\n            if (ImGui::BeginPopupModal(\"Save?\", NULL, ImGuiWindowFlags_AlwaysAutoResize))\r\n            {\r\n                ImGui::Text(\"Save change to the following items?\");\r\n                float item_height = ImGui::GetTextLineHeightWithSpacing();\r\n                if (ImGui::BeginChildFrame(ImGui::GetID(\"frame\"), ImVec2(-FLT_MIN, 6.25f * item_height)))\r\n                {\r\n                    for (int n = 0; n < close_queue.Size; n++)\r\n                        if (close_queue[n]->Dirty)\r\n                            ImGui::Text(\"%s\", close_queue[n]->Name);\r\n                    ImGui::EndChildFrame();\r\n                }\r\n\r\n                ImVec2 button_size(ImGui::GetFontSize() * 7.0f, 0.0f);\r\n                if (ImGui::Button(\"Yes\", button_size))\r\n                {\r\n                    for (int n = 0; n < close_queue.Size; n++)\r\n                    {\r\n                        if (close_queue[n]->Dirty)\r\n                            close_queue[n]->DoSave();\r\n                        close_queue[n]->DoForceClose();\r\n                    }\r\n                    close_queue.clear();\r\n                    ImGui::CloseCurrentPopup();\r\n                }\r\n                ImGui::SameLine();\r\n                if (ImGui::Button(\"No\", button_size))\r\n                {\r\n                    for (int n = 0; n < close_queue.Size; n++)\r\n                        close_queue[n]->DoForceClose();\r\n                    close_queue.clear();\r\n                    ImGui::CloseCurrentPopup();\r\n                }\r\n                ImGui::SameLine();\r\n                if (ImGui::Button(\"Cancel\", button_size))\r\n                {\r\n                    close_queue.clear();\r\n                    ImGui::CloseCurrentPopup();\r\n                }\r\n                ImGui::EndPopup();\r\n            }\r\n        }\r\n    }\r\n\r\n    ImGui::End();\r\n}\r\n\r\n// End of Demo code\r\n#else\r\n\r\nvoid ImGui::ShowAboutWindow(bool*) {}\r\nvoid ImGui::ShowDemoWindow(bool*) {}\r\nvoid ImGui::ShowUserGuide() {}\r\nvoid ImGui::ShowStyleEditor(ImGuiStyle*) {}\r\n\r\n#endif\r\n\r\n#endif // #ifndef IMGUI_DISABLE\r\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/imgui/imgui_draw.cpp",
    "content": "// dear imgui, v1.87 WIP\r\n// (drawing and font code)\r\n\r\n/*\r\n\r\nIndex of this file:\r\n\r\n// [SECTION] STB libraries implementation\r\n// [SECTION] Style functions\r\n// [SECTION] ImDrawList\r\n// [SECTION] ImDrawListSplitter\r\n// [SECTION] ImDrawData\r\n// [SECTION] Helpers ShadeVertsXXX functions\r\n// [SECTION] ImFontConfig\r\n// [SECTION] ImFontAtlas\r\n// [SECTION] ImFontAtlas glyph ranges helpers\r\n// [SECTION] ImFontGlyphRangesBuilder\r\n// [SECTION] ImFont\r\n// [SECTION] ImGui Internal Render Helpers\r\n// [SECTION] Decompression code\r\n// [SECTION] Default font data (ProggyClean.ttf)\r\n\r\n*/\r\n\r\n#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)\r\n#define _CRT_SECURE_NO_WARNINGS\r\n#endif\r\n\r\n#include \"imgui.h\"\r\n#ifndef IMGUI_DISABLE\r\n\r\n#ifndef IMGUI_DEFINE_MATH_OPERATORS\r\n#define IMGUI_DEFINE_MATH_OPERATORS\r\n#endif\r\n\r\n#include \"imgui_internal.h\"\r\n#ifdef IMGUI_ENABLE_FREETYPE\r\n#include \"misc/freetype/imgui_freetype.h\"\r\n#endif\r\n\r\n#include <stdio.h>      // vsnprintf, sscanf, printf\r\n#if !defined(alloca)\r\n#if defined(__GLIBC__) || defined(__sun) || defined(__APPLE__) || defined(__NEWLIB__)\r\n#include <alloca.h>     // alloca (glibc uses <alloca.h>. Note that Cygwin may have _WIN32 defined, so the order matters here)\r\n#elif defined(_WIN32)\r\n#include <malloc.h>     // alloca\r\n#if !defined(alloca)\r\n#define alloca _alloca  // for clang with MS Codegen\r\n#endif\r\n#else\r\n#include <stdlib.h>     // alloca\r\n#endif\r\n#endif\r\n\r\n// Visual Studio warnings\r\n#ifdef _MSC_VER\r\n#pragma warning (disable: 4127)     // condition expression is constant\r\n#pragma warning (disable: 4505)     // unreferenced local function has been removed (stb stuff)\r\n#pragma warning (disable: 4996)     // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen\r\n#pragma warning (disable: 6255)     // [Static Analyzer] _alloca indicates failure by raising a stack overflow exception.  Consider using _malloca instead.\r\n#pragma warning (disable: 26451)    // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to a 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2).\r\n#pragma warning (disable: 26812)    // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3). [MSVC Static Analyzer)\r\n#endif\r\n\r\n// Clang/GCC warnings with -Weverything\r\n#if defined(__clang__)\r\n#if __has_warning(\"-Wunknown-warning-option\")\r\n#pragma clang diagnostic ignored \"-Wunknown-warning-option\"         // warning: unknown warning group 'xxx'                      // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great!\r\n#endif\r\n#if __has_warning(\"-Walloca\")\r\n#pragma clang diagnostic ignored \"-Walloca\"                         // warning: use of function '__builtin_alloca' is discouraged\r\n#endif\r\n#pragma clang diagnostic ignored \"-Wunknown-pragmas\"                // warning: unknown warning group 'xxx'\r\n#pragma clang diagnostic ignored \"-Wold-style-cast\"                 // warning: use of old-style cast                            // yes, they are more terse.\r\n#pragma clang diagnostic ignored \"-Wfloat-equal\"                    // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants ok.\r\n#pragma clang diagnostic ignored \"-Wglobal-constructors\"            // warning: declaration requires a global destructor         // similar to above, not sure what the exact difference is.\r\n#pragma clang diagnostic ignored \"-Wsign-conversion\"                // warning: implicit conversion changes signedness\r\n#pragma clang diagnostic ignored \"-Wzero-as-null-pointer-constant\"  // warning: zero as null pointer constant                    // some standard header variations use #define NULL 0\r\n#pragma clang diagnostic ignored \"-Wcomma\"                          // warning: possible misuse of comma operator here\r\n#pragma clang diagnostic ignored \"-Wreserved-id-macro\"              // warning: macro name is a reserved identifier\r\n#pragma clang diagnostic ignored \"-Wdouble-promotion\"               // warning: implicit conversion from 'float' to 'double' when passing argument to function  // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.\r\n#pragma clang diagnostic ignored \"-Wimplicit-int-float-conversion\"  // warning: implicit conversion from 'xxx' to 'float' may lose precision\r\n#elif defined(__GNUC__)\r\n#pragma GCC diagnostic ignored \"-Wpragmas\"                  // warning: unknown option after '#pragma GCC diagnostic' kind\r\n#pragma GCC diagnostic ignored \"-Wunused-function\"          // warning: 'xxxx' defined but not used\r\n#pragma GCC diagnostic ignored \"-Wdouble-promotion\"         // warning: implicit conversion from 'float' to 'double' when passing argument to function\r\n#pragma GCC diagnostic ignored \"-Wconversion\"               // warning: conversion to 'xxxx' from 'xxxx' may alter its value\r\n#pragma GCC diagnostic ignored \"-Wstack-protector\"          // warning: stack protector not protecting local variables: variable length buffer\r\n#pragma GCC diagnostic ignored \"-Wclass-memaccess\"          // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead\r\n#endif\r\n\r\n//-------------------------------------------------------------------------\r\n// [SECTION] STB libraries implementation\r\n//-------------------------------------------------------------------------\r\n\r\n// Compile time options:\r\n//#define IMGUI_STB_NAMESPACE           ImStb\r\n//#define IMGUI_STB_TRUETYPE_FILENAME   \"my_folder/stb_truetype.h\"\r\n//#define IMGUI_STB_RECT_PACK_FILENAME  \"my_folder/stb_rect_pack.h\"\r\n//#define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION\r\n//#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION\r\n\r\n#ifdef IMGUI_STB_NAMESPACE\r\nnamespace IMGUI_STB_NAMESPACE\r\n{\r\n#endif\r\n\r\n#ifdef _MSC_VER\r\n#pragma warning (push)\r\n#pragma warning (disable: 4456)                             // declaration of 'xx' hides previous local declaration\r\n#pragma warning (disable: 6011)                             // (stb_rectpack) Dereferencing NULL pointer 'cur->next'.\r\n#pragma warning (disable: 6385)                             // (stb_truetype) Reading invalid data from 'buffer':  the readable size is '_Old_3`kernel_width' bytes, but '3' bytes may be read.\r\n#pragma warning (disable: 28182)                            // (stb_rectpack) Dereferencing NULL pointer. 'cur' contains the same NULL value as 'cur->next' did.\r\n#endif\r\n\r\n#if defined(__clang__)\r\n#pragma clang diagnostic push\r\n#pragma clang diagnostic ignored \"-Wunused-function\"\r\n#pragma clang diagnostic ignored \"-Wmissing-prototypes\"\r\n#pragma clang diagnostic ignored \"-Wimplicit-fallthrough\"\r\n#pragma clang diagnostic ignored \"-Wcast-qual\"              // warning: cast from 'const xxxx *' to 'xxx *' drops const qualifier\r\n#endif\r\n\r\n#if defined(__GNUC__)\r\n#pragma GCC diagnostic push\r\n#pragma GCC diagnostic ignored \"-Wtype-limits\"              // warning: comparison is always true due to limited range of data type [-Wtype-limits]\r\n#pragma GCC diagnostic ignored \"-Wcast-qual\"                // warning: cast from type 'const xxxx *' to type 'xxxx *' casts away qualifiers\r\n#endif\r\n\r\n#ifndef STB_RECT_PACK_IMPLEMENTATION                        // in case the user already have an implementation in the _same_ compilation unit (e.g. unity builds)\r\n#ifndef IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION          // in case the user already have an implementation in another compilation unit\r\n#define STBRP_STATIC\r\n#define STBRP_ASSERT(x)     do { IM_ASSERT(x); } while (0)\r\n#define STBRP_SORT          ImQsort\r\n#define STB_RECT_PACK_IMPLEMENTATION\r\n#endif\r\n#ifdef IMGUI_STB_RECT_PACK_FILENAME\r\n#include IMGUI_STB_RECT_PACK_FILENAME\r\n#else\r\n#include \"imstb_rectpack.h\"\r\n#endif\r\n#endif\r\n\r\n#ifdef  IMGUI_ENABLE_STB_TRUETYPE\r\n#ifndef STB_TRUETYPE_IMPLEMENTATION                         // in case the user already have an implementation in the _same_ compilation unit (e.g. unity builds)\r\n#ifndef IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION           // in case the user already have an implementation in another compilation unit\r\n#define STBTT_malloc(x,u)   ((void)(u), IM_ALLOC(x))\r\n#define STBTT_free(x,u)     ((void)(u), IM_FREE(x))\r\n#define STBTT_assert(x)     do { IM_ASSERT(x); } while(0)\r\n#define STBTT_fmod(x,y)     ImFmod(x,y)\r\n#define STBTT_sqrt(x)       ImSqrt(x)\r\n#define STBTT_pow(x,y)      ImPow(x,y)\r\n#define STBTT_fabs(x)       ImFabs(x)\r\n#define STBTT_ifloor(x)     ((int)ImFloorSigned(x))\r\n#define STBTT_iceil(x)      ((int)ImCeil(x))\r\n#define STBTT_STATIC\r\n#define STB_TRUETYPE_IMPLEMENTATION\r\n#else\r\n#define STBTT_DEF extern\r\n#endif\r\n#ifdef IMGUI_STB_TRUETYPE_FILENAME\r\n#include IMGUI_STB_TRUETYPE_FILENAME\r\n#else\r\n#include \"imstb_truetype.h\"\r\n#endif\r\n#endif\r\n#endif // IMGUI_ENABLE_STB_TRUETYPE\r\n\r\n#if defined(__GNUC__)\r\n#pragma GCC diagnostic pop\r\n#endif\r\n\r\n#if defined(__clang__)\r\n#pragma clang diagnostic pop\r\n#endif\r\n\r\n#if defined(_MSC_VER)\r\n#pragma warning (pop)\r\n#endif\r\n\r\n#ifdef IMGUI_STB_NAMESPACE\r\n} // namespace ImStb\r\nusing namespace IMGUI_STB_NAMESPACE;\r\n#endif\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Style functions\r\n//-----------------------------------------------------------------------------\r\n\r\nvoid ImGui::StyleColorsDark(ImGuiStyle* dst)\r\n{\r\n    ImGuiStyle* style = dst ? dst : &ImGui::GetStyle();\r\n    ImVec4* colors = style->Colors;\r\n\r\n    colors[ImGuiCol_Text]                   = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);\r\n    colors[ImGuiCol_TextDisabled]           = ImVec4(0.50f, 0.50f, 0.50f, 1.00f);\r\n    colors[ImGuiCol_WindowBg]               = ImVec4(0.06f, 0.06f, 0.06f, 0.94f);\r\n    colors[ImGuiCol_ChildBg]                = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);\r\n    colors[ImGuiCol_PopupBg]                = ImVec4(0.08f, 0.08f, 0.08f, 0.94f);\r\n    colors[ImGuiCol_Border]                 = ImVec4(0.43f, 0.43f, 0.50f, 0.50f);\r\n    colors[ImGuiCol_BorderShadow]           = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);\r\n    colors[ImGuiCol_FrameBg]                = ImVec4(0.16f, 0.29f, 0.48f, 0.54f);\r\n    colors[ImGuiCol_FrameBgHovered]         = ImVec4(0.26f, 0.59f, 0.98f, 0.40f);\r\n    colors[ImGuiCol_FrameBgActive]          = ImVec4(0.26f, 0.59f, 0.98f, 0.67f);\r\n    colors[ImGuiCol_TitleBg]                = ImVec4(0.04f, 0.04f, 0.04f, 1.00f);\r\n    colors[ImGuiCol_TitleBgActive]          = ImVec4(0.16f, 0.29f, 0.48f, 1.00f);\r\n    colors[ImGuiCol_TitleBgCollapsed]       = ImVec4(0.00f, 0.00f, 0.00f, 0.51f);\r\n    colors[ImGuiCol_MenuBarBg]              = ImVec4(0.14f, 0.14f, 0.14f, 1.00f);\r\n    colors[ImGuiCol_ScrollbarBg]            = ImVec4(0.02f, 0.02f, 0.02f, 0.53f);\r\n    colors[ImGuiCol_ScrollbarGrab]          = ImVec4(0.31f, 0.31f, 0.31f, 1.00f);\r\n    colors[ImGuiCol_ScrollbarGrabHovered]   = ImVec4(0.41f, 0.41f, 0.41f, 1.00f);\r\n    colors[ImGuiCol_ScrollbarGrabActive]    = ImVec4(0.51f, 0.51f, 0.51f, 1.00f);\r\n    colors[ImGuiCol_CheckMark]              = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);\r\n    colors[ImGuiCol_SliderGrab]             = ImVec4(0.24f, 0.52f, 0.88f, 1.00f);\r\n    colors[ImGuiCol_SliderGrabActive]       = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);\r\n    colors[ImGuiCol_Button]                 = ImVec4(0.26f, 0.59f, 0.98f, 0.40f);\r\n    colors[ImGuiCol_ButtonHovered]          = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);\r\n    colors[ImGuiCol_ButtonActive]           = ImVec4(0.06f, 0.53f, 0.98f, 1.00f);\r\n    colors[ImGuiCol_Header]                 = ImVec4(0.26f, 0.59f, 0.98f, 0.31f);\r\n    colors[ImGuiCol_HeaderHovered]          = ImVec4(0.26f, 0.59f, 0.98f, 0.80f);\r\n    colors[ImGuiCol_HeaderActive]           = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);\r\n    colors[ImGuiCol_Separator]              = colors[ImGuiCol_Border];\r\n    colors[ImGuiCol_SeparatorHovered]       = ImVec4(0.10f, 0.40f, 0.75f, 0.78f);\r\n    colors[ImGuiCol_SeparatorActive]        = ImVec4(0.10f, 0.40f, 0.75f, 1.00f);\r\n    colors[ImGuiCol_ResizeGrip]             = ImVec4(0.26f, 0.59f, 0.98f, 0.20f);\r\n    colors[ImGuiCol_ResizeGripHovered]      = ImVec4(0.26f, 0.59f, 0.98f, 0.67f);\r\n    colors[ImGuiCol_ResizeGripActive]       = ImVec4(0.26f, 0.59f, 0.98f, 0.95f);\r\n    colors[ImGuiCol_Tab]                    = ImLerp(colors[ImGuiCol_Header],       colors[ImGuiCol_TitleBgActive], 0.80f);\r\n    colors[ImGuiCol_TabHovered]             = colors[ImGuiCol_HeaderHovered];\r\n    colors[ImGuiCol_TabActive]              = ImLerp(colors[ImGuiCol_HeaderActive], colors[ImGuiCol_TitleBgActive], 0.60f);\r\n    colors[ImGuiCol_TabUnfocused]           = ImLerp(colors[ImGuiCol_Tab],          colors[ImGuiCol_TitleBg], 0.80f);\r\n    colors[ImGuiCol_TabUnfocusedActive]     = ImLerp(colors[ImGuiCol_TabActive],    colors[ImGuiCol_TitleBg], 0.40f);\r\n    colors[ImGuiCol_PlotLines]              = ImVec4(0.61f, 0.61f, 0.61f, 1.00f);\r\n    colors[ImGuiCol_PlotLinesHovered]       = ImVec4(1.00f, 0.43f, 0.35f, 1.00f);\r\n    colors[ImGuiCol_PlotHistogram]          = ImVec4(0.90f, 0.70f, 0.00f, 1.00f);\r\n    colors[ImGuiCol_PlotHistogramHovered]   = ImVec4(1.00f, 0.60f, 0.00f, 1.00f);\r\n    colors[ImGuiCol_TableHeaderBg]          = ImVec4(0.19f, 0.19f, 0.20f, 1.00f);\r\n    colors[ImGuiCol_TableBorderStrong]      = ImVec4(0.31f, 0.31f, 0.35f, 1.00f);   // Prefer using Alpha=1.0 here\r\n    colors[ImGuiCol_TableBorderLight]       = ImVec4(0.23f, 0.23f, 0.25f, 1.00f);   // Prefer using Alpha=1.0 here\r\n    colors[ImGuiCol_TableRowBg]             = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);\r\n    colors[ImGuiCol_TableRowBgAlt]          = ImVec4(1.00f, 1.00f, 1.00f, 0.06f);\r\n    colors[ImGuiCol_TextSelectedBg]         = ImVec4(0.26f, 0.59f, 0.98f, 0.35f);\r\n    colors[ImGuiCol_DragDropTarget]         = ImVec4(1.00f, 1.00f, 0.00f, 0.90f);\r\n    colors[ImGuiCol_NavHighlight]           = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);\r\n    colors[ImGuiCol_NavWindowingHighlight]  = ImVec4(1.00f, 1.00f, 1.00f, 0.70f);\r\n    colors[ImGuiCol_NavWindowingDimBg]      = ImVec4(0.80f, 0.80f, 0.80f, 0.20f);\r\n    colors[ImGuiCol_ModalWindowDimBg]       = ImVec4(0.80f, 0.80f, 0.80f, 0.35f);\r\n}\r\n\r\nvoid ImGui::StyleColorsClassic(ImGuiStyle* dst)\r\n{\r\n    ImGuiStyle* style = dst ? dst : &ImGui::GetStyle();\r\n    ImVec4* colors = style->Colors;\r\n\r\n    colors[ImGuiCol_Text]                   = ImVec4(0.90f, 0.90f, 0.90f, 1.00f);\r\n    colors[ImGuiCol_TextDisabled]           = ImVec4(0.60f, 0.60f, 0.60f, 1.00f);\r\n    colors[ImGuiCol_WindowBg]               = ImVec4(0.00f, 0.00f, 0.00f, 0.85f);\r\n    colors[ImGuiCol_ChildBg]                = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);\r\n    colors[ImGuiCol_PopupBg]                = ImVec4(0.11f, 0.11f, 0.14f, 0.92f);\r\n    colors[ImGuiCol_Border]                 = ImVec4(0.50f, 0.50f, 0.50f, 0.50f);\r\n    colors[ImGuiCol_BorderShadow]           = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);\r\n    colors[ImGuiCol_FrameBg]                = ImVec4(0.43f, 0.43f, 0.43f, 0.39f);\r\n    colors[ImGuiCol_FrameBgHovered]         = ImVec4(0.47f, 0.47f, 0.69f, 0.40f);\r\n    colors[ImGuiCol_FrameBgActive]          = ImVec4(0.42f, 0.41f, 0.64f, 0.69f);\r\n    colors[ImGuiCol_TitleBg]                = ImVec4(0.27f, 0.27f, 0.54f, 0.83f);\r\n    colors[ImGuiCol_TitleBgActive]          = ImVec4(0.32f, 0.32f, 0.63f, 0.87f);\r\n    colors[ImGuiCol_TitleBgCollapsed]       = ImVec4(0.40f, 0.40f, 0.80f, 0.20f);\r\n    colors[ImGuiCol_MenuBarBg]              = ImVec4(0.40f, 0.40f, 0.55f, 0.80f);\r\n    colors[ImGuiCol_ScrollbarBg]            = ImVec4(0.20f, 0.25f, 0.30f, 0.60f);\r\n    colors[ImGuiCol_ScrollbarGrab]          = ImVec4(0.40f, 0.40f, 0.80f, 0.30f);\r\n    colors[ImGuiCol_ScrollbarGrabHovered]   = ImVec4(0.40f, 0.40f, 0.80f, 0.40f);\r\n    colors[ImGuiCol_ScrollbarGrabActive]    = ImVec4(0.41f, 0.39f, 0.80f, 0.60f);\r\n    colors[ImGuiCol_CheckMark]              = ImVec4(0.90f, 0.90f, 0.90f, 0.50f);\r\n    colors[ImGuiCol_SliderGrab]             = ImVec4(1.00f, 1.00f, 1.00f, 0.30f);\r\n    colors[ImGuiCol_SliderGrabActive]       = ImVec4(0.41f, 0.39f, 0.80f, 0.60f);\r\n    colors[ImGuiCol_Button]                 = ImVec4(0.35f, 0.40f, 0.61f, 0.62f);\r\n    colors[ImGuiCol_ButtonHovered]          = ImVec4(0.40f, 0.48f, 0.71f, 0.79f);\r\n    colors[ImGuiCol_ButtonActive]           = ImVec4(0.46f, 0.54f, 0.80f, 1.00f);\r\n    colors[ImGuiCol_Header]                 = ImVec4(0.40f, 0.40f, 0.90f, 0.45f);\r\n    colors[ImGuiCol_HeaderHovered]          = ImVec4(0.45f, 0.45f, 0.90f, 0.80f);\r\n    colors[ImGuiCol_HeaderActive]           = ImVec4(0.53f, 0.53f, 0.87f, 0.80f);\r\n    colors[ImGuiCol_Separator]              = ImVec4(0.50f, 0.50f, 0.50f, 0.60f);\r\n    colors[ImGuiCol_SeparatorHovered]       = ImVec4(0.60f, 0.60f, 0.70f, 1.00f);\r\n    colors[ImGuiCol_SeparatorActive]        = ImVec4(0.70f, 0.70f, 0.90f, 1.00f);\r\n    colors[ImGuiCol_ResizeGrip]             = ImVec4(1.00f, 1.00f, 1.00f, 0.10f);\r\n    colors[ImGuiCol_ResizeGripHovered]      = ImVec4(0.78f, 0.82f, 1.00f, 0.60f);\r\n    colors[ImGuiCol_ResizeGripActive]       = ImVec4(0.78f, 0.82f, 1.00f, 0.90f);\r\n    colors[ImGuiCol_Tab]                    = ImLerp(colors[ImGuiCol_Header],       colors[ImGuiCol_TitleBgActive], 0.80f);\r\n    colors[ImGuiCol_TabHovered]             = colors[ImGuiCol_HeaderHovered];\r\n    colors[ImGuiCol_TabActive]              = ImLerp(colors[ImGuiCol_HeaderActive], colors[ImGuiCol_TitleBgActive], 0.60f);\r\n    colors[ImGuiCol_TabUnfocused]           = ImLerp(colors[ImGuiCol_Tab],          colors[ImGuiCol_TitleBg], 0.80f);\r\n    colors[ImGuiCol_TabUnfocusedActive]     = ImLerp(colors[ImGuiCol_TabActive],    colors[ImGuiCol_TitleBg], 0.40f);\r\n    colors[ImGuiCol_PlotLines]              = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);\r\n    colors[ImGuiCol_PlotLinesHovered]       = ImVec4(0.90f, 0.70f, 0.00f, 1.00f);\r\n    colors[ImGuiCol_PlotHistogram]          = ImVec4(0.90f, 0.70f, 0.00f, 1.00f);\r\n    colors[ImGuiCol_PlotHistogramHovered]   = ImVec4(1.00f, 0.60f, 0.00f, 1.00f);\r\n    colors[ImGuiCol_TableHeaderBg]          = ImVec4(0.27f, 0.27f, 0.38f, 1.00f);\r\n    colors[ImGuiCol_TableBorderStrong]      = ImVec4(0.31f, 0.31f, 0.45f, 1.00f);   // Prefer using Alpha=1.0 here\r\n    colors[ImGuiCol_TableBorderLight]       = ImVec4(0.26f, 0.26f, 0.28f, 1.00f);   // Prefer using Alpha=1.0 here\r\n    colors[ImGuiCol_TableRowBg]             = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);\r\n    colors[ImGuiCol_TableRowBgAlt]          = ImVec4(1.00f, 1.00f, 1.00f, 0.07f);\r\n    colors[ImGuiCol_TextSelectedBg]         = ImVec4(0.00f, 0.00f, 1.00f, 0.35f);\r\n    colors[ImGuiCol_DragDropTarget]         = ImVec4(1.00f, 1.00f, 0.00f, 0.90f);\r\n    colors[ImGuiCol_NavHighlight]           = colors[ImGuiCol_HeaderHovered];\r\n    colors[ImGuiCol_NavWindowingHighlight]  = ImVec4(1.00f, 1.00f, 1.00f, 0.70f);\r\n    colors[ImGuiCol_NavWindowingDimBg]      = ImVec4(0.80f, 0.80f, 0.80f, 0.20f);\r\n    colors[ImGuiCol_ModalWindowDimBg]       = ImVec4(0.20f, 0.20f, 0.20f, 0.35f);\r\n}\r\n\r\n// Those light colors are better suited with a thicker font than the default one + FrameBorder\r\nvoid ImGui::StyleColorsLight(ImGuiStyle* dst)\r\n{\r\n    ImGuiStyle* style = dst ? dst : &ImGui::GetStyle();\r\n    ImVec4* colors = style->Colors;\r\n\r\n    colors[ImGuiCol_Text]                   = ImVec4(0.00f, 0.00f, 0.00f, 1.00f);\r\n    colors[ImGuiCol_TextDisabled]           = ImVec4(0.60f, 0.60f, 0.60f, 1.00f);\r\n    colors[ImGuiCol_WindowBg]               = ImVec4(0.94f, 0.94f, 0.94f, 1.00f);\r\n    colors[ImGuiCol_ChildBg]                = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);\r\n    colors[ImGuiCol_PopupBg]                = ImVec4(1.00f, 1.00f, 1.00f, 0.98f);\r\n    colors[ImGuiCol_Border]                 = ImVec4(0.00f, 0.00f, 0.00f, 0.30f);\r\n    colors[ImGuiCol_BorderShadow]           = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);\r\n    colors[ImGuiCol_FrameBg]                = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);\r\n    colors[ImGuiCol_FrameBgHovered]         = ImVec4(0.26f, 0.59f, 0.98f, 0.40f);\r\n    colors[ImGuiCol_FrameBgActive]          = ImVec4(0.26f, 0.59f, 0.98f, 0.67f);\r\n    colors[ImGuiCol_TitleBg]                = ImVec4(0.96f, 0.96f, 0.96f, 1.00f);\r\n    colors[ImGuiCol_TitleBgActive]          = ImVec4(0.82f, 0.82f, 0.82f, 1.00f);\r\n    colors[ImGuiCol_TitleBgCollapsed]       = ImVec4(1.00f, 1.00f, 1.00f, 0.51f);\r\n    colors[ImGuiCol_MenuBarBg]              = ImVec4(0.86f, 0.86f, 0.86f, 1.00f);\r\n    colors[ImGuiCol_ScrollbarBg]            = ImVec4(0.98f, 0.98f, 0.98f, 0.53f);\r\n    colors[ImGuiCol_ScrollbarGrab]          = ImVec4(0.69f, 0.69f, 0.69f, 0.80f);\r\n    colors[ImGuiCol_ScrollbarGrabHovered]   = ImVec4(0.49f, 0.49f, 0.49f, 0.80f);\r\n    colors[ImGuiCol_ScrollbarGrabActive]    = ImVec4(0.49f, 0.49f, 0.49f, 1.00f);\r\n    colors[ImGuiCol_CheckMark]              = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);\r\n    colors[ImGuiCol_SliderGrab]             = ImVec4(0.26f, 0.59f, 0.98f, 0.78f);\r\n    colors[ImGuiCol_SliderGrabActive]       = ImVec4(0.46f, 0.54f, 0.80f, 0.60f);\r\n    colors[ImGuiCol_Button]                 = ImVec4(0.26f, 0.59f, 0.98f, 0.40f);\r\n    colors[ImGuiCol_ButtonHovered]          = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);\r\n    colors[ImGuiCol_ButtonActive]           = ImVec4(0.06f, 0.53f, 0.98f, 1.00f);\r\n    colors[ImGuiCol_Header]                 = ImVec4(0.26f, 0.59f, 0.98f, 0.31f);\r\n    colors[ImGuiCol_HeaderHovered]          = ImVec4(0.26f, 0.59f, 0.98f, 0.80f);\r\n    colors[ImGuiCol_HeaderActive]           = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);\r\n    colors[ImGuiCol_Separator]              = ImVec4(0.39f, 0.39f, 0.39f, 0.62f);\r\n    colors[ImGuiCol_SeparatorHovered]       = ImVec4(0.14f, 0.44f, 0.80f, 0.78f);\r\n    colors[ImGuiCol_SeparatorActive]        = ImVec4(0.14f, 0.44f, 0.80f, 1.00f);\r\n    colors[ImGuiCol_ResizeGrip]             = ImVec4(0.35f, 0.35f, 0.35f, 0.17f);\r\n    colors[ImGuiCol_ResizeGripHovered]      = ImVec4(0.26f, 0.59f, 0.98f, 0.67f);\r\n    colors[ImGuiCol_ResizeGripActive]       = ImVec4(0.26f, 0.59f, 0.98f, 0.95f);\r\n    colors[ImGuiCol_Tab]                    = ImLerp(colors[ImGuiCol_Header],       colors[ImGuiCol_TitleBgActive], 0.90f);\r\n    colors[ImGuiCol_TabHovered]             = colors[ImGuiCol_HeaderHovered];\r\n    colors[ImGuiCol_TabActive]              = ImLerp(colors[ImGuiCol_HeaderActive], colors[ImGuiCol_TitleBgActive], 0.60f);\r\n    colors[ImGuiCol_TabUnfocused]           = ImLerp(colors[ImGuiCol_Tab],          colors[ImGuiCol_TitleBg], 0.80f);\r\n    colors[ImGuiCol_TabUnfocusedActive]     = ImLerp(colors[ImGuiCol_TabActive],    colors[ImGuiCol_TitleBg], 0.40f);\r\n    colors[ImGuiCol_PlotLines]              = ImVec4(0.39f, 0.39f, 0.39f, 1.00f);\r\n    colors[ImGuiCol_PlotLinesHovered]       = ImVec4(1.00f, 0.43f, 0.35f, 1.00f);\r\n    colors[ImGuiCol_PlotHistogram]          = ImVec4(0.90f, 0.70f, 0.00f, 1.00f);\r\n    colors[ImGuiCol_PlotHistogramHovered]   = ImVec4(1.00f, 0.45f, 0.00f, 1.00f);\r\n    colors[ImGuiCol_TableHeaderBg]          = ImVec4(0.78f, 0.87f, 0.98f, 1.00f);\r\n    colors[ImGuiCol_TableBorderStrong]      = ImVec4(0.57f, 0.57f, 0.64f, 1.00f);   // Prefer using Alpha=1.0 here\r\n    colors[ImGuiCol_TableBorderLight]       = ImVec4(0.68f, 0.68f, 0.74f, 1.00f);   // Prefer using Alpha=1.0 here\r\n    colors[ImGuiCol_TableRowBg]             = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);\r\n    colors[ImGuiCol_TableRowBgAlt]          = ImVec4(0.30f, 0.30f, 0.30f, 0.09f);\r\n    colors[ImGuiCol_TextSelectedBg]         = ImVec4(0.26f, 0.59f, 0.98f, 0.35f);\r\n    colors[ImGuiCol_DragDropTarget]         = ImVec4(0.26f, 0.59f, 0.98f, 0.95f);\r\n    colors[ImGuiCol_NavHighlight]           = colors[ImGuiCol_HeaderHovered];\r\n    colors[ImGuiCol_NavWindowingHighlight]  = ImVec4(0.70f, 0.70f, 0.70f, 0.70f);\r\n    colors[ImGuiCol_NavWindowingDimBg]      = ImVec4(0.20f, 0.20f, 0.20f, 0.20f);\r\n    colors[ImGuiCol_ModalWindowDimBg]       = ImVec4(0.20f, 0.20f, 0.20f, 0.35f);\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] ImDrawList\r\n//-----------------------------------------------------------------------------\r\n\r\nImDrawListSharedData::ImDrawListSharedData()\r\n{\r\n    memset(this, 0, sizeof(*this));\r\n    for (int i = 0; i < IM_ARRAYSIZE(ArcFastVtx); i++)\r\n    {\r\n        const float a = ((float)i * 2 * IM_PI) / (float)IM_ARRAYSIZE(ArcFastVtx);\r\n        ArcFastVtx[i] = ImVec2(ImCos(a), ImSin(a));\r\n    }\r\n    ArcFastRadiusCutoff = IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC_R(IM_DRAWLIST_ARCFAST_SAMPLE_MAX, CircleSegmentMaxError);\r\n}\r\n\r\nvoid ImDrawListSharedData::SetCircleTessellationMaxError(float max_error)\r\n{\r\n    if (CircleSegmentMaxError == max_error)\r\n        return;\r\n\r\n    IM_ASSERT(max_error > 0.0f);\r\n    CircleSegmentMaxError = max_error;\r\n    for (int i = 0; i < IM_ARRAYSIZE(CircleSegmentCounts); i++)\r\n    {\r\n        const float radius = (float)i;\r\n        CircleSegmentCounts[i] = (ImU8)((i > 0) ? IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(radius, CircleSegmentMaxError) : 0);\r\n    }\r\n    ArcFastRadiusCutoff = IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC_R(IM_DRAWLIST_ARCFAST_SAMPLE_MAX, CircleSegmentMaxError);\r\n}\r\n\r\n// Initialize before use in a new frame. We always have a command ready in the buffer.\r\nvoid ImDrawList::_ResetForNewFrame()\r\n{\r\n    // Verify that the ImDrawCmd fields we want to memcmp() are contiguous in memory.\r\n    IM_STATIC_ASSERT(IM_OFFSETOF(ImDrawCmd, ClipRect) == 0);\r\n    IM_STATIC_ASSERT(IM_OFFSETOF(ImDrawCmd, TextureId) == sizeof(ImVec4));\r\n    IM_STATIC_ASSERT(IM_OFFSETOF(ImDrawCmd, VtxOffset) == sizeof(ImVec4) + sizeof(ImTextureID));\r\n\r\n    CmdBuffer.resize(0);\r\n    IdxBuffer.resize(0);\r\n    VtxBuffer.resize(0);\r\n    Flags = _Data->InitialFlags;\r\n    memset(&_CmdHeader, 0, sizeof(_CmdHeader));\r\n    _VtxCurrentIdx = 0;\r\n    _VtxWritePtr = NULL;\r\n    _IdxWritePtr = NULL;\r\n    _ClipRectStack.resize(0);\r\n    _TextureIdStack.resize(0);\r\n    _Path.resize(0);\r\n    _Splitter.Clear();\r\n    CmdBuffer.push_back(ImDrawCmd());\r\n    _FringeScale = 1.0f;\r\n}\r\n\r\nvoid ImDrawList::_ClearFreeMemory()\r\n{\r\n    CmdBuffer.clear();\r\n    IdxBuffer.clear();\r\n    VtxBuffer.clear();\r\n    Flags = ImDrawListFlags_None;\r\n    _VtxCurrentIdx = 0;\r\n    _VtxWritePtr = NULL;\r\n    _IdxWritePtr = NULL;\r\n    _ClipRectStack.clear();\r\n    _TextureIdStack.clear();\r\n    _Path.clear();\r\n    _Splitter.ClearFreeMemory();\r\n}\r\n\r\nImDrawList* ImDrawList::CloneOutput() const\r\n{\r\n    ImDrawList* dst = IM_NEW(ImDrawList(_Data));\r\n    dst->CmdBuffer = CmdBuffer;\r\n    dst->IdxBuffer = IdxBuffer;\r\n    dst->VtxBuffer = VtxBuffer;\r\n    dst->Flags = Flags;\r\n    return dst;\r\n}\r\n\r\nvoid ImDrawList::AddDrawCmd()\r\n{\r\n    ImDrawCmd draw_cmd;\r\n    draw_cmd.ClipRect = _CmdHeader.ClipRect;    // Same as calling ImDrawCmd_HeaderCopy()\r\n    draw_cmd.TextureId = _CmdHeader.TextureId;\r\n    draw_cmd.VtxOffset = _CmdHeader.VtxOffset;\r\n    draw_cmd.IdxOffset = IdxBuffer.Size;\r\n\r\n    IM_ASSERT(draw_cmd.ClipRect.x <= draw_cmd.ClipRect.z && draw_cmd.ClipRect.y <= draw_cmd.ClipRect.w);\r\n    CmdBuffer.push_back(draw_cmd);\r\n}\r\n\r\n// Pop trailing draw command (used before merging or presenting to user)\r\n// Note that this leaves the ImDrawList in a state unfit for further commands, as most code assume that CmdBuffer.Size > 0 && CmdBuffer.back().UserCallback == NULL\r\nvoid ImDrawList::_PopUnusedDrawCmd()\r\n{\r\n    if (CmdBuffer.Size == 0)\r\n        return;\r\n    ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1];\r\n    if (curr_cmd->ElemCount == 0 && curr_cmd->UserCallback == NULL)\r\n        CmdBuffer.pop_back();\r\n}\r\n\r\nvoid ImDrawList::AddCallback(ImDrawCallback callback, void* callback_data)\r\n{\r\n    IM_ASSERT_PARANOID(CmdBuffer.Size > 0);\r\n    ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1];\r\n    IM_ASSERT(curr_cmd->UserCallback == NULL);\r\n    if (curr_cmd->ElemCount != 0)\r\n    {\r\n        AddDrawCmd();\r\n        curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1];\r\n    }\r\n    curr_cmd->UserCallback = callback;\r\n    curr_cmd->UserCallbackData = callback_data;\r\n\r\n    AddDrawCmd(); // Force a new command after us (see comment below)\r\n}\r\n\r\n// Compare ClipRect, TextureId and VtxOffset with a single memcmp()\r\n#define ImDrawCmd_HeaderSize                            (IM_OFFSETOF(ImDrawCmd, VtxOffset) + sizeof(unsigned int))\r\n#define ImDrawCmd_HeaderCompare(CMD_LHS, CMD_RHS)       (memcmp(CMD_LHS, CMD_RHS, ImDrawCmd_HeaderSize))    // Compare ClipRect, TextureId, VtxOffset\r\n#define ImDrawCmd_HeaderCopy(CMD_DST, CMD_SRC)          (memcpy(CMD_DST, CMD_SRC, ImDrawCmd_HeaderSize))    // Copy ClipRect, TextureId, VtxOffset\r\n#define ImDrawCmd_AreSequentialIdxOffset(CMD_0, CMD_1)  (CMD_0->IdxOffset + CMD_0->ElemCount == CMD_1->IdxOffset)\r\n\r\n// Try to merge two last draw commands\r\nvoid ImDrawList::_TryMergeDrawCmds()\r\n{\r\n    IM_ASSERT_PARANOID(CmdBuffer.Size > 0);\r\n    ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1];\r\n    ImDrawCmd* prev_cmd = curr_cmd - 1;\r\n    if (ImDrawCmd_HeaderCompare(curr_cmd, prev_cmd) == 0 && ImDrawCmd_AreSequentialIdxOffset(prev_cmd, curr_cmd) && curr_cmd->UserCallback == NULL && prev_cmd->UserCallback == NULL)\r\n    {\r\n        prev_cmd->ElemCount += curr_cmd->ElemCount;\r\n        CmdBuffer.pop_back();\r\n    }\r\n}\r\n\r\n// Our scheme may appears a bit unusual, basically we want the most-common calls AddLine AddRect etc. to not have to perform any check so we always have a command ready in the stack.\r\n// The cost of figuring out if a new command has to be added or if we can merge is paid in those Update** functions only.\r\nvoid ImDrawList::_OnChangedClipRect()\r\n{\r\n    // If current command is used with different settings we need to add a new command\r\n    IM_ASSERT_PARANOID(CmdBuffer.Size > 0);\r\n    ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1];\r\n    if (curr_cmd->ElemCount != 0 && memcmp(&curr_cmd->ClipRect, &_CmdHeader.ClipRect, sizeof(ImVec4)) != 0)\r\n    {\r\n        AddDrawCmd();\r\n        return;\r\n    }\r\n    IM_ASSERT(curr_cmd->UserCallback == NULL);\r\n\r\n    // Try to merge with previous command if it matches, else use current command\r\n    ImDrawCmd* prev_cmd = curr_cmd - 1;\r\n    if (curr_cmd->ElemCount == 0 && CmdBuffer.Size > 1 && ImDrawCmd_HeaderCompare(&_CmdHeader, prev_cmd) == 0 && ImDrawCmd_AreSequentialIdxOffset(prev_cmd, curr_cmd) && prev_cmd->UserCallback == NULL)\r\n    {\r\n        CmdBuffer.pop_back();\r\n        return;\r\n    }\r\n\r\n    curr_cmd->ClipRect = _CmdHeader.ClipRect;\r\n}\r\n\r\nvoid ImDrawList::_OnChangedTextureID()\r\n{\r\n    // If current command is used with different settings we need to add a new command\r\n    IM_ASSERT_PARANOID(CmdBuffer.Size > 0);\r\n    ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1];\r\n    if (curr_cmd->ElemCount != 0 && curr_cmd->TextureId != _CmdHeader.TextureId)\r\n    {\r\n        AddDrawCmd();\r\n        return;\r\n    }\r\n    IM_ASSERT(curr_cmd->UserCallback == NULL);\r\n\r\n    // Try to merge with previous command if it matches, else use current command\r\n    ImDrawCmd* prev_cmd = curr_cmd - 1;\r\n    if (curr_cmd->ElemCount == 0 && CmdBuffer.Size > 1 && ImDrawCmd_HeaderCompare(&_CmdHeader, prev_cmd) == 0 && ImDrawCmd_AreSequentialIdxOffset(prev_cmd, curr_cmd) && prev_cmd->UserCallback == NULL)\r\n    {\r\n        CmdBuffer.pop_back();\r\n        return;\r\n    }\r\n\r\n    curr_cmd->TextureId = _CmdHeader.TextureId;\r\n}\r\n\r\nvoid ImDrawList::_OnChangedVtxOffset()\r\n{\r\n    // We don't need to compare curr_cmd->VtxOffset != _CmdHeader.VtxOffset because we know it'll be different at the time we call this.\r\n    _VtxCurrentIdx = 0;\r\n    IM_ASSERT_PARANOID(CmdBuffer.Size > 0);\r\n    ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1];\r\n    //IM_ASSERT(curr_cmd->VtxOffset != _CmdHeader.VtxOffset); // See #3349\r\n    if (curr_cmd->ElemCount != 0)\r\n    {\r\n        AddDrawCmd();\r\n        return;\r\n    }\r\n    IM_ASSERT(curr_cmd->UserCallback == NULL);\r\n    curr_cmd->VtxOffset = _CmdHeader.VtxOffset;\r\n}\r\n\r\nint ImDrawList::_CalcCircleAutoSegmentCount(float radius) const\r\n{\r\n    // Automatic segment count\r\n    const int radius_idx = (int)(radius + 0.999999f); // ceil to never reduce accuracy\r\n    if (radius_idx < IM_ARRAYSIZE(_Data->CircleSegmentCounts))\r\n        return _Data->CircleSegmentCounts[radius_idx]; // Use cached value\r\n    else\r\n        return IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(radius, _Data->CircleSegmentMaxError);\r\n}\r\n\r\n// Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui::PushClipRect() to affect logic (hit-testing and widget culling)\r\nvoid ImDrawList::PushClipRect(ImVec2 cr_min, ImVec2 cr_max, bool intersect_with_current_clip_rect)\r\n{\r\n    ImVec4 cr(cr_min.x, cr_min.y, cr_max.x, cr_max.y);\r\n    if (intersect_with_current_clip_rect)\r\n    {\r\n        ImVec4 current = _CmdHeader.ClipRect;\r\n        if (cr.x < current.x) cr.x = current.x;\r\n        if (cr.y < current.y) cr.y = current.y;\r\n        if (cr.z > current.z) cr.z = current.z;\r\n        if (cr.w > current.w) cr.w = current.w;\r\n    }\r\n    cr.z = ImMax(cr.x, cr.z);\r\n    cr.w = ImMax(cr.y, cr.w);\r\n\r\n    _ClipRectStack.push_back(cr);\r\n    _CmdHeader.ClipRect = cr;\r\n    _OnChangedClipRect();\r\n}\r\n\r\nvoid ImDrawList::PushClipRectFullScreen()\r\n{\r\n    PushClipRect(ImVec2(_Data->ClipRectFullscreen.x, _Data->ClipRectFullscreen.y), ImVec2(_Data->ClipRectFullscreen.z, _Data->ClipRectFullscreen.w));\r\n}\r\n\r\nvoid ImDrawList::PopClipRect()\r\n{\r\n    _ClipRectStack.pop_back();\r\n    _CmdHeader.ClipRect = (_ClipRectStack.Size == 0) ? _Data->ClipRectFullscreen : _ClipRectStack.Data[_ClipRectStack.Size - 1];\r\n    _OnChangedClipRect();\r\n}\r\n\r\nvoid ImDrawList::PushTextureID(ImTextureID texture_id)\r\n{\r\n    _TextureIdStack.push_back(texture_id);\r\n    _CmdHeader.TextureId = texture_id;\r\n    _OnChangedTextureID();\r\n}\r\n\r\nvoid ImDrawList::PopTextureID()\r\n{\r\n    _TextureIdStack.pop_back();\r\n    _CmdHeader.TextureId = (_TextureIdStack.Size == 0) ? (ImTextureID)NULL : _TextureIdStack.Data[_TextureIdStack.Size - 1];\r\n    _OnChangedTextureID();\r\n}\r\n\r\n// Reserve space for a number of vertices and indices.\r\n// You must finish filling your reserved data before calling PrimReserve() again, as it may reallocate or\r\n// submit the intermediate results. PrimUnreserve() can be used to release unused allocations.\r\nvoid ImDrawList::PrimReserve(int idx_count, int vtx_count)\r\n{\r\n    // Large mesh support (when enabled)\r\n    IM_ASSERT_PARANOID(idx_count >= 0 && vtx_count >= 0);\r\n    if (sizeof(ImDrawIdx) == 2 && (_VtxCurrentIdx + vtx_count >= (1 << 16)) && (Flags & ImDrawListFlags_AllowVtxOffset))\r\n    {\r\n        // FIXME: In theory we should be testing that vtx_count <64k here.\r\n        // In practice, RenderText() relies on reserving ahead for a worst case scenario so it is currently useful for us\r\n        // to not make that check until we rework the text functions to handle clipping and large horizontal lines better.\r\n        _CmdHeader.VtxOffset = VtxBuffer.Size;\r\n        _OnChangedVtxOffset();\r\n    }\r\n\r\n    ImDrawCmd* draw_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1];\r\n    draw_cmd->ElemCount += idx_count;\r\n\r\n    int vtx_buffer_old_size = VtxBuffer.Size;\r\n    VtxBuffer.resize(vtx_buffer_old_size + vtx_count);\r\n    _VtxWritePtr = VtxBuffer.Data + vtx_buffer_old_size;\r\n\r\n    int idx_buffer_old_size = IdxBuffer.Size;\r\n    IdxBuffer.resize(idx_buffer_old_size + idx_count);\r\n    _IdxWritePtr = IdxBuffer.Data + idx_buffer_old_size;\r\n}\r\n\r\n// Release the a number of reserved vertices/indices from the end of the last reservation made with PrimReserve().\r\nvoid ImDrawList::PrimUnreserve(int idx_count, int vtx_count)\r\n{\r\n    IM_ASSERT_PARANOID(idx_count >= 0 && vtx_count >= 0);\r\n\r\n    ImDrawCmd* draw_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1];\r\n    draw_cmd->ElemCount -= idx_count;\r\n    VtxBuffer.shrink(VtxBuffer.Size - vtx_count);\r\n    IdxBuffer.shrink(IdxBuffer.Size - idx_count);\r\n}\r\n\r\n// Fully unrolled with inline call to keep our debug builds decently fast.\r\nvoid ImDrawList::PrimRect(const ImVec2& a, const ImVec2& c, ImU32 col)\r\n{\r\n    ImVec2 b(c.x, a.y), d(a.x, c.y), uv(_Data->TexUvWhitePixel);\r\n    ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx;\r\n    _IdxWritePtr[0] = idx; _IdxWritePtr[1] = (ImDrawIdx)(idx+1); _IdxWritePtr[2] = (ImDrawIdx)(idx+2);\r\n    _IdxWritePtr[3] = idx; _IdxWritePtr[4] = (ImDrawIdx)(idx+2); _IdxWritePtr[5] = (ImDrawIdx)(idx+3);\r\n    _VtxWritePtr[0].pos = a; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col;\r\n    _VtxWritePtr[1].pos = b; _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col;\r\n    _VtxWritePtr[2].pos = c; _VtxWritePtr[2].uv = uv; _VtxWritePtr[2].col = col;\r\n    _VtxWritePtr[3].pos = d; _VtxWritePtr[3].uv = uv; _VtxWritePtr[3].col = col;\r\n    _VtxWritePtr += 4;\r\n    _VtxCurrentIdx += 4;\r\n    _IdxWritePtr += 6;\r\n}\r\n\r\nvoid ImDrawList::PrimRectUV(const ImVec2& a, const ImVec2& c, const ImVec2& uv_a, const ImVec2& uv_c, ImU32 col)\r\n{\r\n    ImVec2 b(c.x, a.y), d(a.x, c.y), uv_b(uv_c.x, uv_a.y), uv_d(uv_a.x, uv_c.y);\r\n    ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx;\r\n    _IdxWritePtr[0] = idx; _IdxWritePtr[1] = (ImDrawIdx)(idx+1); _IdxWritePtr[2] = (ImDrawIdx)(idx+2);\r\n    _IdxWritePtr[3] = idx; _IdxWritePtr[4] = (ImDrawIdx)(idx+2); _IdxWritePtr[5] = (ImDrawIdx)(idx+3);\r\n    _VtxWritePtr[0].pos = a; _VtxWritePtr[0].uv = uv_a; _VtxWritePtr[0].col = col;\r\n    _VtxWritePtr[1].pos = b; _VtxWritePtr[1].uv = uv_b; _VtxWritePtr[1].col = col;\r\n    _VtxWritePtr[2].pos = c; _VtxWritePtr[2].uv = uv_c; _VtxWritePtr[2].col = col;\r\n    _VtxWritePtr[3].pos = d; _VtxWritePtr[3].uv = uv_d; _VtxWritePtr[3].col = col;\r\n    _VtxWritePtr += 4;\r\n    _VtxCurrentIdx += 4;\r\n    _IdxWritePtr += 6;\r\n}\r\n\r\nvoid ImDrawList::PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a, const ImVec2& uv_b, const ImVec2& uv_c, const ImVec2& uv_d, ImU32 col)\r\n{\r\n    ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx;\r\n    _IdxWritePtr[0] = idx; _IdxWritePtr[1] = (ImDrawIdx)(idx+1); _IdxWritePtr[2] = (ImDrawIdx)(idx+2);\r\n    _IdxWritePtr[3] = idx; _IdxWritePtr[4] = (ImDrawIdx)(idx+2); _IdxWritePtr[5] = (ImDrawIdx)(idx+3);\r\n    _VtxWritePtr[0].pos = a; _VtxWritePtr[0].uv = uv_a; _VtxWritePtr[0].col = col;\r\n    _VtxWritePtr[1].pos = b; _VtxWritePtr[1].uv = uv_b; _VtxWritePtr[1].col = col;\r\n    _VtxWritePtr[2].pos = c; _VtxWritePtr[2].uv = uv_c; _VtxWritePtr[2].col = col;\r\n    _VtxWritePtr[3].pos = d; _VtxWritePtr[3].uv = uv_d; _VtxWritePtr[3].col = col;\r\n    _VtxWritePtr += 4;\r\n    _VtxCurrentIdx += 4;\r\n    _IdxWritePtr += 6;\r\n}\r\n\r\n// On AddPolyline() and AddConvexPolyFilled() we intentionally avoid using ImVec2 and superfluous function calls to optimize debug/non-inlined builds.\r\n// - Those macros expects l-values and need to be used as their own statement.\r\n// - Those macros are intentionally not surrounded by the 'do {} while (0)' idiom because even that translates to runtime with debug compilers.\r\n#define IM_NORMALIZE2F_OVER_ZERO(VX,VY)     { float d2 = VX*VX + VY*VY; if (d2 > 0.0f) { float inv_len = ImRsqrt(d2); VX *= inv_len; VY *= inv_len; } } (void)0\r\n#define IM_FIXNORMAL2F_MAX_INVLEN2          100.0f // 500.0f (see #4053, #3366)\r\n#define IM_FIXNORMAL2F(VX,VY)               { float d2 = VX*VX + VY*VY; if (d2 > 0.000001f) { float inv_len2 = 1.0f / d2; if (inv_len2 > IM_FIXNORMAL2F_MAX_INVLEN2) inv_len2 = IM_FIXNORMAL2F_MAX_INVLEN2; VX *= inv_len2; VY *= inv_len2; } } (void)0\r\n\r\n// TODO: Thickness anti-aliased lines cap are missing their AA fringe.\r\n// We avoid using the ImVec2 math operators here to reduce cost to a minimum for debug/non-inlined builds.\r\nvoid ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 col, ImDrawFlags flags, float thickness)\r\n{\r\n    if (points_count < 2)\r\n        return;\r\n\r\n    const bool closed = (flags & ImDrawFlags_Closed) != 0;\r\n    const ImVec2 opaque_uv = _Data->TexUvWhitePixel;\r\n    const int count = closed ? points_count : points_count - 1; // The number of line segments we need to draw\r\n    const bool thick_line = (thickness > _FringeScale);\r\n\r\n    if (Flags & ImDrawListFlags_AntiAliasedLines)\r\n    {\r\n        // Anti-aliased stroke\r\n        const float AA_SIZE = _FringeScale;\r\n        const ImU32 col_trans = col & ~IM_COL32_A_MASK;\r\n\r\n        // Thicknesses <1.0 should behave like thickness 1.0\r\n        thickness = ImMax(thickness, 1.0f);\r\n        const int integer_thickness = (int)thickness;\r\n        const float fractional_thickness = thickness - integer_thickness;\r\n\r\n        // Do we want to draw this line using a texture?\r\n        // - For now, only draw integer-width lines using textures to avoid issues with the way scaling occurs, could be improved.\r\n        // - If AA_SIZE is not 1.0f we cannot use the texture path.\r\n        const bool use_texture = (Flags & ImDrawListFlags_AntiAliasedLinesUseTex) && (integer_thickness < IM_DRAWLIST_TEX_LINES_WIDTH_MAX) && (fractional_thickness <= 0.00001f) && (AA_SIZE == 1.0f);\r\n\r\n        // We should never hit this, because NewFrame() doesn't set ImDrawListFlags_AntiAliasedLinesUseTex unless ImFontAtlasFlags_NoBakedLines is off\r\n        IM_ASSERT_PARANOID(!use_texture || !(_Data->Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoBakedLines));\r\n\r\n        const int idx_count = use_texture ? (count * 6) : (thick_line ? count * 18 : count * 12);\r\n        const int vtx_count = use_texture ? (points_count * 2) : (thick_line ? points_count * 4 : points_count * 3);\r\n        PrimReserve(idx_count, vtx_count);\r\n\r\n        // Temporary buffer\r\n        // The first <points_count> items are normals at each line point, then after that there are either 2 or 4 temp points for each line point\r\n        ImVec2* temp_normals = (ImVec2*)alloca(points_count * ((use_texture || !thick_line) ? 3 : 5) * sizeof(ImVec2)); //-V630\r\n        ImVec2* temp_points = temp_normals + points_count;\r\n\r\n        // Calculate normals (tangents) for each line segment\r\n        for (int i1 = 0; i1 < count; i1++)\r\n        {\r\n            const int i2 = (i1 + 1) == points_count ? 0 : i1 + 1;\r\n            float dx = points[i2].x - points[i1].x;\r\n            float dy = points[i2].y - points[i1].y;\r\n            IM_NORMALIZE2F_OVER_ZERO(dx, dy);\r\n            temp_normals[i1].x = dy;\r\n            temp_normals[i1].y = -dx;\r\n        }\r\n        if (!closed)\r\n            temp_normals[points_count - 1] = temp_normals[points_count - 2];\r\n\r\n        // If we are drawing a one-pixel-wide line without a texture, or a textured line of any width, we only need 2 or 3 vertices per point\r\n        if (use_texture || !thick_line)\r\n        {\r\n            // [PATH 1] Texture-based lines (thick or non-thick)\r\n            // [PATH 2] Non texture-based lines (non-thick)\r\n\r\n            // The width of the geometry we need to draw - this is essentially <thickness> pixels for the line itself, plus \"one pixel\" for AA.\r\n            // - In the texture-based path, we don't use AA_SIZE here because the +1 is tied to the generated texture\r\n            //   (see ImFontAtlasBuildRenderLinesTexData() function), and so alternate values won't work without changes to that code.\r\n            // - In the non texture-based paths, we would allow AA_SIZE to potentially be != 1.0f with a patch (e.g. fringe_scale patch to\r\n            //   allow scaling geometry while preserving one-screen-pixel AA fringe).\r\n            const float half_draw_size = use_texture ? ((thickness * 0.5f) + 1) : AA_SIZE;\r\n\r\n            // If line is not closed, the first and last points need to be generated differently as there are no normals to blend\r\n            if (!closed)\r\n            {\r\n                temp_points[0] = points[0] + temp_normals[0] * half_draw_size;\r\n                temp_points[1] = points[0] - temp_normals[0] * half_draw_size;\r\n                temp_points[(points_count-1)*2+0] = points[points_count-1] + temp_normals[points_count-1] * half_draw_size;\r\n                temp_points[(points_count-1)*2+1] = points[points_count-1] - temp_normals[points_count-1] * half_draw_size;\r\n            }\r\n\r\n            // Generate the indices to form a number of triangles for each line segment, and the vertices for the line edges\r\n            // This takes points n and n+1 and writes into n+1, with the first point in a closed line being generated from the final one (as n+1 wraps)\r\n            // FIXME-OPT: Merge the different loops, possibly remove the temporary buffer.\r\n            unsigned int idx1 = _VtxCurrentIdx; // Vertex index for start of line segment\r\n            for (int i1 = 0; i1 < count; i1++) // i1 is the first point of the line segment\r\n            {\r\n                const int i2 = (i1 + 1) == points_count ? 0 : i1 + 1; // i2 is the second point of the line segment\r\n                const unsigned int idx2 = ((i1 + 1) == points_count) ? _VtxCurrentIdx : (idx1 + (use_texture ? 2 : 3)); // Vertex index for end of segment\r\n\r\n                // Average normals\r\n                float dm_x = (temp_normals[i1].x + temp_normals[i2].x) * 0.5f;\r\n                float dm_y = (temp_normals[i1].y + temp_normals[i2].y) * 0.5f;\r\n                IM_FIXNORMAL2F(dm_x, dm_y);\r\n                dm_x *= half_draw_size; // dm_x, dm_y are offset to the outer edge of the AA area\r\n                dm_y *= half_draw_size;\r\n\r\n                // Add temporary vertexes for the outer edges\r\n                ImVec2* out_vtx = &temp_points[i2 * 2];\r\n                out_vtx[0].x = points[i2].x + dm_x;\r\n                out_vtx[0].y = points[i2].y + dm_y;\r\n                out_vtx[1].x = points[i2].x - dm_x;\r\n                out_vtx[1].y = points[i2].y - dm_y;\r\n\r\n                if (use_texture)\r\n                {\r\n                    // Add indices for two triangles\r\n                    _IdxWritePtr[0] = (ImDrawIdx)(idx2 + 0); _IdxWritePtr[1] = (ImDrawIdx)(idx1 + 0); _IdxWritePtr[2] = (ImDrawIdx)(idx1 + 1); // Right tri\r\n                    _IdxWritePtr[3] = (ImDrawIdx)(idx2 + 1); _IdxWritePtr[4] = (ImDrawIdx)(idx1 + 1); _IdxWritePtr[5] = (ImDrawIdx)(idx2 + 0); // Left tri\r\n                    _IdxWritePtr += 6;\r\n                }\r\n                else\r\n                {\r\n                    // Add indexes for four triangles\r\n                    _IdxWritePtr[0] = (ImDrawIdx)(idx2 + 0); _IdxWritePtr[1] = (ImDrawIdx)(idx1 + 0); _IdxWritePtr[2] = (ImDrawIdx)(idx1 + 2); // Right tri 1\r\n                    _IdxWritePtr[3] = (ImDrawIdx)(idx1 + 2); _IdxWritePtr[4] = (ImDrawIdx)(idx2 + 2); _IdxWritePtr[5] = (ImDrawIdx)(idx2 + 0); // Right tri 2\r\n                    _IdxWritePtr[6] = (ImDrawIdx)(idx2 + 1); _IdxWritePtr[7] = (ImDrawIdx)(idx1 + 1); _IdxWritePtr[8] = (ImDrawIdx)(idx1 + 0); // Left tri 1\r\n                    _IdxWritePtr[9] = (ImDrawIdx)(idx1 + 0); _IdxWritePtr[10] = (ImDrawIdx)(idx2 + 0); _IdxWritePtr[11] = (ImDrawIdx)(idx2 + 1); // Left tri 2\r\n                    _IdxWritePtr += 12;\r\n                }\r\n\r\n                idx1 = idx2;\r\n            }\r\n\r\n            // Add vertexes for each point on the line\r\n            if (use_texture)\r\n            {\r\n                // If we're using textures we only need to emit the left/right edge vertices\r\n                ImVec4 tex_uvs = _Data->TexUvLines[integer_thickness];\r\n                /*if (fractional_thickness != 0.0f) // Currently always zero when use_texture==false!\r\n                {\r\n                    const ImVec4 tex_uvs_1 = _Data->TexUvLines[integer_thickness + 1];\r\n                    tex_uvs.x = tex_uvs.x + (tex_uvs_1.x - tex_uvs.x) * fractional_thickness; // inlined ImLerp()\r\n                    tex_uvs.y = tex_uvs.y + (tex_uvs_1.y - tex_uvs.y) * fractional_thickness;\r\n                    tex_uvs.z = tex_uvs.z + (tex_uvs_1.z - tex_uvs.z) * fractional_thickness;\r\n                    tex_uvs.w = tex_uvs.w + (tex_uvs_1.w - tex_uvs.w) * fractional_thickness;\r\n                }*/\r\n                ImVec2 tex_uv0(tex_uvs.x, tex_uvs.y);\r\n                ImVec2 tex_uv1(tex_uvs.z, tex_uvs.w);\r\n                for (int i = 0; i < points_count; i++)\r\n                {\r\n                    _VtxWritePtr[0].pos = temp_points[i * 2 + 0]; _VtxWritePtr[0].uv = tex_uv0; _VtxWritePtr[0].col = col; // Left-side outer edge\r\n                    _VtxWritePtr[1].pos = temp_points[i * 2 + 1]; _VtxWritePtr[1].uv = tex_uv1; _VtxWritePtr[1].col = col; // Right-side outer edge\r\n                    _VtxWritePtr += 2;\r\n                }\r\n            }\r\n            else\r\n            {\r\n                // If we're not using a texture, we need the center vertex as well\r\n                for (int i = 0; i < points_count; i++)\r\n                {\r\n                    _VtxWritePtr[0].pos = points[i];              _VtxWritePtr[0].uv = opaque_uv; _VtxWritePtr[0].col = col;       // Center of line\r\n                    _VtxWritePtr[1].pos = temp_points[i * 2 + 0]; _VtxWritePtr[1].uv = opaque_uv; _VtxWritePtr[1].col = col_trans; // Left-side outer edge\r\n                    _VtxWritePtr[2].pos = temp_points[i * 2 + 1]; _VtxWritePtr[2].uv = opaque_uv; _VtxWritePtr[2].col = col_trans; // Right-side outer edge\r\n                    _VtxWritePtr += 3;\r\n                }\r\n            }\r\n        }\r\n        else\r\n        {\r\n            // [PATH 2] Non texture-based lines (thick): we need to draw the solid line core and thus require four vertices per point\r\n            const float half_inner_thickness = (thickness - AA_SIZE) * 0.5f;\r\n\r\n            // If line is not closed, the first and last points need to be generated differently as there are no normals to blend\r\n            if (!closed)\r\n            {\r\n                const int points_last = points_count - 1;\r\n                temp_points[0] = points[0] + temp_normals[0] * (half_inner_thickness + AA_SIZE);\r\n                temp_points[1] = points[0] + temp_normals[0] * (half_inner_thickness);\r\n                temp_points[2] = points[0] - temp_normals[0] * (half_inner_thickness);\r\n                temp_points[3] = points[0] - temp_normals[0] * (half_inner_thickness + AA_SIZE);\r\n                temp_points[points_last * 4 + 0] = points[points_last] + temp_normals[points_last] * (half_inner_thickness + AA_SIZE);\r\n                temp_points[points_last * 4 + 1] = points[points_last] + temp_normals[points_last] * (half_inner_thickness);\r\n                temp_points[points_last * 4 + 2] = points[points_last] - temp_normals[points_last] * (half_inner_thickness);\r\n                temp_points[points_last * 4 + 3] = points[points_last] - temp_normals[points_last] * (half_inner_thickness + AA_SIZE);\r\n            }\r\n\r\n            // Generate the indices to form a number of triangles for each line segment, and the vertices for the line edges\r\n            // This takes points n and n+1 and writes into n+1, with the first point in a closed line being generated from the final one (as n+1 wraps)\r\n            // FIXME-OPT: Merge the different loops, possibly remove the temporary buffer.\r\n            unsigned int idx1 = _VtxCurrentIdx; // Vertex index for start of line segment\r\n            for (int i1 = 0; i1 < count; i1++) // i1 is the first point of the line segment\r\n            {\r\n                const int i2 = (i1 + 1) == points_count ? 0 : (i1 + 1); // i2 is the second point of the line segment\r\n                const unsigned int idx2 = (i1 + 1) == points_count ? _VtxCurrentIdx : (idx1 + 4); // Vertex index for end of segment\r\n\r\n                // Average normals\r\n                float dm_x = (temp_normals[i1].x + temp_normals[i2].x) * 0.5f;\r\n                float dm_y = (temp_normals[i1].y + temp_normals[i2].y) * 0.5f;\r\n                IM_FIXNORMAL2F(dm_x, dm_y);\r\n                float dm_out_x = dm_x * (half_inner_thickness + AA_SIZE);\r\n                float dm_out_y = dm_y * (half_inner_thickness + AA_SIZE);\r\n                float dm_in_x = dm_x * half_inner_thickness;\r\n                float dm_in_y = dm_y * half_inner_thickness;\r\n\r\n                // Add temporary vertices\r\n                ImVec2* out_vtx = &temp_points[i2 * 4];\r\n                out_vtx[0].x = points[i2].x + dm_out_x;\r\n                out_vtx[0].y = points[i2].y + dm_out_y;\r\n                out_vtx[1].x = points[i2].x + dm_in_x;\r\n                out_vtx[1].y = points[i2].y + dm_in_y;\r\n                out_vtx[2].x = points[i2].x - dm_in_x;\r\n                out_vtx[2].y = points[i2].y - dm_in_y;\r\n                out_vtx[3].x = points[i2].x - dm_out_x;\r\n                out_vtx[3].y = points[i2].y - dm_out_y;\r\n\r\n                // Add indexes\r\n                _IdxWritePtr[0]  = (ImDrawIdx)(idx2 + 1); _IdxWritePtr[1]  = (ImDrawIdx)(idx1 + 1); _IdxWritePtr[2]  = (ImDrawIdx)(idx1 + 2);\r\n                _IdxWritePtr[3]  = (ImDrawIdx)(idx1 + 2); _IdxWritePtr[4]  = (ImDrawIdx)(idx2 + 2); _IdxWritePtr[5]  = (ImDrawIdx)(idx2 + 1);\r\n                _IdxWritePtr[6]  = (ImDrawIdx)(idx2 + 1); _IdxWritePtr[7]  = (ImDrawIdx)(idx1 + 1); _IdxWritePtr[8]  = (ImDrawIdx)(idx1 + 0);\r\n                _IdxWritePtr[9]  = (ImDrawIdx)(idx1 + 0); _IdxWritePtr[10] = (ImDrawIdx)(idx2 + 0); _IdxWritePtr[11] = (ImDrawIdx)(idx2 + 1);\r\n                _IdxWritePtr[12] = (ImDrawIdx)(idx2 + 2); _IdxWritePtr[13] = (ImDrawIdx)(idx1 + 2); _IdxWritePtr[14] = (ImDrawIdx)(idx1 + 3);\r\n                _IdxWritePtr[15] = (ImDrawIdx)(idx1 + 3); _IdxWritePtr[16] = (ImDrawIdx)(idx2 + 3); _IdxWritePtr[17] = (ImDrawIdx)(idx2 + 2);\r\n                _IdxWritePtr += 18;\r\n\r\n                idx1 = idx2;\r\n            }\r\n\r\n            // Add vertices\r\n            for (int i = 0; i < points_count; i++)\r\n            {\r\n                _VtxWritePtr[0].pos = temp_points[i * 4 + 0]; _VtxWritePtr[0].uv = opaque_uv; _VtxWritePtr[0].col = col_trans;\r\n                _VtxWritePtr[1].pos = temp_points[i * 4 + 1]; _VtxWritePtr[1].uv = opaque_uv; _VtxWritePtr[1].col = col;\r\n                _VtxWritePtr[2].pos = temp_points[i * 4 + 2]; _VtxWritePtr[2].uv = opaque_uv; _VtxWritePtr[2].col = col;\r\n                _VtxWritePtr[3].pos = temp_points[i * 4 + 3]; _VtxWritePtr[3].uv = opaque_uv; _VtxWritePtr[3].col = col_trans;\r\n                _VtxWritePtr += 4;\r\n            }\r\n        }\r\n        _VtxCurrentIdx += (ImDrawIdx)vtx_count;\r\n    }\r\n    else\r\n    {\r\n        // [PATH 4] Non texture-based, Non anti-aliased lines\r\n        const int idx_count = count * 6;\r\n        const int vtx_count = count * 4;    // FIXME-OPT: Not sharing edges\r\n        PrimReserve(idx_count, vtx_count);\r\n\r\n        for (int i1 = 0; i1 < count; i1++)\r\n        {\r\n            const int i2 = (i1 + 1) == points_count ? 0 : i1 + 1;\r\n            const ImVec2& p1 = points[i1];\r\n            const ImVec2& p2 = points[i2];\r\n\r\n            float dx = p2.x - p1.x;\r\n            float dy = p2.y - p1.y;\r\n            IM_NORMALIZE2F_OVER_ZERO(dx, dy);\r\n            dx *= (thickness * 0.5f);\r\n            dy *= (thickness * 0.5f);\r\n\r\n            _VtxWritePtr[0].pos.x = p1.x + dy; _VtxWritePtr[0].pos.y = p1.y - dx; _VtxWritePtr[0].uv = opaque_uv; _VtxWritePtr[0].col = col;\r\n            _VtxWritePtr[1].pos.x = p2.x + dy; _VtxWritePtr[1].pos.y = p2.y - dx; _VtxWritePtr[1].uv = opaque_uv; _VtxWritePtr[1].col = col;\r\n            _VtxWritePtr[2].pos.x = p2.x - dy; _VtxWritePtr[2].pos.y = p2.y + dx; _VtxWritePtr[2].uv = opaque_uv; _VtxWritePtr[2].col = col;\r\n            _VtxWritePtr[3].pos.x = p1.x - dy; _VtxWritePtr[3].pos.y = p1.y + dx; _VtxWritePtr[3].uv = opaque_uv; _VtxWritePtr[3].col = col;\r\n            _VtxWritePtr += 4;\r\n\r\n            _IdxWritePtr[0] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[1] = (ImDrawIdx)(_VtxCurrentIdx + 1); _IdxWritePtr[2] = (ImDrawIdx)(_VtxCurrentIdx + 2);\r\n            _IdxWritePtr[3] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[4] = (ImDrawIdx)(_VtxCurrentIdx + 2); _IdxWritePtr[5] = (ImDrawIdx)(_VtxCurrentIdx + 3);\r\n            _IdxWritePtr += 6;\r\n            _VtxCurrentIdx += 4;\r\n        }\r\n    }\r\n}\r\n\r\n// We intentionally avoid using ImVec2 and its math operators here to reduce cost to a minimum for debug/non-inlined builds.\r\nvoid ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_count, ImU32 col)\r\n{\r\n    if (points_count < 3)\r\n        return;\r\n\r\n    const ImVec2 uv = _Data->TexUvWhitePixel;\r\n\r\n    if (Flags & ImDrawListFlags_AntiAliasedFill)\r\n    {\r\n        // Anti-aliased Fill\r\n        const float AA_SIZE = _FringeScale;\r\n        const ImU32 col_trans = col & ~IM_COL32_A_MASK;\r\n        const int idx_count = (points_count - 2)*3 + points_count * 6;\r\n        const int vtx_count = (points_count * 2);\r\n        PrimReserve(idx_count, vtx_count);\r\n\r\n        // Add indexes for fill\r\n        unsigned int vtx_inner_idx = _VtxCurrentIdx;\r\n        unsigned int vtx_outer_idx = _VtxCurrentIdx + 1;\r\n        for (int i = 2; i < points_count; i++)\r\n        {\r\n            _IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx); _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx + ((i - 1) << 1)); _IdxWritePtr[2] = (ImDrawIdx)(vtx_inner_idx + (i << 1));\r\n            _IdxWritePtr += 3;\r\n        }\r\n\r\n        // Compute normals\r\n        ImVec2* temp_normals = (ImVec2*)alloca(points_count * sizeof(ImVec2)); //-V630\r\n        for (int i0 = points_count - 1, i1 = 0; i1 < points_count; i0 = i1++)\r\n        {\r\n            const ImVec2& p0 = points[i0];\r\n            const ImVec2& p1 = points[i1];\r\n            float dx = p1.x - p0.x;\r\n            float dy = p1.y - p0.y;\r\n            IM_NORMALIZE2F_OVER_ZERO(dx, dy);\r\n            temp_normals[i0].x = dy;\r\n            temp_normals[i0].y = -dx;\r\n        }\r\n\r\n        for (int i0 = points_count - 1, i1 = 0; i1 < points_count; i0 = i1++)\r\n        {\r\n            // Average normals\r\n            const ImVec2& n0 = temp_normals[i0];\r\n            const ImVec2& n1 = temp_normals[i1];\r\n            float dm_x = (n0.x + n1.x) * 0.5f;\r\n            float dm_y = (n0.y + n1.y) * 0.5f;\r\n            IM_FIXNORMAL2F(dm_x, dm_y);\r\n            dm_x *= AA_SIZE * 0.5f;\r\n            dm_y *= AA_SIZE * 0.5f;\r\n\r\n            // Add vertices\r\n            _VtxWritePtr[0].pos.x = (points[i1].x - dm_x); _VtxWritePtr[0].pos.y = (points[i1].y - dm_y); _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col;        // Inner\r\n            _VtxWritePtr[1].pos.x = (points[i1].x + dm_x); _VtxWritePtr[1].pos.y = (points[i1].y + dm_y); _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col_trans;  // Outer\r\n            _VtxWritePtr += 2;\r\n\r\n            // Add indexes for fringes\r\n            _IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx + (i1 << 1)); _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx + (i0 << 1)); _IdxWritePtr[2] = (ImDrawIdx)(vtx_outer_idx + (i0 << 1));\r\n            _IdxWritePtr[3] = (ImDrawIdx)(vtx_outer_idx + (i0 << 1)); _IdxWritePtr[4] = (ImDrawIdx)(vtx_outer_idx + (i1 << 1)); _IdxWritePtr[5] = (ImDrawIdx)(vtx_inner_idx + (i1 << 1));\r\n            _IdxWritePtr += 6;\r\n        }\r\n        _VtxCurrentIdx += (ImDrawIdx)vtx_count;\r\n    }\r\n    else\r\n    {\r\n        // Non Anti-aliased Fill\r\n        const int idx_count = (points_count - 2)*3;\r\n        const int vtx_count = points_count;\r\n        PrimReserve(idx_count, vtx_count);\r\n        for (int i = 0; i < vtx_count; i++)\r\n        {\r\n            _VtxWritePtr[0].pos = points[i]; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col;\r\n            _VtxWritePtr++;\r\n        }\r\n        for (int i = 2; i < points_count; i++)\r\n        {\r\n            _IdxWritePtr[0] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[1] = (ImDrawIdx)(_VtxCurrentIdx + i - 1); _IdxWritePtr[2] = (ImDrawIdx)(_VtxCurrentIdx + i);\r\n            _IdxWritePtr += 3;\r\n        }\r\n        _VtxCurrentIdx += (ImDrawIdx)vtx_count;\r\n    }\r\n}\r\n\r\nvoid ImDrawList::_PathArcToFastEx(const ImVec2& center, float radius, int a_min_sample, int a_max_sample, int a_step)\r\n{\r\n    if (radius <= 0.0f)\r\n    {\r\n        _Path.push_back(center);\r\n        return;\r\n    }\r\n\r\n    // Calculate arc auto segment step size\r\n    if (a_step <= 0)\r\n        a_step = IM_DRAWLIST_ARCFAST_SAMPLE_MAX / _CalcCircleAutoSegmentCount(radius);\r\n\r\n    // Make sure we never do steps larger than one quarter of the circle\r\n    a_step = ImClamp(a_step, 1, IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4);\r\n\r\n    const int sample_range = ImAbs(a_max_sample - a_min_sample);\r\n    const int a_next_step = a_step;\r\n\r\n    int samples = sample_range + 1;\r\n    bool extra_max_sample = false;\r\n    if (a_step > 1)\r\n    {\r\n        samples            = sample_range / a_step + 1;\r\n        const int overstep = sample_range % a_step;\r\n\r\n        if (overstep > 0)\r\n        {\r\n            extra_max_sample = true;\r\n            samples++;\r\n\r\n            // When we have overstep to avoid awkwardly looking one long line and one tiny one at the end,\r\n            // distribute first step range evenly between them by reducing first step size.\r\n            if (sample_range > 0)\r\n                a_step -= (a_step - overstep) / 2;\r\n        }\r\n    }\r\n\r\n    _Path.resize(_Path.Size + samples);\r\n    ImVec2* out_ptr = _Path.Data + (_Path.Size - samples);\r\n\r\n    int sample_index = a_min_sample;\r\n    if (sample_index < 0 || sample_index >= IM_DRAWLIST_ARCFAST_SAMPLE_MAX)\r\n    {\r\n        sample_index = sample_index % IM_DRAWLIST_ARCFAST_SAMPLE_MAX;\r\n        if (sample_index < 0)\r\n            sample_index += IM_DRAWLIST_ARCFAST_SAMPLE_MAX;\r\n    }\r\n\r\n    if (a_max_sample >= a_min_sample)\r\n    {\r\n        for (int a = a_min_sample; a <= a_max_sample; a += a_step, sample_index += a_step, a_step = a_next_step)\r\n        {\r\n            // a_step is clamped to IM_DRAWLIST_ARCFAST_SAMPLE_MAX, so we have guaranteed that it will not wrap over range twice or more\r\n            if (sample_index >= IM_DRAWLIST_ARCFAST_SAMPLE_MAX)\r\n                sample_index -= IM_DRAWLIST_ARCFAST_SAMPLE_MAX;\r\n\r\n            const ImVec2 s = _Data->ArcFastVtx[sample_index];\r\n            out_ptr->x = center.x + s.x * radius;\r\n            out_ptr->y = center.y + s.y * radius;\r\n            out_ptr++;\r\n        }\r\n    }\r\n    else\r\n    {\r\n        for (int a = a_min_sample; a >= a_max_sample; a -= a_step, sample_index -= a_step, a_step = a_next_step)\r\n        {\r\n            // a_step is clamped to IM_DRAWLIST_ARCFAST_SAMPLE_MAX, so we have guaranteed that it will not wrap over range twice or more\r\n            if (sample_index < 0)\r\n                sample_index += IM_DRAWLIST_ARCFAST_SAMPLE_MAX;\r\n\r\n            const ImVec2 s = _Data->ArcFastVtx[sample_index];\r\n            out_ptr->x = center.x + s.x * radius;\r\n            out_ptr->y = center.y + s.y * radius;\r\n            out_ptr++;\r\n        }\r\n    }\r\n\r\n    if (extra_max_sample)\r\n    {\r\n        int normalized_max_sample = a_max_sample % IM_DRAWLIST_ARCFAST_SAMPLE_MAX;\r\n        if (normalized_max_sample < 0)\r\n            normalized_max_sample += IM_DRAWLIST_ARCFAST_SAMPLE_MAX;\r\n\r\n        const ImVec2 s = _Data->ArcFastVtx[normalized_max_sample];\r\n        out_ptr->x = center.x + s.x * radius;\r\n        out_ptr->y = center.y + s.y * radius;\r\n        out_ptr++;\r\n    }\r\n\r\n    IM_ASSERT_PARANOID(_Path.Data + _Path.Size == out_ptr);\r\n}\r\n\r\nvoid ImDrawList::_PathArcToN(const ImVec2& center, float radius, float a_min, float a_max, int num_segments)\r\n{\r\n    if (radius <= 0.0f)\r\n    {\r\n        _Path.push_back(center);\r\n        return;\r\n    }\r\n\r\n    // Note that we are adding a point at both a_min and a_max.\r\n    // If you are trying to draw a full closed circle you don't want the overlapping points!\r\n    _Path.reserve(_Path.Size + (num_segments + 1));\r\n    for (int i = 0; i <= num_segments; i++)\r\n    {\r\n        const float a = a_min + ((float)i / (float)num_segments) * (a_max - a_min);\r\n        _Path.push_back(ImVec2(center.x + ImCos(a) * radius, center.y + ImSin(a) * radius));\r\n    }\r\n}\r\n\r\n// 0: East, 3: South, 6: West, 9: North, 12: East\r\nvoid ImDrawList::PathArcToFast(const ImVec2& center, float radius, int a_min_of_12, int a_max_of_12)\r\n{\r\n    if (radius <= 0.0f)\r\n    {\r\n        _Path.push_back(center);\r\n        return;\r\n    }\r\n    _PathArcToFastEx(center, radius, a_min_of_12 * IM_DRAWLIST_ARCFAST_SAMPLE_MAX / 12, a_max_of_12 * IM_DRAWLIST_ARCFAST_SAMPLE_MAX / 12, 0);\r\n}\r\n\r\nvoid ImDrawList::PathArcTo(const ImVec2& center, float radius, float a_min, float a_max, int num_segments)\r\n{\r\n    if (radius <= 0.0f)\r\n    {\r\n        _Path.push_back(center);\r\n        return;\r\n    }\r\n\r\n    if (num_segments > 0)\r\n    {\r\n        _PathArcToN(center, radius, a_min, a_max, num_segments);\r\n        return;\r\n    }\r\n\r\n    // Automatic segment count\r\n    if (radius <= _Data->ArcFastRadiusCutoff)\r\n    {\r\n        const bool a_is_reverse = a_max < a_min;\r\n\r\n        // We are going to use precomputed values for mid samples.\r\n        // Determine first and last sample in lookup table that belong to the arc.\r\n        const float a_min_sample_f = IM_DRAWLIST_ARCFAST_SAMPLE_MAX * a_min / (IM_PI * 2.0f);\r\n        const float a_max_sample_f = IM_DRAWLIST_ARCFAST_SAMPLE_MAX * a_max / (IM_PI * 2.0f);\r\n\r\n        const int a_min_sample = a_is_reverse ? (int)ImFloorSigned(a_min_sample_f) : (int)ImCeil(a_min_sample_f);\r\n        const int a_max_sample = a_is_reverse ? (int)ImCeil(a_max_sample_f) : (int)ImFloorSigned(a_max_sample_f);\r\n        const int a_mid_samples = a_is_reverse ? ImMax(a_min_sample - a_max_sample, 0) : ImMax(a_max_sample - a_min_sample, 0);\r\n\r\n        const float a_min_segment_angle = a_min_sample * IM_PI * 2.0f / IM_DRAWLIST_ARCFAST_SAMPLE_MAX;\r\n        const float a_max_segment_angle = a_max_sample * IM_PI * 2.0f / IM_DRAWLIST_ARCFAST_SAMPLE_MAX;\r\n        const bool a_emit_start = (a_min_segment_angle - a_min) != 0.0f;\r\n        const bool a_emit_end = (a_max - a_max_segment_angle) != 0.0f;\r\n\r\n        _Path.reserve(_Path.Size + (a_mid_samples + 1 + (a_emit_start ? 1 : 0) + (a_emit_end ? 1 : 0)));\r\n        if (a_emit_start)\r\n            _Path.push_back(ImVec2(center.x + ImCos(a_min) * radius, center.y + ImSin(a_min) * radius));\r\n        if (a_mid_samples > 0)\r\n            _PathArcToFastEx(center, radius, a_min_sample, a_max_sample, 0);\r\n        if (a_emit_end)\r\n            _Path.push_back(ImVec2(center.x + ImCos(a_max) * radius, center.y + ImSin(a_max) * radius));\r\n    }\r\n    else\r\n    {\r\n        const float arc_length = ImAbs(a_max - a_min);\r\n        const int circle_segment_count = _CalcCircleAutoSegmentCount(radius);\r\n        const int arc_segment_count = ImMax((int)ImCeil(circle_segment_count * arc_length / (IM_PI * 2.0f)), (int)(2.0f * IM_PI / arc_length));\r\n        _PathArcToN(center, radius, a_min, a_max, arc_segment_count);\r\n    }\r\n}\r\n\r\nImVec2 ImBezierCubicCalc(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, float t)\r\n{\r\n    float u = 1.0f - t;\r\n    float w1 = u * u * u;\r\n    float w2 = 3 * u * u * t;\r\n    float w3 = 3 * u * t * t;\r\n    float w4 = t * t * t;\r\n    return ImVec2(w1 * p1.x + w2 * p2.x + w3 * p3.x + w4 * p4.x, w1 * p1.y + w2 * p2.y + w3 * p3.y + w4 * p4.y);\r\n}\r\n\r\nImVec2 ImBezierQuadraticCalc(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, float t)\r\n{\r\n    float u = 1.0f - t;\r\n    float w1 = u * u;\r\n    float w2 = 2 * u * t;\r\n    float w3 = t * t;\r\n    return ImVec2(w1 * p1.x + w2 * p2.x + w3 * p3.x, w1 * p1.y + w2 * p2.y + w3 * p3.y);\r\n}\r\n\r\n// Closely mimics ImBezierCubicClosestPointCasteljau() in imgui.cpp\r\nstatic void PathBezierCubicCurveToCasteljau(ImVector<ImVec2>* path, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level)\r\n{\r\n    float dx = x4 - x1;\r\n    float dy = y4 - y1;\r\n    float d2 = (x2 - x4) * dy - (y2 - y4) * dx;\r\n    float d3 = (x3 - x4) * dy - (y3 - y4) * dx;\r\n    d2 = (d2 >= 0) ? d2 : -d2;\r\n    d3 = (d3 >= 0) ? d3 : -d3;\r\n    if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy))\r\n    {\r\n        path->push_back(ImVec2(x4, y4));\r\n    }\r\n    else if (level < 10)\r\n    {\r\n        float x12 = (x1 + x2) * 0.5f, y12 = (y1 + y2) * 0.5f;\r\n        float x23 = (x2 + x3) * 0.5f, y23 = (y2 + y3) * 0.5f;\r\n        float x34 = (x3 + x4) * 0.5f, y34 = (y3 + y4) * 0.5f;\r\n        float x123 = (x12 + x23) * 0.5f, y123 = (y12 + y23) * 0.5f;\r\n        float x234 = (x23 + x34) * 0.5f, y234 = (y23 + y34) * 0.5f;\r\n        float x1234 = (x123 + x234) * 0.5f, y1234 = (y123 + y234) * 0.5f;\r\n        PathBezierCubicCurveToCasteljau(path, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1);\r\n        PathBezierCubicCurveToCasteljau(path, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1);\r\n    }\r\n}\r\n\r\nstatic void PathBezierQuadraticCurveToCasteljau(ImVector<ImVec2>* path, float x1, float y1, float x2, float y2, float x3, float y3, float tess_tol, int level)\r\n{\r\n    float dx = x3 - x1, dy = y3 - y1;\r\n    float det = (x2 - x3) * dy - (y2 - y3) * dx;\r\n    if (det * det * 4.0f < tess_tol * (dx * dx + dy * dy))\r\n    {\r\n        path->push_back(ImVec2(x3, y3));\r\n    }\r\n    else if (level < 10)\r\n    {\r\n        float x12 = (x1 + x2) * 0.5f, y12 = (y1 + y2) * 0.5f;\r\n        float x23 = (x2 + x3) * 0.5f, y23 = (y2 + y3) * 0.5f;\r\n        float x123 = (x12 + x23) * 0.5f, y123 = (y12 + y23) * 0.5f;\r\n        PathBezierQuadraticCurveToCasteljau(path, x1, y1, x12, y12, x123, y123, tess_tol, level + 1);\r\n        PathBezierQuadraticCurveToCasteljau(path, x123, y123, x23, y23, x3, y3, tess_tol, level + 1);\r\n    }\r\n}\r\n\r\nvoid ImDrawList::PathBezierCubicCurveTo(const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, int num_segments)\r\n{\r\n    ImVec2 p1 = _Path.back();\r\n    if (num_segments == 0)\r\n    {\r\n        PathBezierCubicCurveToCasteljau(&_Path, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, _Data->CurveTessellationTol, 0); // Auto-tessellated\r\n    }\r\n    else\r\n    {\r\n        float t_step = 1.0f / (float)num_segments;\r\n        for (int i_step = 1; i_step <= num_segments; i_step++)\r\n            _Path.push_back(ImBezierCubicCalc(p1, p2, p3, p4, t_step * i_step));\r\n    }\r\n}\r\n\r\nvoid ImDrawList::PathBezierQuadraticCurveTo(const ImVec2& p2, const ImVec2& p3, int num_segments)\r\n{\r\n    ImVec2 p1 = _Path.back();\r\n    if (num_segments == 0)\r\n    {\r\n        PathBezierQuadraticCurveToCasteljau(&_Path, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, _Data->CurveTessellationTol, 0);// Auto-tessellated\r\n    }\r\n    else\r\n    {\r\n        float t_step = 1.0f / (float)num_segments;\r\n        for (int i_step = 1; i_step <= num_segments; i_step++)\r\n            _Path.push_back(ImBezierQuadraticCalc(p1, p2, p3, t_step * i_step));\r\n    }\r\n}\r\n\r\nIM_STATIC_ASSERT(ImDrawFlags_RoundCornersTopLeft == (1 << 4));\r\nstatic inline ImDrawFlags FixRectCornerFlags(ImDrawFlags flags)\r\n{\r\n#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS\r\n    // Legacy Support for hard coded ~0 (used to be a suggested equivalent to ImDrawCornerFlags_All)\r\n    //   ~0   --> ImDrawFlags_RoundCornersAll or 0\r\n    if (flags == ~0)\r\n        return ImDrawFlags_RoundCornersAll;\r\n\r\n    // Legacy Support for hard coded 0x01 to 0x0F (matching 15 out of 16 old flags combinations)\r\n    //   0x01 --> ImDrawFlags_RoundCornersTopLeft (VALUE 0x01 OVERLAPS ImDrawFlags_Closed but ImDrawFlags_Closed is never valid in this path!)\r\n    //   0x02 --> ImDrawFlags_RoundCornersTopRight\r\n    //   0x03 --> ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersTopRight\r\n    //   0x04 --> ImDrawFlags_RoundCornersBotLeft\r\n    //   0x05 --> ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersBotLeft\r\n    //   ...\r\n    //   0x0F --> ImDrawFlags_RoundCornersAll or 0\r\n    // (See all values in ImDrawCornerFlags_)\r\n    if (flags >= 0x01 && flags <= 0x0F)\r\n        return (flags << 4);\r\n\r\n    // We cannot support hard coded 0x00 with 'float rounding > 0.0f' --> replace with ImDrawFlags_RoundCornersNone or use 'float rounding = 0.0f'\r\n#endif\r\n\r\n    // If this triggers, please update your code replacing hardcoded values with new ImDrawFlags_RoundCorners* values.\r\n    // Note that ImDrawFlags_Closed (== 0x01) is an invalid flag for AddRect(), AddRectFilled(), PathRect() etc...\r\n    IM_ASSERT((flags & 0x0F) == 0 && \"Misuse of legacy hardcoded ImDrawCornerFlags values!\");\r\n\r\n    if ((flags & ImDrawFlags_RoundCornersMask_) == 0)\r\n        flags |= ImDrawFlags_RoundCornersAll;\r\n\r\n    return flags;\r\n}\r\n\r\nvoid ImDrawList::PathRect(const ImVec2& a, const ImVec2& b, float rounding, ImDrawFlags flags)\r\n{\r\n    flags = FixRectCornerFlags(flags);\r\n    rounding = ImMin(rounding, ImFabs(b.x - a.x) * ( ((flags & ImDrawFlags_RoundCornersTop)  == ImDrawFlags_RoundCornersTop)  || ((flags & ImDrawFlags_RoundCornersBottom) == ImDrawFlags_RoundCornersBottom) ? 0.5f : 1.0f ) - 1.0f);\r\n    rounding = ImMin(rounding, ImFabs(b.y - a.y) * ( ((flags & ImDrawFlags_RoundCornersLeft) == ImDrawFlags_RoundCornersLeft) || ((flags & ImDrawFlags_RoundCornersRight)  == ImDrawFlags_RoundCornersRight)  ? 0.5f : 1.0f ) - 1.0f);\r\n\r\n    if (rounding <= 0.0f || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone)\r\n    {\r\n        PathLineTo(a);\r\n        PathLineTo(ImVec2(b.x, a.y));\r\n        PathLineTo(b);\r\n        PathLineTo(ImVec2(a.x, b.y));\r\n    }\r\n    else\r\n    {\r\n        const float rounding_tl = (flags & ImDrawFlags_RoundCornersTopLeft)     ? rounding : 0.0f;\r\n        const float rounding_tr = (flags & ImDrawFlags_RoundCornersTopRight)    ? rounding : 0.0f;\r\n        const float rounding_br = (flags & ImDrawFlags_RoundCornersBottomRight) ? rounding : 0.0f;\r\n        const float rounding_bl = (flags & ImDrawFlags_RoundCornersBottomLeft)  ? rounding : 0.0f;\r\n        PathArcToFast(ImVec2(a.x + rounding_tl, a.y + rounding_tl), rounding_tl, 6, 9);\r\n        PathArcToFast(ImVec2(b.x - rounding_tr, a.y + rounding_tr), rounding_tr, 9, 12);\r\n        PathArcToFast(ImVec2(b.x - rounding_br, b.y - rounding_br), rounding_br, 0, 3);\r\n        PathArcToFast(ImVec2(a.x + rounding_bl, b.y - rounding_bl), rounding_bl, 3, 6);\r\n    }\r\n}\r\n\r\nvoid ImDrawList::AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float thickness)\r\n{\r\n    if ((col & IM_COL32_A_MASK) == 0)\r\n        return;\r\n    PathLineTo(p1 + ImVec2(0.5f, 0.5f));\r\n    PathLineTo(p2 + ImVec2(0.5f, 0.5f));\r\n    PathStroke(col, 0, thickness);\r\n}\r\n\r\n// p_min = upper-left, p_max = lower-right\r\n// Note we don't render 1 pixels sized rectangles properly.\r\nvoid ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding, ImDrawFlags flags, float thickness)\r\n{\r\n    if ((col & IM_COL32_A_MASK) == 0)\r\n        return;\r\n    if (Flags & ImDrawListFlags_AntiAliasedLines)\r\n        PathRect(p_min + ImVec2(0.50f, 0.50f), p_max - ImVec2(0.50f, 0.50f), rounding, flags);\r\n    else\r\n        PathRect(p_min + ImVec2(0.50f, 0.50f), p_max - ImVec2(0.49f, 0.49f), rounding, flags); // Better looking lower-right corner and rounded non-AA shapes.\r\n    PathStroke(col, ImDrawFlags_Closed, thickness);\r\n}\r\n\r\nvoid ImDrawList::AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding, ImDrawFlags flags)\r\n{\r\n    if ((col & IM_COL32_A_MASK) == 0)\r\n        return;\r\n    if (rounding <= 0.0f || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone)\r\n    {\r\n        PrimReserve(6, 4);\r\n        PrimRect(p_min, p_max, col);\r\n    }\r\n    else\r\n    {\r\n        PathRect(p_min, p_max, rounding, flags);\r\n        PathFillConvex(col);\r\n    }\r\n}\r\n\r\n// p_min = upper-left, p_max = lower-right\r\nvoid ImDrawList::AddRectFilledMultiColor(const ImVec2& p_min, const ImVec2& p_max, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left)\r\n{\r\n    if (((col_upr_left | col_upr_right | col_bot_right | col_bot_left) & IM_COL32_A_MASK) == 0)\r\n        return;\r\n\r\n    const ImVec2 uv = _Data->TexUvWhitePixel;\r\n    PrimReserve(6, 4);\r\n    PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx + 1)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx + 2));\r\n    PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx + 2)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx + 3));\r\n    PrimWriteVtx(p_min, uv, col_upr_left);\r\n    PrimWriteVtx(ImVec2(p_max.x, p_min.y), uv, col_upr_right);\r\n    PrimWriteVtx(p_max, uv, col_bot_right);\r\n    PrimWriteVtx(ImVec2(p_min.x, p_max.y), uv, col_bot_left);\r\n}\r\n\r\nvoid ImDrawList::AddQuad(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness)\r\n{\r\n    if ((col & IM_COL32_A_MASK) == 0)\r\n        return;\r\n\r\n    PathLineTo(p1);\r\n    PathLineTo(p2);\r\n    PathLineTo(p3);\r\n    PathLineTo(p4);\r\n    PathStroke(col, ImDrawFlags_Closed, thickness);\r\n}\r\n\r\nvoid ImDrawList::AddQuadFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col)\r\n{\r\n    if ((col & IM_COL32_A_MASK) == 0)\r\n        return;\r\n\r\n    PathLineTo(p1);\r\n    PathLineTo(p2);\r\n    PathLineTo(p3);\r\n    PathLineTo(p4);\r\n    PathFillConvex(col);\r\n}\r\n\r\nvoid ImDrawList::AddTriangle(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness)\r\n{\r\n    if ((col & IM_COL32_A_MASK) == 0)\r\n        return;\r\n\r\n    PathLineTo(p1);\r\n    PathLineTo(p2);\r\n    PathLineTo(p3);\r\n    PathStroke(col, ImDrawFlags_Closed, thickness);\r\n}\r\n\r\nvoid ImDrawList::AddTriangleFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col)\r\n{\r\n    if ((col & IM_COL32_A_MASK) == 0)\r\n        return;\r\n\r\n    PathLineTo(p1);\r\n    PathLineTo(p2);\r\n    PathLineTo(p3);\r\n    PathFillConvex(col);\r\n}\r\n\r\nvoid ImDrawList::AddCircle(const ImVec2& center, float radius, ImU32 col, int num_segments, float thickness)\r\n{\r\n    if ((col & IM_COL32_A_MASK) == 0 || radius <= 0.0f)\r\n        return;\r\n\r\n    if (num_segments <= 0)\r\n    {\r\n        // Use arc with automatic segment count\r\n        _PathArcToFastEx(center, radius - 0.5f, 0, IM_DRAWLIST_ARCFAST_SAMPLE_MAX, 0);\r\n        _Path.Size--;\r\n    }\r\n    else\r\n    {\r\n        // Explicit segment count (still clamp to avoid drawing insanely tessellated shapes)\r\n        num_segments = ImClamp(num_segments, 3, IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX);\r\n\r\n        // Because we are filling a closed shape we remove 1 from the count of segments/points\r\n        const float a_max = (IM_PI * 2.0f) * ((float)num_segments - 1.0f) / (float)num_segments;\r\n        PathArcTo(center, radius - 0.5f, 0.0f, a_max, num_segments - 1);\r\n    }\r\n\r\n    PathStroke(col, ImDrawFlags_Closed, thickness);\r\n}\r\n\r\nvoid ImDrawList::AddCircleFilled(const ImVec2& center, float radius, ImU32 col, int num_segments)\r\n{\r\n    if ((col & IM_COL32_A_MASK) == 0 || radius <= 0.0f)\r\n        return;\r\n\r\n    if (num_segments <= 0)\r\n    {\r\n        // Use arc with automatic segment count\r\n        _PathArcToFastEx(center, radius, 0, IM_DRAWLIST_ARCFAST_SAMPLE_MAX, 0);\r\n        _Path.Size--;\r\n    }\r\n    else\r\n    {\r\n        // Explicit segment count (still clamp to avoid drawing insanely tessellated shapes)\r\n        num_segments = ImClamp(num_segments, 3, IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX);\r\n\r\n        // Because we are filling a closed shape we remove 1 from the count of segments/points\r\n        const float a_max = (IM_PI * 2.0f) * ((float)num_segments - 1.0f) / (float)num_segments;\r\n        PathArcTo(center, radius, 0.0f, a_max, num_segments - 1);\r\n    }\r\n\r\n    PathFillConvex(col);\r\n}\r\n\r\n// Guaranteed to honor 'num_segments'\r\nvoid ImDrawList::AddNgon(const ImVec2& center, float radius, ImU32 col, int num_segments, float thickness)\r\n{\r\n    if ((col & IM_COL32_A_MASK) == 0 || num_segments <= 2)\r\n        return;\r\n\r\n    // Because we are filling a closed shape we remove 1 from the count of segments/points\r\n    const float a_max = (IM_PI * 2.0f) * ((float)num_segments - 1.0f) / (float)num_segments;\r\n    PathArcTo(center, radius - 0.5f, 0.0f, a_max, num_segments - 1);\r\n    PathStroke(col, ImDrawFlags_Closed, thickness);\r\n}\r\n\r\n// Guaranteed to honor 'num_segments'\r\nvoid ImDrawList::AddNgonFilled(const ImVec2& center, float radius, ImU32 col, int num_segments)\r\n{\r\n    if ((col & IM_COL32_A_MASK) == 0 || num_segments <= 2)\r\n        return;\r\n\r\n    // Because we are filling a closed shape we remove 1 from the count of segments/points\r\n    const float a_max = (IM_PI * 2.0f) * ((float)num_segments - 1.0f) / (float)num_segments;\r\n    PathArcTo(center, radius, 0.0f, a_max, num_segments - 1);\r\n    PathFillConvex(col);\r\n}\r\n\r\n// Cubic Bezier takes 4 controls points\r\nvoid ImDrawList::AddBezierCubic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness, int num_segments)\r\n{\r\n    if ((col & IM_COL32_A_MASK) == 0)\r\n        return;\r\n\r\n    PathLineTo(p1);\r\n    PathBezierCubicCurveTo(p2, p3, p4, num_segments);\r\n    PathStroke(col, 0, thickness);\r\n}\r\n\r\n// Quadratic Bezier takes 3 controls points\r\nvoid ImDrawList::AddBezierQuadratic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness, int num_segments)\r\n{\r\n    if ((col & IM_COL32_A_MASK) == 0)\r\n        return;\r\n\r\n    PathLineTo(p1);\r\n    PathBezierQuadraticCurveTo(p2, p3, num_segments);\r\n    PathStroke(col, 0, thickness);\r\n}\r\n\r\nvoid ImDrawList::AddText(const ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end, float wrap_width, const ImVec4* cpu_fine_clip_rect)\r\n{\r\n    if ((col & IM_COL32_A_MASK) == 0)\r\n        return;\r\n\r\n    if (text_end == NULL)\r\n        text_end = text_begin + strlen(text_begin);\r\n    if (text_begin == text_end)\r\n        return;\r\n\r\n    // Pull default font/size from the shared ImDrawListSharedData instance\r\n    if (font == NULL)\r\n        font = _Data->Font;\r\n    if (font_size == 0.0f)\r\n        font_size = _Data->FontSize;\r\n\r\n    IM_ASSERT(font->ContainerAtlas->TexID == _CmdHeader.TextureId);  // Use high-level ImGui::PushFont() or low-level ImDrawList::PushTextureId() to change font.\r\n\r\n    ImVec4 clip_rect = _CmdHeader.ClipRect;\r\n    if (cpu_fine_clip_rect)\r\n    {\r\n        clip_rect.x = ImMax(clip_rect.x, cpu_fine_clip_rect->x);\r\n        clip_rect.y = ImMax(clip_rect.y, cpu_fine_clip_rect->y);\r\n        clip_rect.z = ImMin(clip_rect.z, cpu_fine_clip_rect->z);\r\n        clip_rect.w = ImMin(clip_rect.w, cpu_fine_clip_rect->w);\r\n    }\r\n    font->RenderText(this, font_size, pos, col, clip_rect, text_begin, text_end, wrap_width, cpu_fine_clip_rect != NULL);\r\n}\r\n\r\nvoid ImDrawList::AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end)\r\n{\r\n    AddText(NULL, 0.0f, pos, col, text_begin, text_end);\r\n}\r\n\r\nvoid ImDrawList::AddImage(ImTextureID user_texture_id, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min, const ImVec2& uv_max, ImU32 col)\r\n{\r\n    if ((col & IM_COL32_A_MASK) == 0)\r\n        return;\r\n\r\n    const bool push_texture_id = user_texture_id != _CmdHeader.TextureId;\r\n    if (push_texture_id)\r\n        PushTextureID(user_texture_id);\r\n\r\n    PrimReserve(6, 4);\r\n    PrimRectUV(p_min, p_max, uv_min, uv_max, col);\r\n\r\n    if (push_texture_id)\r\n        PopTextureID();\r\n}\r\n\r\nvoid ImDrawList::AddImageQuad(ImTextureID user_texture_id, const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& uv1, const ImVec2& uv2, const ImVec2& uv3, const ImVec2& uv4, ImU32 col)\r\n{\r\n    if ((col & IM_COL32_A_MASK) == 0)\r\n        return;\r\n\r\n    const bool push_texture_id = user_texture_id != _CmdHeader.TextureId;\r\n    if (push_texture_id)\r\n        PushTextureID(user_texture_id);\r\n\r\n    PrimReserve(6, 4);\r\n    PrimQuadUV(p1, p2, p3, p4, uv1, uv2, uv3, uv4, col);\r\n\r\n    if (push_texture_id)\r\n        PopTextureID();\r\n}\r\n\r\nvoid ImDrawList::AddImageRounded(ImTextureID user_texture_id, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min, const ImVec2& uv_max, ImU32 col, float rounding, ImDrawFlags flags)\r\n{\r\n    if ((col & IM_COL32_A_MASK) == 0)\r\n        return;\r\n\r\n    flags = FixRectCornerFlags(flags);\r\n    if (rounding <= 0.0f || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone)\r\n    {\r\n        AddImage(user_texture_id, p_min, p_max, uv_min, uv_max, col);\r\n        return;\r\n    }\r\n\r\n    const bool push_texture_id = user_texture_id != _CmdHeader.TextureId;\r\n    if (push_texture_id)\r\n        PushTextureID(user_texture_id);\r\n\r\n    int vert_start_idx = VtxBuffer.Size;\r\n    PathRect(p_min, p_max, rounding, flags);\r\n    PathFillConvex(col);\r\n    int vert_end_idx = VtxBuffer.Size;\r\n    ImGui::ShadeVertsLinearUV(this, vert_start_idx, vert_end_idx, p_min, p_max, uv_min, uv_max, true);\r\n\r\n    if (push_texture_id)\r\n        PopTextureID();\r\n}\r\n\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] ImDrawListSplitter\r\n//-----------------------------------------------------------------------------\r\n// FIXME: This may be a little confusing, trying to be a little too low-level/optimal instead of just doing vector swap..\r\n//-----------------------------------------------------------------------------\r\n\r\nvoid ImDrawListSplitter::ClearFreeMemory()\r\n{\r\n    for (int i = 0; i < _Channels.Size; i++)\r\n    {\r\n        if (i == _Current)\r\n            memset(&_Channels[i], 0, sizeof(_Channels[i]));  // Current channel is a copy of CmdBuffer/IdxBuffer, don't destruct again\r\n        _Channels[i]._CmdBuffer.clear();\r\n        _Channels[i]._IdxBuffer.clear();\r\n    }\r\n    _Current = 0;\r\n    _Count = 1;\r\n    _Channels.clear();\r\n}\r\n\r\nvoid ImDrawListSplitter::Split(ImDrawList* draw_list, int channels_count)\r\n{\r\n    IM_UNUSED(draw_list);\r\n    IM_ASSERT(_Current == 0 && _Count <= 1 && \"Nested channel splitting is not supported. Please use separate instances of ImDrawListSplitter.\");\r\n    int old_channels_count = _Channels.Size;\r\n    if (old_channels_count < channels_count)\r\n    {\r\n        _Channels.reserve(channels_count); // Avoid over reserving since this is likely to stay stable\r\n        _Channels.resize(channels_count);\r\n    }\r\n    _Count = channels_count;\r\n\r\n    // Channels[] (24/32 bytes each) hold storage that we'll swap with draw_list->_CmdBuffer/_IdxBuffer\r\n    // The content of Channels[0] at this point doesn't matter. We clear it to make state tidy in a debugger but we don't strictly need to.\r\n    // When we switch to the next channel, we'll copy draw_list->_CmdBuffer/_IdxBuffer into Channels[0] and then Channels[1] into draw_list->CmdBuffer/_IdxBuffer\r\n    memset(&_Channels[0], 0, sizeof(ImDrawChannel));\r\n    for (int i = 1; i < channels_count; i++)\r\n    {\r\n        if (i >= old_channels_count)\r\n        {\r\n            IM_PLACEMENT_NEW(&_Channels[i]) ImDrawChannel();\r\n        }\r\n        else\r\n        {\r\n            _Channels[i]._CmdBuffer.resize(0);\r\n            _Channels[i]._IdxBuffer.resize(0);\r\n        }\r\n    }\r\n}\r\n\r\nvoid ImDrawListSplitter::Merge(ImDrawList* draw_list)\r\n{\r\n    // Note that we never use or rely on _Channels.Size because it is merely a buffer that we never shrink back to 0 to keep all sub-buffers ready for use.\r\n    if (_Count <= 1)\r\n        return;\r\n\r\n    SetCurrentChannel(draw_list, 0);\r\n    draw_list->_PopUnusedDrawCmd();\r\n\r\n    // Calculate our final buffer sizes. Also fix the incorrect IdxOffset values in each command.\r\n    int new_cmd_buffer_count = 0;\r\n    int new_idx_buffer_count = 0;\r\n    ImDrawCmd* last_cmd = (_Count > 0 && draw_list->CmdBuffer.Size > 0) ? &draw_list->CmdBuffer.back() : NULL;\r\n    int idx_offset = last_cmd ? last_cmd->IdxOffset + last_cmd->ElemCount : 0;\r\n    for (int i = 1; i < _Count; i++)\r\n    {\r\n        ImDrawChannel& ch = _Channels[i];\r\n        if (ch._CmdBuffer.Size > 0 && ch._CmdBuffer.back().ElemCount == 0 && ch._CmdBuffer.back().UserCallback == NULL) // Equivalent of PopUnusedDrawCmd()\r\n            ch._CmdBuffer.pop_back();\r\n\r\n        if (ch._CmdBuffer.Size > 0 && last_cmd != NULL)\r\n        {\r\n            // Do not include ImDrawCmd_AreSequentialIdxOffset() in the compare as we rebuild IdxOffset values ourselves.\r\n            // Manipulating IdxOffset (e.g. by reordering draw commands like done by RenderDimmedBackgroundBehindWindow()) is not supported within a splitter.\r\n            ImDrawCmd* next_cmd = &ch._CmdBuffer[0];\r\n            if (ImDrawCmd_HeaderCompare(last_cmd, next_cmd) == 0 && last_cmd->UserCallback == NULL && next_cmd->UserCallback == NULL)\r\n            {\r\n                // Merge previous channel last draw command with current channel first draw command if matching.\r\n                last_cmd->ElemCount += next_cmd->ElemCount;\r\n                idx_offset += next_cmd->ElemCount;\r\n                ch._CmdBuffer.erase(ch._CmdBuffer.Data); // FIXME-OPT: Improve for multiple merges.\r\n            }\r\n        }\r\n        if (ch._CmdBuffer.Size > 0)\r\n            last_cmd = &ch._CmdBuffer.back();\r\n        new_cmd_buffer_count += ch._CmdBuffer.Size;\r\n        new_idx_buffer_count += ch._IdxBuffer.Size;\r\n        for (int cmd_n = 0; cmd_n < ch._CmdBuffer.Size; cmd_n++)\r\n        {\r\n            ch._CmdBuffer.Data[cmd_n].IdxOffset = idx_offset;\r\n            idx_offset += ch._CmdBuffer.Data[cmd_n].ElemCount;\r\n        }\r\n    }\r\n    draw_list->CmdBuffer.resize(draw_list->CmdBuffer.Size + new_cmd_buffer_count);\r\n    draw_list->IdxBuffer.resize(draw_list->IdxBuffer.Size + new_idx_buffer_count);\r\n\r\n    // Write commands and indices in order (they are fairly small structures, we don't copy vertices only indices)\r\n    ImDrawCmd* cmd_write = draw_list->CmdBuffer.Data + draw_list->CmdBuffer.Size - new_cmd_buffer_count;\r\n    ImDrawIdx* idx_write = draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size - new_idx_buffer_count;\r\n    for (int i = 1; i < _Count; i++)\r\n    {\r\n        ImDrawChannel& ch = _Channels[i];\r\n        if (int sz = ch._CmdBuffer.Size) { memcpy(cmd_write, ch._CmdBuffer.Data, sz * sizeof(ImDrawCmd)); cmd_write += sz; }\r\n        if (int sz = ch._IdxBuffer.Size) { memcpy(idx_write, ch._IdxBuffer.Data, sz * sizeof(ImDrawIdx)); idx_write += sz; }\r\n    }\r\n    draw_list->_IdxWritePtr = idx_write;\r\n\r\n    // Ensure there's always a non-callback draw command trailing the command-buffer\r\n    if (draw_list->CmdBuffer.Size == 0 || draw_list->CmdBuffer.back().UserCallback != NULL)\r\n        draw_list->AddDrawCmd();\r\n\r\n    // If current command is used with different settings we need to add a new command\r\n    ImDrawCmd* curr_cmd = &draw_list->CmdBuffer.Data[draw_list->CmdBuffer.Size - 1];\r\n    if (curr_cmd->ElemCount == 0)\r\n        ImDrawCmd_HeaderCopy(curr_cmd, &draw_list->_CmdHeader); // Copy ClipRect, TextureId, VtxOffset\r\n    else if (ImDrawCmd_HeaderCompare(curr_cmd, &draw_list->_CmdHeader) != 0)\r\n        draw_list->AddDrawCmd();\r\n\r\n    _Count = 1;\r\n}\r\n\r\nvoid ImDrawListSplitter::SetCurrentChannel(ImDrawList* draw_list, int idx)\r\n{\r\n    IM_ASSERT(idx >= 0 && idx < _Count);\r\n    if (_Current == idx)\r\n        return;\r\n\r\n    // Overwrite ImVector (12/16 bytes), four times. This is merely a silly optimization instead of doing .swap()\r\n    memcpy(&_Channels.Data[_Current]._CmdBuffer, &draw_list->CmdBuffer, sizeof(draw_list->CmdBuffer));\r\n    memcpy(&_Channels.Data[_Current]._IdxBuffer, &draw_list->IdxBuffer, sizeof(draw_list->IdxBuffer));\r\n    _Current = idx;\r\n    memcpy(&draw_list->CmdBuffer, &_Channels.Data[idx]._CmdBuffer, sizeof(draw_list->CmdBuffer));\r\n    memcpy(&draw_list->IdxBuffer, &_Channels.Data[idx]._IdxBuffer, sizeof(draw_list->IdxBuffer));\r\n    draw_list->_IdxWritePtr = draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size;\r\n\r\n    // If current command is used with different settings we need to add a new command\r\n    ImDrawCmd* curr_cmd = (draw_list->CmdBuffer.Size == 0) ? NULL : &draw_list->CmdBuffer.Data[draw_list->CmdBuffer.Size - 1];\r\n    if (curr_cmd == NULL)\r\n        draw_list->AddDrawCmd();\r\n    else if (curr_cmd->ElemCount == 0)\r\n        ImDrawCmd_HeaderCopy(curr_cmd, &draw_list->_CmdHeader); // Copy ClipRect, TextureId, VtxOffset\r\n    else if (ImDrawCmd_HeaderCompare(curr_cmd, &draw_list->_CmdHeader) != 0)\r\n        draw_list->AddDrawCmd();\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] ImDrawData\r\n//-----------------------------------------------------------------------------\r\n\r\n// For backward compatibility: convert all buffers from indexed to de-indexed, in case you cannot render indexed. Note: this is slow and most likely a waste of resources. Always prefer indexed rendering!\r\nvoid ImDrawData::DeIndexAllBuffers()\r\n{\r\n    ImVector<ImDrawVert> new_vtx_buffer;\r\n    TotalVtxCount = TotalIdxCount = 0;\r\n    for (int i = 0; i < CmdListsCount; i++)\r\n    {\r\n        ImDrawList* cmd_list = CmdLists[i];\r\n        if (cmd_list->IdxBuffer.empty())\r\n            continue;\r\n        new_vtx_buffer.resize(cmd_list->IdxBuffer.Size);\r\n        for (int j = 0; j < cmd_list->IdxBuffer.Size; j++)\r\n            new_vtx_buffer[j] = cmd_list->VtxBuffer[cmd_list->IdxBuffer[j]];\r\n        cmd_list->VtxBuffer.swap(new_vtx_buffer);\r\n        cmd_list->IdxBuffer.resize(0);\r\n        TotalVtxCount += cmd_list->VtxBuffer.Size;\r\n    }\r\n}\r\n\r\n// Helper to scale the ClipRect field of each ImDrawCmd.\r\n// Use if your final output buffer is at a different scale than draw_data->DisplaySize,\r\n// or if there is a difference between your window resolution and framebuffer resolution.\r\nvoid ImDrawData::ScaleClipRects(const ImVec2& fb_scale)\r\n{\r\n    for (int i = 0; i < CmdListsCount; i++)\r\n    {\r\n        ImDrawList* cmd_list = CmdLists[i];\r\n        for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)\r\n        {\r\n            ImDrawCmd* cmd = &cmd_list->CmdBuffer[cmd_i];\r\n            cmd->ClipRect = ImVec4(cmd->ClipRect.x * fb_scale.x, cmd->ClipRect.y * fb_scale.y, cmd->ClipRect.z * fb_scale.x, cmd->ClipRect.w * fb_scale.y);\r\n        }\r\n    }\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Helpers ShadeVertsXXX functions\r\n//-----------------------------------------------------------------------------\r\n\r\n// Generic linear color gradient, write to RGB fields, leave A untouched.\r\nvoid ImGui::ShadeVertsLinearColorGradientKeepAlpha(ImDrawList* draw_list, int vert_start_idx, int vert_end_idx, ImVec2 gradient_p0, ImVec2 gradient_p1, ImU32 col0, ImU32 col1)\r\n{\r\n    ImVec2 gradient_extent = gradient_p1 - gradient_p0;\r\n    float gradient_inv_length2 = 1.0f / ImLengthSqr(gradient_extent);\r\n    ImDrawVert* vert_start = draw_list->VtxBuffer.Data + vert_start_idx;\r\n    ImDrawVert* vert_end = draw_list->VtxBuffer.Data + vert_end_idx;\r\n    const int col0_r = (int)(col0 >> IM_COL32_R_SHIFT) & 0xFF;\r\n    const int col0_g = (int)(col0 >> IM_COL32_G_SHIFT) & 0xFF;\r\n    const int col0_b = (int)(col0 >> IM_COL32_B_SHIFT) & 0xFF;\r\n    const int col_delta_r = ((int)(col1 >> IM_COL32_R_SHIFT) & 0xFF) - col0_r;\r\n    const int col_delta_g = ((int)(col1 >> IM_COL32_G_SHIFT) & 0xFF) - col0_g;\r\n    const int col_delta_b = ((int)(col1 >> IM_COL32_B_SHIFT) & 0xFF) - col0_b;\r\n    for (ImDrawVert* vert = vert_start; vert < vert_end; vert++)\r\n    {\r\n        float d = ImDot(vert->pos - gradient_p0, gradient_extent);\r\n        float t = ImClamp(d * gradient_inv_length2, 0.0f, 1.0f);\r\n        int r = (int)(col0_r + col_delta_r * t);\r\n        int g = (int)(col0_g + col_delta_g * t);\r\n        int b = (int)(col0_b + col_delta_b * t);\r\n        vert->col = (r << IM_COL32_R_SHIFT) | (g << IM_COL32_G_SHIFT) | (b << IM_COL32_B_SHIFT) | (vert->col & IM_COL32_A_MASK);\r\n    }\r\n}\r\n\r\n// Distribute UV over (a, b) rectangle\r\nvoid ImGui::ShadeVertsLinearUV(ImDrawList* draw_list, int vert_start_idx, int vert_end_idx, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, bool clamp)\r\n{\r\n    const ImVec2 size = b - a;\r\n    const ImVec2 uv_size = uv_b - uv_a;\r\n    const ImVec2 scale = ImVec2(\r\n        size.x != 0.0f ? (uv_size.x / size.x) : 0.0f,\r\n        size.y != 0.0f ? (uv_size.y / size.y) : 0.0f);\r\n\r\n    ImDrawVert* vert_start = draw_list->VtxBuffer.Data + vert_start_idx;\r\n    ImDrawVert* vert_end = draw_list->VtxBuffer.Data + vert_end_idx;\r\n    if (clamp)\r\n    {\r\n        const ImVec2 min = ImMin(uv_a, uv_b);\r\n        const ImVec2 max = ImMax(uv_a, uv_b);\r\n        for (ImDrawVert* vertex = vert_start; vertex < vert_end; ++vertex)\r\n            vertex->uv = ImClamp(uv_a + ImMul(ImVec2(vertex->pos.x, vertex->pos.y) - a, scale), min, max);\r\n    }\r\n    else\r\n    {\r\n        for (ImDrawVert* vertex = vert_start; vertex < vert_end; ++vertex)\r\n            vertex->uv = uv_a + ImMul(ImVec2(vertex->pos.x, vertex->pos.y) - a, scale);\r\n    }\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] ImFontConfig\r\n//-----------------------------------------------------------------------------\r\n\r\nImFontConfig::ImFontConfig()\r\n{\r\n    memset(this, 0, sizeof(*this));\r\n    FontDataOwnedByAtlas = true;\r\n    OversampleH = 3; // FIXME: 2 may be a better default?\r\n    OversampleV = 1;\r\n    GlyphMaxAdvanceX = FLT_MAX;\r\n    RasterizerMultiply = 1.0f;\r\n    EllipsisChar = (ImWchar)-1;\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] ImFontAtlas\r\n//-----------------------------------------------------------------------------\r\n\r\n// A work of art lies ahead! (. = white layer, X = black layer, others are blank)\r\n// The 2x2 white texels on the top left are the ones we'll use everywhere in Dear ImGui to render filled shapes.\r\n// (This is used when io.MouseDrawCursor = true)\r\nconst int FONT_ATLAS_DEFAULT_TEX_DATA_W = 122; // Actual texture will be 2 times that + 1 spacing.\r\nconst int FONT_ATLAS_DEFAULT_TEX_DATA_H = 27;\r\nstatic const char FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS[FONT_ATLAS_DEFAULT_TEX_DATA_W * FONT_ATLAS_DEFAULT_TEX_DATA_H + 1] =\r\n{\r\n    \"..-         -XXXXXXX-    X    -           X           -XXXXXXX          -          XXXXXXX-     XX          - XX       XX \"\r\n    \"..-         -X.....X-   X.X   -          X.X          -X.....X          -          X.....X-    X..X         -X..X     X..X\"\r\n    \"---         -XXX.XXX-  X...X  -         X...X         -X....X           -           X....X-    X..X         -X...X   X...X\"\r\n    \"X           -  X.X  - X.....X -        X.....X        -X...X            -            X...X-    X..X         - X...X X...X \"\r\n    \"XX          -  X.X  -X.......X-       X.......X       -X..X.X           -           X.X..X-    X..X         -  X...X...X  \"\r\n    \"X.X         -  X.X  -XXXX.XXXX-       XXXX.XXXX       -X.X X.X          -          X.X X.X-    X..XXX       -   X.....X   \"\r\n    \"X..X        -  X.X  -   X.X   -          X.X          -XX   X.X         -         X.X   XX-    X..X..XXX    -    X...X    \"\r\n    \"X...X       -  X.X  -   X.X   -    XX    X.X    XX    -      X.X        -        X.X      -    X..X..X..XX  -     X.X     \"\r\n    \"X....X      -  X.X  -   X.X   -   X.X    X.X    X.X   -       X.X       -       X.X       -    X..X..X..X.X -    X...X    \"\r\n    \"X.....X     -  X.X  -   X.X   -  X..X    X.X    X..X  -        X.X      -      X.X        -XXX X..X..X..X..X-   X.....X   \"\r\n    \"X......X    -  X.X  -   X.X   - X...XXXXXX.XXXXXX...X -         X.X   XX-XX   X.X         -X..XX........X..X-  X...X...X  \"\r\n    \"X.......X   -  X.X  -   X.X   -X.....................X-          X.X X.X-X.X X.X          -X...X...........X- X...X X...X \"\r\n    \"X........X  -  X.X  -   X.X   - X...XXXXXX.XXXXXX...X -           X.X..X-X..X.X           - X..............X-X...X   X...X\"\r\n    \"X.........X -XXX.XXX-   X.X   -  X..X    X.X    X..X  -            X...X-X...X            -  X.............X-X..X     X..X\"\r\n    \"X..........X-X.....X-   X.X   -   X.X    X.X    X.X   -           X....X-X....X           -  X.............X- XX       XX \"\r\n    \"X......XXXXX-XXXXXXX-   X.X   -    XX    X.X    XX    -          X.....X-X.....X          -   X............X--------------\"\r\n    \"X...X..X    ---------   X.X   -          X.X          -          XXXXXXX-XXXXXXX          -   X...........X -             \"\r\n    \"X..X X..X   -       -XXXX.XXXX-       XXXX.XXXX       -------------------------------------    X..........X -             \"\r\n    \"X.X  X..X   -       -X.......X-       X.......X       -    XX           XX    -           -    X..........X -             \"\r\n    \"XX    X..X  -       - X.....X -        X.....X        -   X.X           X.X   -           -     X........X  -             \"\r\n    \"      X..X  -       -  X...X  -         X...X         -  X..X           X..X  -           -     X........X  -             \"\r\n    \"       XX   -       -   X.X   -          X.X          - X...XXXXXXXXXXXXX...X -           -     XXXXXXXXXX  -             \"\r\n    \"-------------       -    X    -           X           -X.....................X-           -------------------             \"\r\n    \"                    ----------------------------------- X...XXXXXXXXXXXXX...X -                                           \"\r\n    \"                                                      -  X..X           X..X  -                                           \"\r\n    \"                                                      -   X.X           X.X   -                                           \"\r\n    \"                                                      -    XX           XX    -                                           \"\r\n};\r\n\r\nstatic const ImVec2 FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[ImGuiMouseCursor_COUNT][3] =\r\n{\r\n    // Pos ........ Size ......... Offset ......\r\n    { ImVec2( 0,3), ImVec2(12,19), ImVec2( 0, 0) }, // ImGuiMouseCursor_Arrow\r\n    { ImVec2(13,0), ImVec2( 7,16), ImVec2( 1, 8) }, // ImGuiMouseCursor_TextInput\r\n    { ImVec2(31,0), ImVec2(23,23), ImVec2(11,11) }, // ImGuiMouseCursor_ResizeAll\r\n    { ImVec2(21,0), ImVec2( 9,23), ImVec2( 4,11) }, // ImGuiMouseCursor_ResizeNS\r\n    { ImVec2(55,18),ImVec2(23, 9), ImVec2(11, 4) }, // ImGuiMouseCursor_ResizeEW\r\n    { ImVec2(73,0), ImVec2(17,17), ImVec2( 8, 8) }, // ImGuiMouseCursor_ResizeNESW\r\n    { ImVec2(55,0), ImVec2(17,17), ImVec2( 8, 8) }, // ImGuiMouseCursor_ResizeNWSE\r\n    { ImVec2(91,0), ImVec2(17,22), ImVec2( 5, 0) }, // ImGuiMouseCursor_Hand\r\n    { ImVec2(109,0),ImVec2(13,15), ImVec2( 6, 7) }, // ImGuiMouseCursor_NotAllowed\r\n};\r\n\r\nImFontAtlas::ImFontAtlas()\r\n{\r\n    memset(this, 0, sizeof(*this));\r\n    TexGlyphPadding = 1;\r\n    PackIdMouseCursors = PackIdLines = -1;\r\n}\r\n\r\nImFontAtlas::~ImFontAtlas()\r\n{\r\n    IM_ASSERT(!Locked && \"Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!\");\r\n    Clear();\r\n}\r\n\r\nvoid    ImFontAtlas::ClearInputData()\r\n{\r\n    IM_ASSERT(!Locked && \"Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!\");\r\n    for (int i = 0; i < ConfigData.Size; i++)\r\n        if (ConfigData[i].FontData && ConfigData[i].FontDataOwnedByAtlas)\r\n        {\r\n            IM_FREE(ConfigData[i].FontData);\r\n            ConfigData[i].FontData = NULL;\r\n        }\r\n\r\n    // When clearing this we lose access to the font name and other information used to build the font.\r\n    for (int i = 0; i < Fonts.Size; i++)\r\n        if (Fonts[i]->ConfigData >= ConfigData.Data && Fonts[i]->ConfigData < ConfigData.Data + ConfigData.Size)\r\n        {\r\n            Fonts[i]->ConfigData = NULL;\r\n            Fonts[i]->ConfigDataCount = 0;\r\n        }\r\n    ConfigData.clear();\r\n    CustomRects.clear();\r\n    PackIdMouseCursors = PackIdLines = -1;\r\n    // Important: we leave TexReady untouched\r\n}\r\n\r\nvoid    ImFontAtlas::ClearTexData()\r\n{\r\n    IM_ASSERT(!Locked && \"Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!\");\r\n    if (TexPixelsAlpha8)\r\n        IM_FREE(TexPixelsAlpha8);\r\n    if (TexPixelsRGBA32)\r\n        IM_FREE(TexPixelsRGBA32);\r\n    TexPixelsAlpha8 = NULL;\r\n    TexPixelsRGBA32 = NULL;\r\n    TexPixelsUseColors = false;\r\n    // Important: we leave TexReady untouched\r\n}\r\n\r\nvoid    ImFontAtlas::ClearFonts()\r\n{\r\n    IM_ASSERT(!Locked && \"Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!\");\r\n    Fonts.clear_delete();\r\n    TexReady = false;\r\n}\r\n\r\nvoid    ImFontAtlas::Clear()\r\n{\r\n    ClearInputData();\r\n    ClearTexData();\r\n    ClearFonts();\r\n}\r\n\r\nvoid    ImFontAtlas::GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel)\r\n{\r\n    // Build atlas on demand\r\n    if (TexPixelsAlpha8 == NULL)\r\n        Build();\r\n\r\n    *out_pixels = TexPixelsAlpha8;\r\n    if (out_width) *out_width = TexWidth;\r\n    if (out_height) *out_height = TexHeight;\r\n    if (out_bytes_per_pixel) *out_bytes_per_pixel = 1;\r\n}\r\n\r\nvoid    ImFontAtlas::GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel)\r\n{\r\n    // Convert to RGBA32 format on demand\r\n    // Although it is likely to be the most commonly used format, our font rendering is 1 channel / 8 bpp\r\n    if (!TexPixelsRGBA32)\r\n    {\r\n        unsigned char* pixels = NULL;\r\n        GetTexDataAsAlpha8(&pixels, NULL, NULL);\r\n        if (pixels)\r\n        {\r\n            TexPixelsRGBA32 = (unsigned int*)IM_ALLOC((size_t)TexWidth * (size_t)TexHeight * 4);\r\n            const unsigned char* src = pixels;\r\n            unsigned int* dst = TexPixelsRGBA32;\r\n            for (int n = TexWidth * TexHeight; n > 0; n--)\r\n                *dst++ = IM_COL32(255, 255, 255, (unsigned int)(*src++));\r\n        }\r\n    }\r\n\r\n    *out_pixels = (unsigned char*)TexPixelsRGBA32;\r\n    if (out_width) *out_width = TexWidth;\r\n    if (out_height) *out_height = TexHeight;\r\n    if (out_bytes_per_pixel) *out_bytes_per_pixel = 4;\r\n}\r\n\r\nImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg)\r\n{\r\n    IM_ASSERT(!Locked && \"Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!\");\r\n    IM_ASSERT(font_cfg->FontData != NULL && font_cfg->FontDataSize > 0);\r\n    IM_ASSERT(font_cfg->SizePixels > 0.0f);\r\n\r\n    // Create new font\r\n    if (!font_cfg->MergeMode)\r\n        Fonts.push_back(IM_NEW(ImFont));\r\n    else\r\n        IM_ASSERT(!Fonts.empty() && \"Cannot use MergeMode for the first font\"); // When using MergeMode make sure that a font has already been added before. You can use ImGui::GetIO().Fonts->AddFontDefault() to add the default imgui font.\r\n\r\n    ConfigData.push_back(*font_cfg);\r\n    ImFontConfig& new_font_cfg = ConfigData.back();\r\n    if (new_font_cfg.DstFont == NULL)\r\n        new_font_cfg.DstFont = Fonts.back();\r\n    if (!new_font_cfg.FontDataOwnedByAtlas)\r\n    {\r\n        new_font_cfg.FontData = IM_ALLOC(new_font_cfg.FontDataSize);\r\n        new_font_cfg.FontDataOwnedByAtlas = true;\r\n        memcpy(new_font_cfg.FontData, font_cfg->FontData, (size_t)new_font_cfg.FontDataSize);\r\n    }\r\n\r\n    if (new_font_cfg.DstFont->EllipsisChar == (ImWchar)-1)\r\n        new_font_cfg.DstFont->EllipsisChar = font_cfg->EllipsisChar;\r\n\r\n    // Invalidate texture\r\n    TexReady = false;\r\n    ClearTexData();\r\n    return new_font_cfg.DstFont;\r\n}\r\n\r\n// Default font TTF is compressed with stb_compress then base85 encoded (see misc/fonts/binary_to_compressed_c.cpp for encoder)\r\nstatic unsigned int stb_decompress_length(const unsigned char* input);\r\nstatic unsigned int stb_decompress(unsigned char* output, const unsigned char* input, unsigned int length);\r\nstatic const char*  GetDefaultCompressedFontDataTTFBase85();\r\nstatic unsigned int Decode85Byte(char c)                                    { return c >= '\\\\' ? c-36 : c-35; }\r\nstatic void         Decode85(const unsigned char* src, unsigned char* dst)\r\n{\r\n    while (*src)\r\n    {\r\n        unsigned int tmp = Decode85Byte(src[0]) + 85 * (Decode85Byte(src[1]) + 85 * (Decode85Byte(src[2]) + 85 * (Decode85Byte(src[3]) + 85 * Decode85Byte(src[4]))));\r\n        dst[0] = ((tmp >> 0) & 0xFF); dst[1] = ((tmp >> 8) & 0xFF); dst[2] = ((tmp >> 16) & 0xFF); dst[3] = ((tmp >> 24) & 0xFF);   // We can't assume little-endianness.\r\n        src += 5;\r\n        dst += 4;\r\n    }\r\n}\r\n\r\n// Load embedded ProggyClean.ttf at size 13, disable oversampling\r\nImFont* ImFontAtlas::AddFontDefault(const ImFontConfig* font_cfg_template)\r\n{\r\n    ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig();\r\n    if (!font_cfg_template)\r\n    {\r\n        font_cfg.OversampleH = font_cfg.OversampleV = 1;\r\n        font_cfg.PixelSnapH = true;\r\n    }\r\n    if (font_cfg.SizePixels <= 0.0f)\r\n        font_cfg.SizePixels = 13.0f * 1.0f;\r\n    if (font_cfg.Name[0] == '\\0')\r\n        ImFormatString(font_cfg.Name, IM_ARRAYSIZE(font_cfg.Name), \"ProggyClean.ttf, %dpx\", (int)font_cfg.SizePixels);\r\n    font_cfg.EllipsisChar = (ImWchar)0x0085;\r\n    font_cfg.GlyphOffset.y = 1.0f * IM_FLOOR(font_cfg.SizePixels / 13.0f);  // Add +1 offset per 13 units\r\n\r\n    const char* ttf_compressed_base85 = GetDefaultCompressedFontDataTTFBase85();\r\n    const ImWchar* glyph_ranges = font_cfg.GlyphRanges != NULL ? font_cfg.GlyphRanges : GetGlyphRangesDefault();\r\n    ImFont* font = AddFontFromMemoryCompressedBase85TTF(ttf_compressed_base85, font_cfg.SizePixels, &font_cfg, glyph_ranges);\r\n    return font;\r\n}\r\n\r\nImFont* ImFontAtlas::AddFontFromFileTTF(const char* filename, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges)\r\n{\r\n    IM_ASSERT(!Locked && \"Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!\");\r\n    size_t data_size = 0;\r\n    void* data = ImFileLoadToMemory(filename, \"rb\", &data_size, 0);\r\n    if (!data)\r\n    {\r\n        IM_ASSERT_USER_ERROR(0, \"Could not load font file!\");\r\n        return NULL;\r\n    }\r\n    ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig();\r\n    if (font_cfg.Name[0] == '\\0')\r\n    {\r\n        // Store a short copy of filename into into the font name for convenience\r\n        const char* p;\r\n        for (p = filename + strlen(filename); p > filename && p[-1] != '/' && p[-1] != '\\\\'; p--) {}\r\n        ImFormatString(font_cfg.Name, IM_ARRAYSIZE(font_cfg.Name), \"%s, %.0fpx\", p, size_pixels);\r\n    }\r\n    return AddFontFromMemoryTTF(data, (int)data_size, size_pixels, &font_cfg, glyph_ranges);\r\n}\r\n\r\n// NB: Transfer ownership of 'ttf_data' to ImFontAtlas, unless font_cfg_template->FontDataOwnedByAtlas == false. Owned TTF buffer will be deleted after Build().\r\nImFont* ImFontAtlas::AddFontFromMemoryTTF(void* ttf_data, int ttf_size, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges)\r\n{\r\n    IM_ASSERT(!Locked && \"Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!\");\r\n    ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig();\r\n    IM_ASSERT(font_cfg.FontData == NULL);\r\n    font_cfg.FontData = ttf_data;\r\n    font_cfg.FontDataSize = ttf_size;\r\n    font_cfg.SizePixels = size_pixels > 0.0f ? size_pixels : font_cfg.SizePixels;\r\n    if (glyph_ranges)\r\n        font_cfg.GlyphRanges = glyph_ranges;\r\n    return AddFont(&font_cfg);\r\n}\r\n\r\nImFont* ImFontAtlas::AddFontFromMemoryCompressedTTF(const void* compressed_ttf_data, int compressed_ttf_size, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges)\r\n{\r\n    const unsigned int buf_decompressed_size = stb_decompress_length((const unsigned char*)compressed_ttf_data);\r\n    unsigned char* buf_decompressed_data = (unsigned char*)IM_ALLOC(buf_decompressed_size);\r\n    stb_decompress(buf_decompressed_data, (const unsigned char*)compressed_ttf_data, (unsigned int)compressed_ttf_size);\r\n\r\n    ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig();\r\n    IM_ASSERT(font_cfg.FontData == NULL);\r\n    font_cfg.FontDataOwnedByAtlas = true;\r\n    return AddFontFromMemoryTTF(buf_decompressed_data, (int)buf_decompressed_size, size_pixels, &font_cfg, glyph_ranges);\r\n}\r\n\r\nImFont* ImFontAtlas::AddFontFromMemoryCompressedBase85TTF(const char* compressed_ttf_data_base85, float size_pixels, const ImFontConfig* font_cfg, const ImWchar* glyph_ranges)\r\n{\r\n    int compressed_ttf_size = (((int)strlen(compressed_ttf_data_base85) + 4) / 5) * 4;\r\n    void* compressed_ttf = IM_ALLOC((size_t)compressed_ttf_size);\r\n    Decode85((const unsigned char*)compressed_ttf_data_base85, (unsigned char*)compressed_ttf);\r\n    ImFont* font = AddFontFromMemoryCompressedTTF(compressed_ttf, compressed_ttf_size, size_pixels, font_cfg, glyph_ranges);\r\n    IM_FREE(compressed_ttf);\r\n    return font;\r\n}\r\n\r\nint ImFontAtlas::AddCustomRectRegular(int width, int height)\r\n{\r\n    IM_ASSERT(width > 0 && width <= 0xFFFF);\r\n    IM_ASSERT(height > 0 && height <= 0xFFFF);\r\n    ImFontAtlasCustomRect r;\r\n    r.Width = (unsigned short)width;\r\n    r.Height = (unsigned short)height;\r\n    CustomRects.push_back(r);\r\n    return CustomRects.Size - 1; // Return index\r\n}\r\n\r\nint ImFontAtlas::AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int height, float advance_x, const ImVec2& offset)\r\n{\r\n#ifdef IMGUI_USE_WCHAR32\r\n    IM_ASSERT(id <= IM_UNICODE_CODEPOINT_MAX);\r\n#endif\r\n    IM_ASSERT(font != NULL);\r\n    IM_ASSERT(width > 0 && width <= 0xFFFF);\r\n    IM_ASSERT(height > 0 && height <= 0xFFFF);\r\n    ImFontAtlasCustomRect r;\r\n    r.Width = (unsigned short)width;\r\n    r.Height = (unsigned short)height;\r\n    r.GlyphID = id;\r\n    r.GlyphAdvanceX = advance_x;\r\n    r.GlyphOffset = offset;\r\n    r.Font = font;\r\n    CustomRects.push_back(r);\r\n    return CustomRects.Size - 1; // Return index\r\n}\r\n\r\nvoid ImFontAtlas::CalcCustomRectUV(const ImFontAtlasCustomRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max) const\r\n{\r\n    IM_ASSERT(TexWidth > 0 && TexHeight > 0);   // Font atlas needs to be built before we can calculate UV coordinates\r\n    IM_ASSERT(rect->IsPacked());                // Make sure the rectangle has been packed\r\n    *out_uv_min = ImVec2((float)rect->X * TexUvScale.x, (float)rect->Y * TexUvScale.y);\r\n    *out_uv_max = ImVec2((float)(rect->X + rect->Width) * TexUvScale.x, (float)(rect->Y + rect->Height) * TexUvScale.y);\r\n}\r\n\r\nbool ImFontAtlas::GetMouseCursorTexData(ImGuiMouseCursor cursor_type, ImVec2* out_offset, ImVec2* out_size, ImVec2 out_uv_border[2], ImVec2 out_uv_fill[2])\r\n{\r\n    if (cursor_type <= ImGuiMouseCursor_None || cursor_type >= ImGuiMouseCursor_COUNT)\r\n        return false;\r\n    if (Flags & ImFontAtlasFlags_NoMouseCursors)\r\n        return false;\r\n\r\n    IM_ASSERT(PackIdMouseCursors != -1);\r\n    ImFontAtlasCustomRect* r = GetCustomRectByIndex(PackIdMouseCursors);\r\n    ImVec2 pos = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][0] + ImVec2((float)r->X, (float)r->Y);\r\n    ImVec2 size = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][1];\r\n    *out_size = size;\r\n    *out_offset = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][2];\r\n    out_uv_border[0] = (pos) * TexUvScale;\r\n    out_uv_border[1] = (pos + size) * TexUvScale;\r\n    pos.x += FONT_ATLAS_DEFAULT_TEX_DATA_W + 1;\r\n    out_uv_fill[0] = (pos) * TexUvScale;\r\n    out_uv_fill[1] = (pos + size) * TexUvScale;\r\n    return true;\r\n}\r\n\r\nbool    ImFontAtlas::Build()\r\n{\r\n    IM_ASSERT(!Locked && \"Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!\");\r\n\r\n    // Default font is none are specified\r\n    if (ConfigData.Size == 0)\r\n        AddFontDefault();\r\n\r\n    // Select builder\r\n    // - Note that we do not reassign to atlas->FontBuilderIO, since it is likely to point to static data which\r\n    //   may mess with some hot-reloading schemes. If you need to assign to this (for dynamic selection) AND are\r\n    //   using a hot-reloading scheme that messes up static data, store your own instance of ImFontBuilderIO somewhere\r\n    //   and point to it instead of pointing directly to return value of the GetBuilderXXX functions.\r\n    const ImFontBuilderIO* builder_io = FontBuilderIO;\r\n    if (builder_io == NULL)\r\n    {\r\n#ifdef IMGUI_ENABLE_FREETYPE\r\n        builder_io = ImGuiFreeType::GetBuilderForFreeType();\r\n#elif defined(IMGUI_ENABLE_STB_TRUETYPE)\r\n        builder_io = ImFontAtlasGetBuilderForStbTruetype();\r\n#else\r\n        IM_ASSERT(0); // Invalid Build function\r\n#endif\r\n    }\r\n\r\n    // Build\r\n    return builder_io->FontBuilder_Build(this);\r\n}\r\n\r\nvoid    ImFontAtlasBuildMultiplyCalcLookupTable(unsigned char out_table[256], float in_brighten_factor)\r\n{\r\n    for (unsigned int i = 0; i < 256; i++)\r\n    {\r\n        unsigned int value = (unsigned int)(i * in_brighten_factor);\r\n        out_table[i] = value > 255 ? 255 : (value & 0xFF);\r\n    }\r\n}\r\n\r\nvoid    ImFontAtlasBuildMultiplyRectAlpha8(const unsigned char table[256], unsigned char* pixels, int x, int y, int w, int h, int stride)\r\n{\r\n    unsigned char* data = pixels + x + y * stride;\r\n    for (int j = h; j > 0; j--, data += stride)\r\n        for (int i = 0; i < w; i++)\r\n            data[i] = table[data[i]];\r\n}\r\n\r\n#ifdef IMGUI_ENABLE_STB_TRUETYPE\r\n// Temporary data for one source font (multiple source fonts can be merged into one destination ImFont)\r\n// (C++03 doesn't allow instancing ImVector<> with function-local types so we declare the type here.)\r\nstruct ImFontBuildSrcData\r\n{\r\n    stbtt_fontinfo      FontInfo;\r\n    stbtt_pack_range    PackRange;          // Hold the list of codepoints to pack (essentially points to Codepoints.Data)\r\n    stbrp_rect*         Rects;              // Rectangle to pack. We first fill in their size and the packer will give us their position.\r\n    stbtt_packedchar*   PackedChars;        // Output glyphs\r\n    const ImWchar*      SrcRanges;          // Ranges as requested by user (user is allowed to request too much, e.g. 0x0020..0xFFFF)\r\n    int                 DstIndex;           // Index into atlas->Fonts[] and dst_tmp_array[]\r\n    int                 GlyphsHighest;      // Highest requested codepoint\r\n    int                 GlyphsCount;        // Glyph count (excluding missing glyphs and glyphs already set by an earlier source font)\r\n    ImBitVector         GlyphsSet;          // Glyph bit map (random access, 1-bit per codepoint. This will be a maximum of 8KB)\r\n    ImVector<int>       GlyphsList;         // Glyph codepoints list (flattened version of GlyphsMap)\r\n};\r\n\r\n// Temporary data for one destination ImFont* (multiple source fonts can be merged into one destination ImFont)\r\nstruct ImFontBuildDstData\r\n{\r\n    int                 SrcCount;           // Number of source fonts targeting this destination font.\r\n    int                 GlyphsHighest;\r\n    int                 GlyphsCount;\r\n    ImBitVector         GlyphsSet;          // This is used to resolve collision when multiple sources are merged into a same destination font.\r\n};\r\n\r\nstatic void UnpackBitVectorToFlatIndexList(const ImBitVector* in, ImVector<int>* out)\r\n{\r\n    IM_ASSERT(sizeof(in->Storage.Data[0]) == sizeof(int));\r\n    const ImU32* it_begin = in->Storage.begin();\r\n    const ImU32* it_end = in->Storage.end();\r\n    for (const ImU32* it = it_begin; it < it_end; it++)\r\n        if (ImU32 entries_32 = *it)\r\n            for (ImU32 bit_n = 0; bit_n < 32; bit_n++)\r\n                if (entries_32 & ((ImU32)1 << bit_n))\r\n                    out->push_back((int)(((it - it_begin) << 5) + bit_n));\r\n}\r\n\r\nstatic bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas)\r\n{\r\n    IM_ASSERT(atlas->ConfigData.Size > 0);\r\n\r\n    ImFontAtlasBuildInit(atlas);\r\n\r\n    // Clear atlas\r\n    atlas->TexID = (ImTextureID)NULL;\r\n    atlas->TexWidth = atlas->TexHeight = 0;\r\n    atlas->TexUvScale = ImVec2(0.0f, 0.0f);\r\n    atlas->TexUvWhitePixel = ImVec2(0.0f, 0.0f);\r\n    atlas->ClearTexData();\r\n\r\n    // Temporary storage for building\r\n    ImVector<ImFontBuildSrcData> src_tmp_array;\r\n    ImVector<ImFontBuildDstData> dst_tmp_array;\r\n    src_tmp_array.resize(atlas->ConfigData.Size);\r\n    dst_tmp_array.resize(atlas->Fonts.Size);\r\n    memset(src_tmp_array.Data, 0, (size_t)src_tmp_array.size_in_bytes());\r\n    memset(dst_tmp_array.Data, 0, (size_t)dst_tmp_array.size_in_bytes());\r\n\r\n    // 1. Initialize font loading structure, check font data validity\r\n    for (int src_i = 0; src_i < atlas->ConfigData.Size; src_i++)\r\n    {\r\n        ImFontBuildSrcData& src_tmp = src_tmp_array[src_i];\r\n        ImFontConfig& cfg = atlas->ConfigData[src_i];\r\n        IM_ASSERT(cfg.DstFont && (!cfg.DstFont->IsLoaded() || cfg.DstFont->ContainerAtlas == atlas));\r\n\r\n        // Find index from cfg.DstFont (we allow the user to set cfg.DstFont. Also it makes casual debugging nicer than when storing indices)\r\n        src_tmp.DstIndex = -1;\r\n        for (int output_i = 0; output_i < atlas->Fonts.Size && src_tmp.DstIndex == -1; output_i++)\r\n            if (cfg.DstFont == atlas->Fonts[output_i])\r\n                src_tmp.DstIndex = output_i;\r\n        if (src_tmp.DstIndex == -1)\r\n        {\r\n            IM_ASSERT(src_tmp.DstIndex != -1); // cfg.DstFont not pointing within atlas->Fonts[] array?\r\n            return false;\r\n        }\r\n        // Initialize helper structure for font loading and verify that the TTF/OTF data is correct\r\n        const int font_offset = stbtt_GetFontOffsetForIndex((unsigned char*)cfg.FontData, cfg.FontNo);\r\n        IM_ASSERT(font_offset >= 0 && \"FontData is incorrect, or FontNo cannot be found.\");\r\n        if (!stbtt_InitFont(&src_tmp.FontInfo, (unsigned char*)cfg.FontData, font_offset))\r\n            return false;\r\n\r\n        // Measure highest codepoints\r\n        ImFontBuildDstData& dst_tmp = dst_tmp_array[src_tmp.DstIndex];\r\n        src_tmp.SrcRanges = cfg.GlyphRanges ? cfg.GlyphRanges : atlas->GetGlyphRangesDefault();\r\n        for (const ImWchar* src_range = src_tmp.SrcRanges; src_range[0] && src_range[1]; src_range += 2)\r\n            src_tmp.GlyphsHighest = ImMax(src_tmp.GlyphsHighest, (int)src_range[1]);\r\n        dst_tmp.SrcCount++;\r\n        dst_tmp.GlyphsHighest = ImMax(dst_tmp.GlyphsHighest, src_tmp.GlyphsHighest);\r\n    }\r\n\r\n    // 2. For every requested codepoint, check for their presence in the font data, and handle redundancy or overlaps between source fonts to avoid unused glyphs.\r\n    int total_glyphs_count = 0;\r\n    for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)\r\n    {\r\n        ImFontBuildSrcData& src_tmp = src_tmp_array[src_i];\r\n        ImFontBuildDstData& dst_tmp = dst_tmp_array[src_tmp.DstIndex];\r\n        src_tmp.GlyphsSet.Create(src_tmp.GlyphsHighest + 1);\r\n        if (dst_tmp.GlyphsSet.Storage.empty())\r\n            dst_tmp.GlyphsSet.Create(dst_tmp.GlyphsHighest + 1);\r\n\r\n        for (const ImWchar* src_range = src_tmp.SrcRanges; src_range[0] && src_range[1]; src_range += 2)\r\n            for (unsigned int codepoint = src_range[0]; codepoint <= src_range[1]; codepoint++)\r\n            {\r\n                if (dst_tmp.GlyphsSet.TestBit(codepoint))    // Don't overwrite existing glyphs. We could make this an option for MergeMode (e.g. MergeOverwrite==true)\r\n                    continue;\r\n                if (!stbtt_FindGlyphIndex(&src_tmp.FontInfo, codepoint))    // It is actually in the font?\r\n                    continue;\r\n\r\n                // Add to avail set/counters\r\n                src_tmp.GlyphsCount++;\r\n                dst_tmp.GlyphsCount++;\r\n                src_tmp.GlyphsSet.SetBit(codepoint);\r\n                dst_tmp.GlyphsSet.SetBit(codepoint);\r\n                total_glyphs_count++;\r\n            }\r\n    }\r\n\r\n    // 3. Unpack our bit map into a flat list (we now have all the Unicode points that we know are requested _and_ available _and_ not overlapping another)\r\n    for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)\r\n    {\r\n        ImFontBuildSrcData& src_tmp = src_tmp_array[src_i];\r\n        src_tmp.GlyphsList.reserve(src_tmp.GlyphsCount);\r\n        UnpackBitVectorToFlatIndexList(&src_tmp.GlyphsSet, &src_tmp.GlyphsList);\r\n        src_tmp.GlyphsSet.Clear();\r\n        IM_ASSERT(src_tmp.GlyphsList.Size == src_tmp.GlyphsCount);\r\n    }\r\n    for (int dst_i = 0; dst_i < dst_tmp_array.Size; dst_i++)\r\n        dst_tmp_array[dst_i].GlyphsSet.Clear();\r\n    dst_tmp_array.clear();\r\n\r\n    // Allocate packing character data and flag packed characters buffer as non-packed (x0=y0=x1=y1=0)\r\n    // (We technically don't need to zero-clear buf_rects, but let's do it for the sake of sanity)\r\n    ImVector<stbrp_rect> buf_rects;\r\n    ImVector<stbtt_packedchar> buf_packedchars;\r\n    buf_rects.resize(total_glyphs_count);\r\n    buf_packedchars.resize(total_glyphs_count);\r\n    memset(buf_rects.Data, 0, (size_t)buf_rects.size_in_bytes());\r\n    memset(buf_packedchars.Data, 0, (size_t)buf_packedchars.size_in_bytes());\r\n\r\n    // 4. Gather glyphs sizes so we can pack them in our virtual canvas.\r\n    int total_surface = 0;\r\n    int buf_rects_out_n = 0;\r\n    int buf_packedchars_out_n = 0;\r\n    for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)\r\n    {\r\n        ImFontBuildSrcData& src_tmp = src_tmp_array[src_i];\r\n        if (src_tmp.GlyphsCount == 0)\r\n            continue;\r\n\r\n        src_tmp.Rects = &buf_rects[buf_rects_out_n];\r\n        src_tmp.PackedChars = &buf_packedchars[buf_packedchars_out_n];\r\n        buf_rects_out_n += src_tmp.GlyphsCount;\r\n        buf_packedchars_out_n += src_tmp.GlyphsCount;\r\n\r\n        // Convert our ranges in the format stb_truetype wants\r\n        ImFontConfig& cfg = atlas->ConfigData[src_i];\r\n        src_tmp.PackRange.font_size = cfg.SizePixels;\r\n        src_tmp.PackRange.first_unicode_codepoint_in_range = 0;\r\n        src_tmp.PackRange.array_of_unicode_codepoints = src_tmp.GlyphsList.Data;\r\n        src_tmp.PackRange.num_chars = src_tmp.GlyphsList.Size;\r\n        src_tmp.PackRange.chardata_for_range = src_tmp.PackedChars;\r\n        src_tmp.PackRange.h_oversample = (unsigned char)cfg.OversampleH;\r\n        src_tmp.PackRange.v_oversample = (unsigned char)cfg.OversampleV;\r\n\r\n        // Gather the sizes of all rectangles we will need to pack (this loop is based on stbtt_PackFontRangesGatherRects)\r\n        const float scale = (cfg.SizePixels > 0) ? stbtt_ScaleForPixelHeight(&src_tmp.FontInfo, cfg.SizePixels) : stbtt_ScaleForMappingEmToPixels(&src_tmp.FontInfo, -cfg.SizePixels);\r\n        const int padding = atlas->TexGlyphPadding;\r\n        for (int glyph_i = 0; glyph_i < src_tmp.GlyphsList.Size; glyph_i++)\r\n        {\r\n            int x0, y0, x1, y1;\r\n            const int glyph_index_in_font = stbtt_FindGlyphIndex(&src_tmp.FontInfo, src_tmp.GlyphsList[glyph_i]);\r\n            IM_ASSERT(glyph_index_in_font != 0);\r\n            stbtt_GetGlyphBitmapBoxSubpixel(&src_tmp.FontInfo, glyph_index_in_font, scale * cfg.OversampleH, scale * cfg.OversampleV, 0, 0, &x0, &y0, &x1, &y1);\r\n            src_tmp.Rects[glyph_i].w = (stbrp_coord)(x1 - x0 + padding + cfg.OversampleH - 1);\r\n            src_tmp.Rects[glyph_i].h = (stbrp_coord)(y1 - y0 + padding + cfg.OversampleV - 1);\r\n            total_surface += src_tmp.Rects[glyph_i].w * src_tmp.Rects[glyph_i].h;\r\n        }\r\n    }\r\n\r\n    // We need a width for the skyline algorithm, any width!\r\n    // The exact width doesn't really matter much, but some API/GPU have texture size limitations and increasing width can decrease height.\r\n    // User can override TexDesiredWidth and TexGlyphPadding if they wish, otherwise we use a simple heuristic to select the width based on expected surface.\r\n    const int surface_sqrt = (int)ImSqrt((float)total_surface) + 1;\r\n    atlas->TexHeight = 0;\r\n    if (atlas->TexDesiredWidth > 0)\r\n        atlas->TexWidth = atlas->TexDesiredWidth;\r\n    else\r\n        atlas->TexWidth = (surface_sqrt >= 4096 * 0.7f) ? 4096 : (surface_sqrt >= 2048 * 0.7f) ? 2048 : (surface_sqrt >= 1024 * 0.7f) ? 1024 : 512;\r\n\r\n    // 5. Start packing\r\n    // Pack our extra data rectangles first, so it will be on the upper-left corner of our texture (UV will have small values).\r\n    const int TEX_HEIGHT_MAX = 1024 * 32;\r\n    stbtt_pack_context spc = {};\r\n    stbtt_PackBegin(&spc, NULL, atlas->TexWidth, TEX_HEIGHT_MAX, 0, atlas->TexGlyphPadding, NULL);\r\n    ImFontAtlasBuildPackCustomRects(atlas, spc.pack_info);\r\n\r\n    // 6. Pack each source font. No rendering yet, we are working with rectangles in an infinitely tall texture at this point.\r\n    for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)\r\n    {\r\n        ImFontBuildSrcData& src_tmp = src_tmp_array[src_i];\r\n        if (src_tmp.GlyphsCount == 0)\r\n            continue;\r\n\r\n        stbrp_pack_rects((stbrp_context*)spc.pack_info, src_tmp.Rects, src_tmp.GlyphsCount);\r\n\r\n        // Extend texture height and mark missing glyphs as non-packed so we won't render them.\r\n        // FIXME: We are not handling packing failure here (would happen if we got off TEX_HEIGHT_MAX or if a single if larger than TexWidth?)\r\n        for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++)\r\n            if (src_tmp.Rects[glyph_i].was_packed)\r\n                atlas->TexHeight = ImMax(atlas->TexHeight, src_tmp.Rects[glyph_i].y + src_tmp.Rects[glyph_i].h);\r\n    }\r\n\r\n    // 7. Allocate texture\r\n    atlas->TexHeight = (atlas->Flags & ImFontAtlasFlags_NoPowerOfTwoHeight) ? (atlas->TexHeight + 1) : ImUpperPowerOfTwo(atlas->TexHeight);\r\n    atlas->TexUvScale = ImVec2(1.0f / atlas->TexWidth, 1.0f / atlas->TexHeight);\r\n    atlas->TexPixelsAlpha8 = (unsigned char*)IM_ALLOC(atlas->TexWidth * atlas->TexHeight);\r\n    memset(atlas->TexPixelsAlpha8, 0, atlas->TexWidth * atlas->TexHeight);\r\n    spc.pixels = atlas->TexPixelsAlpha8;\r\n    spc.height = atlas->TexHeight;\r\n\r\n    // 8. Render/rasterize font characters into the texture\r\n    for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)\r\n    {\r\n        ImFontConfig& cfg = atlas->ConfigData[src_i];\r\n        ImFontBuildSrcData& src_tmp = src_tmp_array[src_i];\r\n        if (src_tmp.GlyphsCount == 0)\r\n            continue;\r\n\r\n        stbtt_PackFontRangesRenderIntoRects(&spc, &src_tmp.FontInfo, &src_tmp.PackRange, 1, src_tmp.Rects);\r\n\r\n        // Apply multiply operator\r\n        if (cfg.RasterizerMultiply != 1.0f)\r\n        {\r\n            unsigned char multiply_table[256];\r\n            ImFontAtlasBuildMultiplyCalcLookupTable(multiply_table, cfg.RasterizerMultiply);\r\n            stbrp_rect* r = &src_tmp.Rects[0];\r\n            for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++, r++)\r\n                if (r->was_packed)\r\n                    ImFontAtlasBuildMultiplyRectAlpha8(multiply_table, atlas->TexPixelsAlpha8, r->x, r->y, r->w, r->h, atlas->TexWidth * 1);\r\n        }\r\n        src_tmp.Rects = NULL;\r\n    }\r\n\r\n    // End packing\r\n    stbtt_PackEnd(&spc);\r\n    buf_rects.clear();\r\n\r\n    // 9. Setup ImFont and glyphs for runtime\r\n    for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)\r\n    {\r\n        ImFontBuildSrcData& src_tmp = src_tmp_array[src_i];\r\n        if (src_tmp.GlyphsCount == 0)\r\n            continue;\r\n\r\n        // When merging fonts with MergeMode=true:\r\n        // - We can have multiple input fonts writing into a same destination font.\r\n        // - dst_font->ConfigData is != from cfg which is our source configuration.\r\n        ImFontConfig& cfg = atlas->ConfigData[src_i];\r\n        ImFont* dst_font = cfg.DstFont;\r\n\r\n        const float font_scale = stbtt_ScaleForPixelHeight(&src_tmp.FontInfo, cfg.SizePixels);\r\n        int unscaled_ascent, unscaled_descent, unscaled_line_gap;\r\n        stbtt_GetFontVMetrics(&src_tmp.FontInfo, &unscaled_ascent, &unscaled_descent, &unscaled_line_gap);\r\n\r\n        const float ascent = ImFloor(unscaled_ascent * font_scale + ((unscaled_ascent > 0.0f) ? +1 : -1));\r\n        const float descent = ImFloor(unscaled_descent * font_scale + ((unscaled_descent > 0.0f) ? +1 : -1));\r\n        ImFontAtlasBuildSetupFont(atlas, dst_font, &cfg, ascent, descent);\r\n        const float font_off_x = cfg.GlyphOffset.x;\r\n        const float font_off_y = cfg.GlyphOffset.y + IM_ROUND(dst_font->Ascent);\r\n\r\n        for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++)\r\n        {\r\n            // Register glyph\r\n            const int codepoint = src_tmp.GlyphsList[glyph_i];\r\n            const stbtt_packedchar& pc = src_tmp.PackedChars[glyph_i];\r\n            stbtt_aligned_quad q;\r\n            float unused_x = 0.0f, unused_y = 0.0f;\r\n            stbtt_GetPackedQuad(src_tmp.PackedChars, atlas->TexWidth, atlas->TexHeight, glyph_i, &unused_x, &unused_y, &q, 0);\r\n            dst_font->AddGlyph(&cfg, (ImWchar)codepoint, q.x0 + font_off_x, q.y0 + font_off_y, q.x1 + font_off_x, q.y1 + font_off_y, q.s0, q.t0, q.s1, q.t1, pc.xadvance);\r\n        }\r\n    }\r\n\r\n    // Cleanup\r\n    src_tmp_array.clear_destruct();\r\n\r\n    ImFontAtlasBuildFinish(atlas);\r\n    return true;\r\n}\r\n\r\nconst ImFontBuilderIO* ImFontAtlasGetBuilderForStbTruetype()\r\n{\r\n    static ImFontBuilderIO io;\r\n    io.FontBuilder_Build = ImFontAtlasBuildWithStbTruetype;\r\n    return &io;\r\n}\r\n\r\n#endif // IMGUI_ENABLE_STB_TRUETYPE\r\n\r\nvoid ImFontAtlasBuildSetupFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* font_config, float ascent, float descent)\r\n{\r\n    if (!font_config->MergeMode)\r\n    {\r\n        font->ClearOutputData();\r\n        font->FontSize = font_config->SizePixels;\r\n        font->ConfigData = font_config;\r\n        font->ConfigDataCount = 0;\r\n        font->ContainerAtlas = atlas;\r\n        font->Ascent = ascent;\r\n        font->Descent = descent;\r\n    }\r\n    font->ConfigDataCount++;\r\n}\r\n\r\nvoid ImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas, void* stbrp_context_opaque)\r\n{\r\n    stbrp_context* pack_context = (stbrp_context*)stbrp_context_opaque;\r\n    IM_ASSERT(pack_context != NULL);\r\n\r\n    ImVector<ImFontAtlasCustomRect>& user_rects = atlas->CustomRects;\r\n    IM_ASSERT(user_rects.Size >= 1); // We expect at least the default custom rects to be registered, else something went wrong.\r\n\r\n    ImVector<stbrp_rect> pack_rects;\r\n    pack_rects.resize(user_rects.Size);\r\n    memset(pack_rects.Data, 0, (size_t)pack_rects.size_in_bytes());\r\n    for (int i = 0; i < user_rects.Size; i++)\r\n    {\r\n        pack_rects[i].w = user_rects[i].Width;\r\n        pack_rects[i].h = user_rects[i].Height;\r\n    }\r\n    stbrp_pack_rects(pack_context, &pack_rects[0], pack_rects.Size);\r\n    for (int i = 0; i < pack_rects.Size; i++)\r\n        if (pack_rects[i].was_packed)\r\n        {\r\n            user_rects[i].X = pack_rects[i].x;\r\n            user_rects[i].Y = pack_rects[i].y;\r\n            IM_ASSERT(pack_rects[i].w == user_rects[i].Width && pack_rects[i].h == user_rects[i].Height);\r\n            atlas->TexHeight = ImMax(atlas->TexHeight, pack_rects[i].y + pack_rects[i].h);\r\n        }\r\n}\r\n\r\nvoid ImFontAtlasBuildRender8bppRectFromString(ImFontAtlas* atlas, int x, int y, int w, int h, const char* in_str, char in_marker_char, unsigned char in_marker_pixel_value)\r\n{\r\n    IM_ASSERT(x >= 0 && x + w <= atlas->TexWidth);\r\n    IM_ASSERT(y >= 0 && y + h <= atlas->TexHeight);\r\n    unsigned char* out_pixel = atlas->TexPixelsAlpha8 + x + (y * atlas->TexWidth);\r\n    for (int off_y = 0; off_y < h; off_y++, out_pixel += atlas->TexWidth, in_str += w)\r\n        for (int off_x = 0; off_x < w; off_x++)\r\n            out_pixel[off_x] = (in_str[off_x] == in_marker_char) ? in_marker_pixel_value : 0x00;\r\n}\r\n\r\nvoid ImFontAtlasBuildRender32bppRectFromString(ImFontAtlas* atlas, int x, int y, int w, int h, const char* in_str, char in_marker_char, unsigned int in_marker_pixel_value)\r\n{\r\n    IM_ASSERT(x >= 0 && x + w <= atlas->TexWidth);\r\n    IM_ASSERT(y >= 0 && y + h <= atlas->TexHeight);\r\n    unsigned int* out_pixel = atlas->TexPixelsRGBA32 + x + (y * atlas->TexWidth);\r\n    for (int off_y = 0; off_y < h; off_y++, out_pixel += atlas->TexWidth, in_str += w)\r\n        for (int off_x = 0; off_x < w; off_x++)\r\n            out_pixel[off_x] = (in_str[off_x] == in_marker_char) ? in_marker_pixel_value : IM_COL32_BLACK_TRANS;\r\n}\r\n\r\nstatic void ImFontAtlasBuildRenderDefaultTexData(ImFontAtlas* atlas)\r\n{\r\n    ImFontAtlasCustomRect* r = atlas->GetCustomRectByIndex(atlas->PackIdMouseCursors);\r\n    IM_ASSERT(r->IsPacked());\r\n\r\n    const int w = atlas->TexWidth;\r\n    if (!(atlas->Flags & ImFontAtlasFlags_NoMouseCursors))\r\n    {\r\n        // Render/copy pixels\r\n        IM_ASSERT(r->Width == FONT_ATLAS_DEFAULT_TEX_DATA_W * 2 + 1 && r->Height == FONT_ATLAS_DEFAULT_TEX_DATA_H);\r\n        const int x_for_white = r->X;\r\n        const int x_for_black = r->X + FONT_ATLAS_DEFAULT_TEX_DATA_W + 1;\r\n        if (atlas->TexPixelsAlpha8 != NULL)\r\n        {\r\n            ImFontAtlasBuildRender8bppRectFromString(atlas, x_for_white, r->Y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, '.', 0xFF);\r\n            ImFontAtlasBuildRender8bppRectFromString(atlas, x_for_black, r->Y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, 'X', 0xFF);\r\n        }\r\n        else\r\n        {\r\n            ImFontAtlasBuildRender32bppRectFromString(atlas, x_for_white, r->Y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, '.', IM_COL32_WHITE);\r\n            ImFontAtlasBuildRender32bppRectFromString(atlas, x_for_black, r->Y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, 'X', IM_COL32_WHITE);\r\n        }\r\n    }\r\n    else\r\n    {\r\n        // Render 4 white pixels\r\n        IM_ASSERT(r->Width == 2 && r->Height == 2);\r\n        const int offset = (int)r->X + (int)r->Y * w;\r\n        if (atlas->TexPixelsAlpha8 != NULL)\r\n        {\r\n            atlas->TexPixelsAlpha8[offset] = atlas->TexPixelsAlpha8[offset + 1] = atlas->TexPixelsAlpha8[offset + w] = atlas->TexPixelsAlpha8[offset + w + 1] = 0xFF;\r\n        }\r\n        else\r\n        {\r\n            atlas->TexPixelsRGBA32[offset] = atlas->TexPixelsRGBA32[offset + 1] = atlas->TexPixelsRGBA32[offset + w] = atlas->TexPixelsRGBA32[offset + w + 1] = IM_COL32_WHITE;\r\n        }\r\n    }\r\n    atlas->TexUvWhitePixel = ImVec2((r->X + 0.5f) * atlas->TexUvScale.x, (r->Y + 0.5f) * atlas->TexUvScale.y);\r\n}\r\n\r\nstatic void ImFontAtlasBuildRenderLinesTexData(ImFontAtlas* atlas)\r\n{\r\n    if (atlas->Flags & ImFontAtlasFlags_NoBakedLines)\r\n        return;\r\n\r\n    // This generates a triangular shape in the texture, with the various line widths stacked on top of each other to allow interpolation between them\r\n    ImFontAtlasCustomRect* r = atlas->GetCustomRectByIndex(atlas->PackIdLines);\r\n    IM_ASSERT(r->IsPacked());\r\n    for (unsigned int n = 0; n < IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1; n++) // +1 because of the zero-width row\r\n    {\r\n        // Each line consists of at least two empty pixels at the ends, with a line of solid pixels in the middle\r\n        unsigned int y = n;\r\n        unsigned int line_width = n;\r\n        unsigned int pad_left = (r->Width - line_width) / 2;\r\n        unsigned int pad_right = r->Width - (pad_left + line_width);\r\n\r\n        // Write each slice\r\n        IM_ASSERT(pad_left + line_width + pad_right == r->Width && y < r->Height); // Make sure we're inside the texture bounds before we start writing pixels\r\n        if (atlas->TexPixelsAlpha8 != NULL)\r\n        {\r\n            unsigned char* write_ptr = &atlas->TexPixelsAlpha8[r->X + ((r->Y + y) * atlas->TexWidth)];\r\n            for (unsigned int i = 0; i < pad_left; i++)\r\n                *(write_ptr + i) = 0x00;\r\n\r\n            for (unsigned int i = 0; i < line_width; i++)\r\n                *(write_ptr + pad_left + i) = 0xFF;\r\n\r\n            for (unsigned int i = 0; i < pad_right; i++)\r\n                *(write_ptr + pad_left + line_width + i) = 0x00;\r\n        }\r\n        else\r\n        {\r\n            unsigned int* write_ptr = &atlas->TexPixelsRGBA32[r->X + ((r->Y + y) * atlas->TexWidth)];\r\n            for (unsigned int i = 0; i < pad_left; i++)\r\n                *(write_ptr + i) = IM_COL32_BLACK_TRANS;\r\n\r\n            for (unsigned int i = 0; i < line_width; i++)\r\n                *(write_ptr + pad_left + i) = IM_COL32_WHITE;\r\n\r\n            for (unsigned int i = 0; i < pad_right; i++)\r\n                *(write_ptr + pad_left + line_width + i) = IM_COL32_BLACK_TRANS;\r\n        }\r\n\r\n        // Calculate UVs for this line\r\n        ImVec2 uv0 = ImVec2((float)(r->X + pad_left - 1), (float)(r->Y + y)) * atlas->TexUvScale;\r\n        ImVec2 uv1 = ImVec2((float)(r->X + pad_left + line_width + 1), (float)(r->Y + y + 1)) * atlas->TexUvScale;\r\n        float half_v = (uv0.y + uv1.y) * 0.5f; // Calculate a constant V in the middle of the row to avoid sampling artifacts\r\n        atlas->TexUvLines[n] = ImVec4(uv0.x, half_v, uv1.x, half_v);\r\n    }\r\n}\r\n\r\n// Note: this is called / shared by both the stb_truetype and the FreeType builder\r\nvoid ImFontAtlasBuildInit(ImFontAtlas* atlas)\r\n{\r\n    // Register texture region for mouse cursors or standard white pixels\r\n    if (atlas->PackIdMouseCursors < 0)\r\n    {\r\n        if (!(atlas->Flags & ImFontAtlasFlags_NoMouseCursors))\r\n            atlas->PackIdMouseCursors = atlas->AddCustomRectRegular(FONT_ATLAS_DEFAULT_TEX_DATA_W * 2 + 1, FONT_ATLAS_DEFAULT_TEX_DATA_H);\r\n        else\r\n            atlas->PackIdMouseCursors = atlas->AddCustomRectRegular(2, 2);\r\n    }\r\n\r\n    // Register texture region for thick lines\r\n    // The +2 here is to give space for the end caps, whilst height +1 is to accommodate the fact we have a zero-width row\r\n    if (atlas->PackIdLines < 0)\r\n    {\r\n        if (!(atlas->Flags & ImFontAtlasFlags_NoBakedLines))\r\n            atlas->PackIdLines = atlas->AddCustomRectRegular(IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 2, IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1);\r\n    }\r\n}\r\n\r\n// This is called/shared by both the stb_truetype and the FreeType builder.\r\nvoid ImFontAtlasBuildFinish(ImFontAtlas* atlas)\r\n{\r\n    // Render into our custom data blocks\r\n    IM_ASSERT(atlas->TexPixelsAlpha8 != NULL || atlas->TexPixelsRGBA32 != NULL);\r\n    ImFontAtlasBuildRenderDefaultTexData(atlas);\r\n    ImFontAtlasBuildRenderLinesTexData(atlas);\r\n\r\n    // Register custom rectangle glyphs\r\n    for (int i = 0; i < atlas->CustomRects.Size; i++)\r\n    {\r\n        const ImFontAtlasCustomRect* r = &atlas->CustomRects[i];\r\n        if (r->Font == NULL || r->GlyphID == 0)\r\n            continue;\r\n\r\n        // Will ignore ImFontConfig settings: GlyphMinAdvanceX, GlyphMinAdvanceY, GlyphExtraSpacing, PixelSnapH\r\n        IM_ASSERT(r->Font->ContainerAtlas == atlas);\r\n        ImVec2 uv0, uv1;\r\n        atlas->CalcCustomRectUV(r, &uv0, &uv1);\r\n        r->Font->AddGlyph(NULL, (ImWchar)r->GlyphID, r->GlyphOffset.x, r->GlyphOffset.y, r->GlyphOffset.x + r->Width, r->GlyphOffset.y + r->Height, uv0.x, uv0.y, uv1.x, uv1.y, r->GlyphAdvanceX);\r\n    }\r\n\r\n    // Build all fonts lookup tables\r\n    for (int i = 0; i < atlas->Fonts.Size; i++)\r\n        if (atlas->Fonts[i]->DirtyLookupTables)\r\n            atlas->Fonts[i]->BuildLookupTable();\r\n\r\n    atlas->TexReady = true;\r\n}\r\n\r\n// Retrieve list of range (2 int per range, values are inclusive)\r\nconst ImWchar*   ImFontAtlas::GetGlyphRangesDefault()\r\n{\r\n    static const ImWchar ranges[] =\r\n    {\r\n        0x0020, 0x00FF, // Basic Latin + Latin Supplement\r\n        0,\r\n    };\r\n    return &ranges[0];\r\n}\r\n\r\nconst ImWchar*  ImFontAtlas::GetGlyphRangesKorean()\r\n{\r\n    static const ImWchar ranges[] =\r\n    {\r\n        0x0020, 0x00FF, // Basic Latin + Latin Supplement\r\n        0x3131, 0x3163, // Korean alphabets\r\n        0xAC00, 0xD7A3, // Korean characters\r\n        0xFFFD, 0xFFFD, // Invalid\r\n        0,\r\n    };\r\n    return &ranges[0];\r\n}\r\n\r\nconst ImWchar*  ImFontAtlas::GetGlyphRangesChineseFull()\r\n{\r\n    static const ImWchar ranges[] =\r\n    {\r\n        0x0020, 0x00FF, // Basic Latin + Latin Supplement\r\n        0x2000, 0x206F, // General Punctuation\r\n        0x3000, 0x30FF, // CJK Symbols and Punctuations, Hiragana, Katakana\r\n        0x31F0, 0x31FF, // Katakana Phonetic Extensions\r\n        0xFF00, 0xFFEF, // Half-width characters\r\n        0xFFFD, 0xFFFD, // Invalid\r\n        0x4e00, 0x9FAF, // CJK Ideograms\r\n        0,\r\n    };\r\n    return &ranges[0];\r\n}\r\n\r\nstatic void UnpackAccumulativeOffsetsIntoRanges(int base_codepoint, const short* accumulative_offsets, int accumulative_offsets_count, ImWchar* out_ranges)\r\n{\r\n    for (int n = 0; n < accumulative_offsets_count; n++, out_ranges += 2)\r\n    {\r\n        out_ranges[0] = out_ranges[1] = (ImWchar)(base_codepoint + accumulative_offsets[n]);\r\n        base_codepoint += accumulative_offsets[n];\r\n    }\r\n    out_ranges[0] = 0;\r\n}\r\n\r\n//-------------------------------------------------------------------------\r\n// [SECTION] ImFontAtlas glyph ranges helpers\r\n//-------------------------------------------------------------------------\r\n\r\nconst ImWchar*  ImFontAtlas::GetGlyphRangesChineseSimplifiedCommon()\r\n{\r\n    // Store 2500 regularly used characters for Simplified Chinese.\r\n    // Sourced from https://zh.wiktionary.org/wiki/%E9%99%84%E5%BD%95:%E7%8E%B0%E4%BB%A3%E6%B1%89%E8%AF%AD%E5%B8%B8%E7%94%A8%E5%AD%97%E8%A1%A8\r\n    // This table covers 97.97% of all characters used during the month in July, 1987.\r\n    // You can use ImFontGlyphRangesBuilder to create your own ranges derived from this, by merging existing ranges or adding new characters.\r\n    // (Stored as accumulative offsets from the initial unicode codepoint 0x4E00. This encoding is designed to helps us compact the source code size.)\r\n    static const short accumulative_offsets_from_0x4E00[] =\r\n    {\r\n        0,1,2,4,1,1,1,1,2,1,3,2,1,2,2,1,1,1,1,1,5,2,1,2,3,3,3,2,2,4,1,1,1,2,1,5,2,3,1,2,1,2,1,1,2,1,1,2,2,1,4,1,1,1,1,5,10,1,2,19,2,1,2,1,2,1,2,1,2,\r\n        1,5,1,6,3,2,1,2,2,1,1,1,4,8,5,1,1,4,1,1,3,1,2,1,5,1,2,1,1,1,10,1,1,5,2,4,6,1,4,2,2,2,12,2,1,1,6,1,1,1,4,1,1,4,6,5,1,4,2,2,4,10,7,1,1,4,2,4,\r\n        2,1,4,3,6,10,12,5,7,2,14,2,9,1,1,6,7,10,4,7,13,1,5,4,8,4,1,1,2,28,5,6,1,1,5,2,5,20,2,2,9,8,11,2,9,17,1,8,6,8,27,4,6,9,20,11,27,6,68,2,2,1,1,\r\n        1,2,1,2,2,7,6,11,3,3,1,1,3,1,2,1,1,1,1,1,3,1,1,8,3,4,1,5,7,2,1,4,4,8,4,2,1,2,1,1,4,5,6,3,6,2,12,3,1,3,9,2,4,3,4,1,5,3,3,1,3,7,1,5,1,1,1,1,2,\r\n        3,4,5,2,3,2,6,1,1,2,1,7,1,7,3,4,5,15,2,2,1,5,3,22,19,2,1,1,1,1,2,5,1,1,1,6,1,1,12,8,2,9,18,22,4,1,1,5,1,16,1,2,7,10,15,1,1,6,2,4,1,2,4,1,6,\r\n        1,1,3,2,4,1,6,4,5,1,2,1,1,2,1,10,3,1,3,2,1,9,3,2,5,7,2,19,4,3,6,1,1,1,1,1,4,3,2,1,1,1,2,5,3,1,1,1,2,2,1,1,2,1,1,2,1,3,1,1,1,3,7,1,4,1,1,2,1,\r\n        1,2,1,2,4,4,3,8,1,1,1,2,1,3,5,1,3,1,3,4,6,2,2,14,4,6,6,11,9,1,15,3,1,28,5,2,5,5,3,1,3,4,5,4,6,14,3,2,3,5,21,2,7,20,10,1,2,19,2,4,28,28,2,3,\r\n        2,1,14,4,1,26,28,42,12,40,3,52,79,5,14,17,3,2,2,11,3,4,6,3,1,8,2,23,4,5,8,10,4,2,7,3,5,1,1,6,3,1,2,2,2,5,28,1,1,7,7,20,5,3,29,3,17,26,1,8,4,\r\n        27,3,6,11,23,5,3,4,6,13,24,16,6,5,10,25,35,7,3,2,3,3,14,3,6,2,6,1,4,2,3,8,2,1,1,3,3,3,4,1,1,13,2,2,4,5,2,1,14,14,1,2,2,1,4,5,2,3,1,14,3,12,\r\n        3,17,2,16,5,1,2,1,8,9,3,19,4,2,2,4,17,25,21,20,28,75,1,10,29,103,4,1,2,1,1,4,2,4,1,2,3,24,2,2,2,1,1,2,1,3,8,1,1,1,2,1,1,3,1,1,1,6,1,5,3,1,1,\r\n        1,3,4,1,1,5,2,1,5,6,13,9,16,1,1,1,1,3,2,3,2,4,5,2,5,2,2,3,7,13,7,2,2,1,1,1,1,2,3,3,2,1,6,4,9,2,1,14,2,14,2,1,18,3,4,14,4,11,41,15,23,15,23,\r\n        176,1,3,4,1,1,1,1,5,3,1,2,3,7,3,1,1,2,1,2,4,4,6,2,4,1,9,7,1,10,5,8,16,29,1,1,2,2,3,1,3,5,2,4,5,4,1,1,2,2,3,3,7,1,6,10,1,17,1,44,4,6,2,1,1,6,\r\n        5,4,2,10,1,6,9,2,8,1,24,1,2,13,7,8,8,2,1,4,1,3,1,3,3,5,2,5,10,9,4,9,12,2,1,6,1,10,1,1,7,7,4,10,8,3,1,13,4,3,1,6,1,3,5,2,1,2,17,16,5,2,16,6,\r\n        1,4,2,1,3,3,6,8,5,11,11,1,3,3,2,4,6,10,9,5,7,4,7,4,7,1,1,4,2,1,3,6,8,7,1,6,11,5,5,3,24,9,4,2,7,13,5,1,8,82,16,61,1,1,1,4,2,2,16,10,3,8,1,1,\r\n        6,4,2,1,3,1,1,1,4,3,8,4,2,2,1,1,1,1,1,6,3,5,1,1,4,6,9,2,1,1,1,2,1,7,2,1,6,1,5,4,4,3,1,8,1,3,3,1,3,2,2,2,2,3,1,6,1,2,1,2,1,3,7,1,8,2,1,2,1,5,\r\n        2,5,3,5,10,1,2,1,1,3,2,5,11,3,9,3,5,1,1,5,9,1,2,1,5,7,9,9,8,1,3,3,3,6,8,2,3,2,1,1,32,6,1,2,15,9,3,7,13,1,3,10,13,2,14,1,13,10,2,1,3,10,4,15,\r\n        2,15,15,10,1,3,9,6,9,32,25,26,47,7,3,2,3,1,6,3,4,3,2,8,5,4,1,9,4,2,2,19,10,6,2,3,8,1,2,2,4,2,1,9,4,4,4,6,4,8,9,2,3,1,1,1,1,3,5,5,1,3,8,4,6,\r\n        2,1,4,12,1,5,3,7,13,2,5,8,1,6,1,2,5,14,6,1,5,2,4,8,15,5,1,23,6,62,2,10,1,1,8,1,2,2,10,4,2,2,9,2,1,1,3,2,3,1,5,3,3,2,1,3,8,1,1,1,11,3,1,1,4,\r\n        3,7,1,14,1,2,3,12,5,2,5,1,6,7,5,7,14,11,1,3,1,8,9,12,2,1,11,8,4,4,2,6,10,9,13,1,1,3,1,5,1,3,2,4,4,1,18,2,3,14,11,4,29,4,2,7,1,3,13,9,2,2,5,\r\n        3,5,20,7,16,8,5,72,34,6,4,22,12,12,28,45,36,9,7,39,9,191,1,1,1,4,11,8,4,9,2,3,22,1,1,1,1,4,17,1,7,7,1,11,31,10,2,4,8,2,3,2,1,4,2,16,4,32,2,\r\n        3,19,13,4,9,1,5,2,14,8,1,1,3,6,19,6,5,1,16,6,2,10,8,5,1,2,3,1,5,5,1,11,6,6,1,3,3,2,6,3,8,1,1,4,10,7,5,7,7,5,8,9,2,1,3,4,1,1,3,1,3,3,2,6,16,\r\n        1,4,6,3,1,10,6,1,3,15,2,9,2,10,25,13,9,16,6,2,2,10,11,4,3,9,1,2,6,6,5,4,30,40,1,10,7,12,14,33,6,3,6,7,3,1,3,1,11,14,4,9,5,12,11,49,18,51,31,\r\n        140,31,2,2,1,5,1,8,1,10,1,4,4,3,24,1,10,1,3,6,6,16,3,4,5,2,1,4,2,57,10,6,22,2,22,3,7,22,6,10,11,36,18,16,33,36,2,5,5,1,1,1,4,10,1,4,13,2,7,\r\n        5,2,9,3,4,1,7,43,3,7,3,9,14,7,9,1,11,1,1,3,7,4,18,13,1,14,1,3,6,10,73,2,2,30,6,1,11,18,19,13,22,3,46,42,37,89,7,3,16,34,2,2,3,9,1,7,1,1,1,2,\r\n        2,4,10,7,3,10,3,9,5,28,9,2,6,13,7,3,1,3,10,2,7,2,11,3,6,21,54,85,2,1,4,2,2,1,39,3,21,2,2,5,1,1,1,4,1,1,3,4,15,1,3,2,4,4,2,3,8,2,20,1,8,7,13,\r\n        4,1,26,6,2,9,34,4,21,52,10,4,4,1,5,12,2,11,1,7,2,30,12,44,2,30,1,1,3,6,16,9,17,39,82,2,2,24,7,1,7,3,16,9,14,44,2,1,2,1,2,3,5,2,4,1,6,7,5,3,\r\n        2,6,1,11,5,11,2,1,18,19,8,1,3,24,29,2,1,3,5,2,2,1,13,6,5,1,46,11,3,5,1,1,5,8,2,10,6,12,6,3,7,11,2,4,16,13,2,5,1,1,2,2,5,2,28,5,2,23,10,8,4,\r\n        4,22,39,95,38,8,14,9,5,1,13,5,4,3,13,12,11,1,9,1,27,37,2,5,4,4,63,211,95,2,2,2,1,3,5,2,1,1,2,2,1,1,1,3,2,4,1,2,1,1,5,2,2,1,1,2,3,1,3,1,1,1,\r\n        3,1,4,2,1,3,6,1,1,3,7,15,5,3,2,5,3,9,11,4,2,22,1,6,3,8,7,1,4,28,4,16,3,3,25,4,4,27,27,1,4,1,2,2,7,1,3,5,2,28,8,2,14,1,8,6,16,25,3,3,3,14,3,\r\n        3,1,1,2,1,4,6,3,8,4,1,1,1,2,3,6,10,6,2,3,18,3,2,5,5,4,3,1,5,2,5,4,23,7,6,12,6,4,17,11,9,5,1,1,10,5,12,1,1,11,26,33,7,3,6,1,17,7,1,5,12,1,11,\r\n        2,4,1,8,14,17,23,1,2,1,7,8,16,11,9,6,5,2,6,4,16,2,8,14,1,11,8,9,1,1,1,9,25,4,11,19,7,2,15,2,12,8,52,7,5,19,2,16,4,36,8,1,16,8,24,26,4,6,2,9,\r\n        5,4,36,3,28,12,25,15,37,27,17,12,59,38,5,32,127,1,2,9,17,14,4,1,2,1,1,8,11,50,4,14,2,19,16,4,17,5,4,5,26,12,45,2,23,45,104,30,12,8,3,10,2,2,\r\n        3,3,1,4,20,7,2,9,6,15,2,20,1,3,16,4,11,15,6,134,2,5,59,1,2,2,2,1,9,17,3,26,137,10,211,59,1,2,4,1,4,1,1,1,2,6,2,3,1,1,2,3,2,3,1,3,4,4,2,3,3,\r\n        1,4,3,1,7,2,2,3,1,2,1,3,3,3,2,2,3,2,1,3,14,6,1,3,2,9,6,15,27,9,34,145,1,1,2,1,1,1,1,2,1,1,1,1,2,2,2,3,1,2,1,1,1,2,3,5,8,3,5,2,4,1,3,2,2,2,12,\r\n        4,1,1,1,10,4,5,1,20,4,16,1,15,9,5,12,2,9,2,5,4,2,26,19,7,1,26,4,30,12,15,42,1,6,8,172,1,1,4,2,1,1,11,2,2,4,2,1,2,1,10,8,1,2,1,4,5,1,2,5,1,8,\r\n        4,1,3,4,2,1,6,2,1,3,4,1,2,1,1,1,1,12,5,7,2,4,3,1,1,1,3,3,6,1,2,2,3,3,3,2,1,2,12,14,11,6,6,4,12,2,8,1,7,10,1,35,7,4,13,15,4,3,23,21,28,52,5,\r\n        26,5,6,1,7,10,2,7,53,3,2,1,1,1,2,163,532,1,10,11,1,3,3,4,8,2,8,6,2,2,23,22,4,2,2,4,2,1,3,1,3,3,5,9,8,2,1,2,8,1,10,2,12,21,20,15,105,2,3,1,1,\r\n        3,2,3,1,1,2,5,1,4,15,11,19,1,1,1,1,5,4,5,1,1,2,5,3,5,12,1,2,5,1,11,1,1,15,9,1,4,5,3,26,8,2,1,3,1,1,15,19,2,12,1,2,5,2,7,2,19,2,20,6,26,7,5,\r\n        2,2,7,34,21,13,70,2,128,1,1,2,1,1,2,1,1,3,2,2,2,15,1,4,1,3,4,42,10,6,1,49,85,8,1,2,1,1,4,4,2,3,6,1,5,7,4,3,211,4,1,2,1,2,5,1,2,4,2,2,6,5,6,\r\n        10,3,4,48,100,6,2,16,296,5,27,387,2,2,3,7,16,8,5,38,15,39,21,9,10,3,7,59,13,27,21,47,5,21,6\r\n    };\r\n    static ImWchar base_ranges[] = // not zero-terminated\r\n    {\r\n        0x0020, 0x00FF, // Basic Latin + Latin Supplement\r\n        0x2000, 0x206F, // General Punctuation\r\n        0x3000, 0x30FF, // CJK Symbols and Punctuations, Hiragana, Katakana\r\n        0x31F0, 0x31FF, // Katakana Phonetic Extensions\r\n        0xFF00, 0xFFEF, // Half-width characters\r\n        0xFFFD, 0xFFFD  // Invalid\r\n    };\r\n    static ImWchar full_ranges[IM_ARRAYSIZE(base_ranges) + IM_ARRAYSIZE(accumulative_offsets_from_0x4E00) * 2 + 1] = { 0 };\r\n    if (!full_ranges[0])\r\n    {\r\n        memcpy(full_ranges, base_ranges, sizeof(base_ranges));\r\n        UnpackAccumulativeOffsetsIntoRanges(0x4E00, accumulative_offsets_from_0x4E00, IM_ARRAYSIZE(accumulative_offsets_from_0x4E00), full_ranges + IM_ARRAYSIZE(base_ranges));\r\n    }\r\n    return &full_ranges[0];\r\n}\r\n\r\nconst ImWchar*  ImFontAtlas::GetGlyphRangesJapanese()\r\n{\r\n    // 2999 ideograms code points for Japanese\r\n    // - 2136 Joyo (meaning \"for regular use\" or \"for common use\") Kanji code points\r\n    // - 863 Jinmeiyo (meaning \"for personal name\") Kanji code points\r\n    // - Sourced from the character information database of the Information-technology Promotion Agency, Japan\r\n    //   - https://mojikiban.ipa.go.jp/mji/\r\n    //   - Available under the terms of the Creative Commons Attribution-ShareAlike 2.1 Japan (CC BY-SA 2.1 JP).\r\n    //     - https://creativecommons.org/licenses/by-sa/2.1/jp/deed.en\r\n    //     - https://creativecommons.org/licenses/by-sa/2.1/jp/legalcode\r\n    //   - You can generate this code by the script at:\r\n    //     - https://github.com/vaiorabbit/everyday_use_kanji\r\n    // - References:\r\n    //   - List of Joyo Kanji\r\n    //     - (Official list by the Agency for Cultural Affairs) https://www.bunka.go.jp/kokugo_nihongo/sisaku/joho/joho/kakuki/14/tosin02/index.html\r\n    //     - (Wikipedia) https://en.wikipedia.org/wiki/List_of_j%C5%8Dy%C5%8D_kanji\r\n    //   - List of Jinmeiyo Kanji\r\n    //     - (Official list by the Ministry of Justice) http://www.moj.go.jp/MINJI/minji86.html\r\n    //     - (Wikipedia) https://en.wikipedia.org/wiki/Jinmeiy%C5%8D_kanji\r\n    // - Missing 1 Joyo Kanji: U+20B9F (Kun'yomi: Shikaru, On'yomi: Shitsu,shichi), see https://github.com/ocornut/imgui/pull/3627 for details.\r\n    // You can use ImFontGlyphRangesBuilder to create your own ranges derived from this, by merging existing ranges or adding new characters.\r\n    // (Stored as accumulative offsets from the initial unicode codepoint 0x4E00. This encoding is designed to helps us compact the source code size.)\r\n    static const short accumulative_offsets_from_0x4E00[] =\r\n    {\r\n        0,1,2,4,1,1,1,1,2,1,3,3,2,2,1,5,3,5,7,5,6,1,2,1,7,2,6,3,1,8,1,1,4,1,1,18,2,11,2,6,2,1,2,1,5,1,2,1,3,1,2,1,2,3,3,1,1,2,3,1,1,1,12,7,9,1,4,5,1,\r\n        1,2,1,10,1,1,9,2,2,4,5,6,9,3,1,1,1,1,9,3,18,5,2,2,2,2,1,6,3,7,1,1,1,1,2,2,4,2,1,23,2,10,4,3,5,2,4,10,2,4,13,1,6,1,9,3,1,1,6,6,7,6,3,1,2,11,3,\r\n        2,2,3,2,15,2,2,5,4,3,6,4,1,2,5,2,12,16,6,13,9,13,2,1,1,7,16,4,7,1,19,1,5,1,2,2,7,7,8,2,6,5,4,9,18,7,4,5,9,13,11,8,15,2,1,1,1,2,1,2,2,1,2,2,8,\r\n        2,9,3,3,1,1,4,4,1,1,1,4,9,1,4,3,5,5,2,7,5,3,4,8,2,1,13,2,3,3,1,14,1,1,4,5,1,3,6,1,5,2,1,1,3,3,3,3,1,1,2,7,6,6,7,1,4,7,6,1,1,1,1,1,12,3,3,9,5,\r\n        2,6,1,5,6,1,2,3,18,2,4,14,4,1,3,6,1,1,6,3,5,5,3,2,2,2,2,12,3,1,4,2,3,2,3,11,1,7,4,1,2,1,3,17,1,9,1,24,1,1,4,2,2,4,1,2,7,1,1,1,3,1,2,2,4,15,1,\r\n        1,2,1,1,2,1,5,2,5,20,2,5,9,1,10,8,7,6,1,1,1,1,1,1,6,2,1,2,8,1,1,1,1,5,1,1,3,1,1,1,1,3,1,1,12,4,1,3,1,1,1,1,1,10,3,1,7,5,13,1,2,3,4,6,1,1,30,\r\n        2,9,9,1,15,38,11,3,1,8,24,7,1,9,8,10,2,1,9,31,2,13,6,2,9,4,49,5,2,15,2,1,10,2,1,1,1,2,2,6,15,30,35,3,14,18,8,1,16,10,28,12,19,45,38,1,3,2,3,\r\n        13,2,1,7,3,6,5,3,4,3,1,5,7,8,1,5,3,18,5,3,6,1,21,4,24,9,24,40,3,14,3,21,3,2,1,2,4,2,3,1,15,15,6,5,1,1,3,1,5,6,1,9,7,3,3,2,1,4,3,8,21,5,16,4,\r\n        5,2,10,11,11,3,6,3,2,9,3,6,13,1,2,1,1,1,1,11,12,6,6,1,4,2,6,5,2,1,1,3,3,6,13,3,1,1,5,1,2,3,3,14,2,1,2,2,2,5,1,9,5,1,1,6,12,3,12,3,4,13,2,14,\r\n        2,8,1,17,5,1,16,4,2,2,21,8,9,6,23,20,12,25,19,9,38,8,3,21,40,25,33,13,4,3,1,4,1,2,4,1,2,5,26,2,1,1,2,1,3,6,2,1,1,1,1,1,1,2,3,1,1,1,9,2,3,1,1,\r\n        1,3,6,3,2,1,1,6,6,1,8,2,2,2,1,4,1,2,3,2,7,3,2,4,1,2,1,2,2,1,1,1,1,1,3,1,2,5,4,10,9,4,9,1,1,1,1,1,1,5,3,2,1,6,4,9,6,1,10,2,31,17,8,3,7,5,40,1,\r\n        7,7,1,6,5,2,10,7,8,4,15,39,25,6,28,47,18,10,7,1,3,1,1,2,1,1,1,3,3,3,1,1,1,3,4,2,1,4,1,3,6,10,7,8,6,2,2,1,3,3,2,5,8,7,9,12,2,15,1,1,4,1,2,1,1,\r\n        1,3,2,1,3,3,5,6,2,3,2,10,1,4,2,8,1,1,1,11,6,1,21,4,16,3,1,3,1,4,2,3,6,5,1,3,1,1,3,3,4,6,1,1,10,4,2,7,10,4,7,4,2,9,4,3,1,1,1,4,1,8,3,4,1,3,1,\r\n        6,1,4,2,1,4,7,2,1,8,1,4,5,1,1,2,2,4,6,2,7,1,10,1,1,3,4,11,10,8,21,4,6,1,3,5,2,1,2,28,5,5,2,3,13,1,2,3,1,4,2,1,5,20,3,8,11,1,3,3,3,1,8,10,9,2,\r\n        10,9,2,3,1,1,2,4,1,8,3,6,1,7,8,6,11,1,4,29,8,4,3,1,2,7,13,1,4,1,6,2,6,12,12,2,20,3,2,3,6,4,8,9,2,7,34,5,1,18,6,1,1,4,4,5,7,9,1,2,2,4,3,4,1,7,\r\n        2,2,2,6,2,3,25,5,3,6,1,4,6,7,4,2,1,4,2,13,6,4,4,3,1,5,3,4,4,3,2,1,1,4,1,2,1,1,3,1,11,1,6,3,1,7,3,6,2,8,8,6,9,3,4,11,3,2,10,12,2,5,11,1,6,4,5,\r\n        3,1,8,5,4,6,6,3,5,1,1,3,2,1,2,2,6,17,12,1,10,1,6,12,1,6,6,19,9,6,16,1,13,4,4,15,7,17,6,11,9,15,12,6,7,2,1,2,2,15,9,3,21,4,6,49,18,7,3,2,3,1,\r\n        6,8,2,2,6,2,9,1,3,6,4,4,1,2,16,2,5,2,1,6,2,3,5,3,1,2,5,1,2,1,9,3,1,8,6,4,8,11,3,1,1,1,1,3,1,13,8,4,1,3,2,2,1,4,1,11,1,5,2,1,5,2,5,8,6,1,1,7,\r\n        4,3,8,3,2,7,2,1,5,1,5,2,4,7,6,2,8,5,1,11,4,5,3,6,18,1,2,13,3,3,1,21,1,1,4,1,4,1,1,1,8,1,2,2,7,1,2,4,2,2,9,2,1,1,1,4,3,6,3,12,5,1,1,1,5,6,3,2,\r\n        4,8,2,2,4,2,7,1,8,9,5,2,3,2,1,3,2,13,7,14,6,5,1,1,2,1,4,2,23,2,1,1,6,3,1,4,1,15,3,1,7,3,9,14,1,3,1,4,1,1,5,8,1,3,8,3,8,15,11,4,14,4,4,2,5,5,\r\n        1,7,1,6,14,7,7,8,5,15,4,8,6,5,6,2,1,13,1,20,15,11,9,2,5,6,2,11,2,6,2,5,1,5,8,4,13,19,25,4,1,1,11,1,34,2,5,9,14,6,2,2,6,1,1,14,1,3,14,13,1,6,\r\n        12,21,14,14,6,32,17,8,32,9,28,1,2,4,11,8,3,1,14,2,5,15,1,1,1,1,3,6,4,1,3,4,11,3,1,1,11,30,1,5,1,4,1,5,8,1,1,3,2,4,3,17,35,2,6,12,17,3,1,6,2,\r\n        1,1,12,2,7,3,3,2,1,16,2,8,3,6,5,4,7,3,3,8,1,9,8,5,1,2,1,3,2,8,1,2,9,12,1,1,2,3,8,3,24,12,4,3,7,5,8,3,3,3,3,3,3,1,23,10,3,1,2,2,6,3,1,16,1,16,\r\n        22,3,10,4,11,6,9,7,7,3,6,2,2,2,4,10,2,1,1,2,8,7,1,6,4,1,3,3,3,5,10,12,12,2,3,12,8,15,1,1,16,6,6,1,5,9,11,4,11,4,2,6,12,1,17,5,13,1,4,9,5,1,11,\r\n        2,1,8,1,5,7,28,8,3,5,10,2,17,3,38,22,1,2,18,12,10,4,38,18,1,4,44,19,4,1,8,4,1,12,1,4,31,12,1,14,7,75,7,5,10,6,6,13,3,2,11,11,3,2,5,28,15,6,18,\r\n        18,5,6,4,3,16,1,7,18,7,36,3,5,3,1,7,1,9,1,10,7,2,4,2,6,2,9,7,4,3,32,12,3,7,10,2,23,16,3,1,12,3,31,4,11,1,3,8,9,5,1,30,15,6,12,3,2,2,11,19,9,\r\n        14,2,6,2,3,19,13,17,5,3,3,25,3,14,1,1,1,36,1,3,2,19,3,13,36,9,13,31,6,4,16,34,2,5,4,2,3,3,5,1,1,1,4,3,1,17,3,2,3,5,3,1,3,2,3,5,6,3,12,11,1,3,\r\n        1,2,26,7,12,7,2,14,3,3,7,7,11,25,25,28,16,4,36,1,2,1,6,2,1,9,3,27,17,4,3,4,13,4,1,3,2,2,1,10,4,2,4,6,3,8,2,1,18,1,1,24,2,2,4,33,2,3,63,7,1,6,\r\n        40,7,3,4,4,2,4,15,18,1,16,1,1,11,2,41,14,1,3,18,13,3,2,4,16,2,17,7,15,24,7,18,13,44,2,2,3,6,1,1,7,5,1,7,1,4,3,3,5,10,8,2,3,1,8,1,1,27,4,2,1,\r\n        12,1,2,1,10,6,1,6,7,5,2,3,7,11,5,11,3,6,6,2,3,15,4,9,1,1,2,1,2,11,2,8,12,8,5,4,2,3,1,5,2,2,1,14,1,12,11,4,1,11,17,17,4,3,2,5,5,7,3,1,5,9,9,8,\r\n        2,5,6,6,13,13,2,1,2,6,1,2,2,49,4,9,1,2,10,16,7,8,4,3,2,23,4,58,3,29,1,14,19,19,11,11,2,7,5,1,3,4,6,2,18,5,12,12,17,17,3,3,2,4,1,6,2,3,4,3,1,\r\n        1,1,1,5,1,1,9,1,3,1,3,6,1,8,1,1,2,6,4,14,3,1,4,11,4,1,3,32,1,2,4,13,4,1,2,4,2,1,3,1,11,1,4,2,1,4,4,6,3,5,1,6,5,7,6,3,23,3,5,3,5,3,3,13,3,9,10,\r\n        1,12,10,2,3,18,13,7,160,52,4,2,2,3,2,14,5,4,12,4,6,4,1,20,4,11,6,2,12,27,1,4,1,2,2,7,4,5,2,28,3,7,25,8,3,19,3,6,10,2,2,1,10,2,5,4,1,3,4,1,5,\r\n        3,2,6,9,3,6,2,16,3,3,16,4,5,5,3,2,1,2,16,15,8,2,6,21,2,4,1,22,5,8,1,1,21,11,2,1,11,11,19,13,12,4,2,3,2,3,6,1,8,11,1,4,2,9,5,2,1,11,2,9,1,1,2,\r\n        14,31,9,3,4,21,14,4,8,1,7,2,2,2,5,1,4,20,3,3,4,10,1,11,9,8,2,1,4,5,14,12,14,2,17,9,6,31,4,14,1,20,13,26,5,2,7,3,6,13,2,4,2,19,6,2,2,18,9,3,5,\r\n        12,12,14,4,6,2,3,6,9,5,22,4,5,25,6,4,8,5,2,6,27,2,35,2,16,3,7,8,8,6,6,5,9,17,2,20,6,19,2,13,3,1,1,1,4,17,12,2,14,7,1,4,18,12,38,33,2,10,1,1,\r\n        2,13,14,17,11,50,6,33,20,26,74,16,23,45,50,13,38,33,6,6,7,4,4,2,1,3,2,5,8,7,8,9,3,11,21,9,13,1,3,10,6,7,1,2,2,18,5,5,1,9,9,2,68,9,19,13,2,5,\r\n        1,4,4,7,4,13,3,9,10,21,17,3,26,2,1,5,2,4,5,4,1,7,4,7,3,4,2,1,6,1,1,20,4,1,9,2,2,1,3,3,2,3,2,1,1,1,20,2,3,1,6,2,3,6,2,4,8,1,3,2,10,3,5,3,4,4,\r\n        3,4,16,1,6,1,10,2,4,2,1,1,2,10,11,2,2,3,1,24,31,4,10,10,2,5,12,16,164,15,4,16,7,9,15,19,17,1,2,1,1,5,1,1,1,1,1,3,1,4,3,1,3,1,3,1,2,1,1,3,3,7,\r\n        2,8,1,2,2,2,1,3,4,3,7,8,12,92,2,10,3,1,3,14,5,25,16,42,4,7,7,4,2,21,5,27,26,27,21,25,30,31,2,1,5,13,3,22,5,6,6,11,9,12,1,5,9,7,5,5,22,60,3,5,\r\n        13,1,1,8,1,1,3,3,2,1,9,3,3,18,4,1,2,3,7,6,3,1,2,3,9,1,3,1,3,2,1,3,1,1,1,2,1,11,3,1,6,9,1,3,2,3,1,2,1,5,1,1,4,3,4,1,2,2,4,4,1,7,2,1,2,2,3,5,13,\r\n        18,3,4,14,9,9,4,16,3,7,5,8,2,6,48,28,3,1,1,4,2,14,8,2,9,2,1,15,2,4,3,2,10,16,12,8,7,1,1,3,1,1,1,2,7,4,1,6,4,38,39,16,23,7,15,15,3,2,12,7,21,\r\n        37,27,6,5,4,8,2,10,8,8,6,5,1,2,1,3,24,1,16,17,9,23,10,17,6,1,51,55,44,13,294,9,3,6,2,4,2,2,15,1,1,1,13,21,17,68,14,8,9,4,1,4,9,3,11,7,1,1,1,\r\n        5,6,3,2,1,1,1,2,3,8,1,2,2,4,1,5,5,2,1,4,3,7,13,4,1,4,1,3,1,1,1,5,5,10,1,6,1,5,2,1,5,2,4,1,4,5,7,3,18,2,9,11,32,4,3,3,2,4,7,11,16,9,11,8,13,38,\r\n        32,8,4,2,1,1,2,1,2,4,4,1,1,1,4,1,21,3,11,1,16,1,1,6,1,3,2,4,9,8,57,7,44,1,3,3,13,3,10,1,1,7,5,2,7,21,47,63,3,15,4,7,1,16,1,1,2,8,2,3,42,15,4,\r\n        1,29,7,22,10,3,78,16,12,20,18,4,67,11,5,1,3,15,6,21,31,32,27,18,13,71,35,5,142,4,10,1,2,50,19,33,16,35,37,16,19,27,7,1,133,19,1,4,8,7,20,1,4,\r\n        4,1,10,3,1,6,1,2,51,5,40,15,24,43,22928,11,1,13,154,70,3,1,1,7,4,10,1,2,1,1,2,1,2,1,2,2,1,1,2,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,\r\n        3,2,1,1,1,1,2,1,1,\r\n    };\r\n    static ImWchar base_ranges[] = // not zero-terminated\r\n    {\r\n        0x0020, 0x00FF, // Basic Latin + Latin Supplement\r\n        0x3000, 0x30FF, // CJK Symbols and Punctuations, Hiragana, Katakana\r\n        0x31F0, 0x31FF, // Katakana Phonetic Extensions\r\n        0xFF00, 0xFFEF, // Half-width characters\r\n        0xFFFD, 0xFFFD  // Invalid\r\n    };\r\n    static ImWchar full_ranges[IM_ARRAYSIZE(base_ranges) + IM_ARRAYSIZE(accumulative_offsets_from_0x4E00)*2 + 1] = { 0 };\r\n    if (!full_ranges[0])\r\n    {\r\n        memcpy(full_ranges, base_ranges, sizeof(base_ranges));\r\n        UnpackAccumulativeOffsetsIntoRanges(0x4E00, accumulative_offsets_from_0x4E00, IM_ARRAYSIZE(accumulative_offsets_from_0x4E00), full_ranges + IM_ARRAYSIZE(base_ranges));\r\n    }\r\n    return &full_ranges[0];\r\n}\r\n\r\nconst ImWchar*  ImFontAtlas::GetGlyphRangesCyrillic()\r\n{\r\n    static const ImWchar ranges[] =\r\n    {\r\n        0x0020, 0x00FF, // Basic Latin + Latin Supplement\r\n        0x0400, 0x052F, // Cyrillic + Cyrillic Supplement\r\n        0x2DE0, 0x2DFF, // Cyrillic Extended-A\r\n        0xA640, 0xA69F, // Cyrillic Extended-B\r\n        0,\r\n    };\r\n    return &ranges[0];\r\n}\r\n\r\nconst ImWchar*  ImFontAtlas::GetGlyphRangesThai()\r\n{\r\n    static const ImWchar ranges[] =\r\n    {\r\n        0x0020, 0x00FF, // Basic Latin\r\n        0x2010, 0x205E, // Punctuations\r\n        0x0E00, 0x0E7F, // Thai\r\n        0,\r\n    };\r\n    return &ranges[0];\r\n}\r\n\r\nconst ImWchar*  ImFontAtlas::GetGlyphRangesVietnamese()\r\n{\r\n    static const ImWchar ranges[] =\r\n    {\r\n        0x0020, 0x00FF, // Basic Latin\r\n        0x0102, 0x0103,\r\n        0x0110, 0x0111,\r\n        0x0128, 0x0129,\r\n        0x0168, 0x0169,\r\n        0x01A0, 0x01A1,\r\n        0x01AF, 0x01B0,\r\n        0x1EA0, 0x1EF9,\r\n        0,\r\n    };\r\n    return &ranges[0];\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] ImFontGlyphRangesBuilder\r\n//-----------------------------------------------------------------------------\r\n\r\nvoid ImFontGlyphRangesBuilder::AddText(const char* text, const char* text_end)\r\n{\r\n    while (text_end ? (text < text_end) : *text)\r\n    {\r\n        unsigned int c = 0;\r\n        int c_len = ImTextCharFromUtf8(&c, text, text_end);\r\n        text += c_len;\r\n        if (c_len == 0)\r\n            break;\r\n        AddChar((ImWchar)c);\r\n    }\r\n}\r\n\r\nvoid ImFontGlyphRangesBuilder::AddRanges(const ImWchar* ranges)\r\n{\r\n    for (; ranges[0]; ranges += 2)\r\n        for (unsigned int c = ranges[0]; c <= ranges[1] && c <= IM_UNICODE_CODEPOINT_MAX; c++) //-V560\r\n            AddChar((ImWchar)c);\r\n}\r\n\r\nvoid ImFontGlyphRangesBuilder::BuildRanges(ImVector<ImWchar>* out_ranges)\r\n{\r\n    const int max_codepoint = IM_UNICODE_CODEPOINT_MAX;\r\n    for (int n = 0; n <= max_codepoint; n++)\r\n        if (GetBit(n))\r\n        {\r\n            out_ranges->push_back((ImWchar)n);\r\n            while (n < max_codepoint && GetBit(n + 1))\r\n                n++;\r\n            out_ranges->push_back((ImWchar)n);\r\n        }\r\n    out_ranges->push_back(0);\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] ImFont\r\n//-----------------------------------------------------------------------------\r\n\r\nImFont::ImFont()\r\n{\r\n    FontSize = 0.0f;\r\n    FallbackAdvanceX = 0.0f;\r\n    FallbackChar = (ImWchar)-1;\r\n    EllipsisChar = (ImWchar)-1;\r\n    DotChar = (ImWchar)-1;\r\n    FallbackGlyph = NULL;\r\n    ContainerAtlas = NULL;\r\n    ConfigData = NULL;\r\n    ConfigDataCount = 0;\r\n    DirtyLookupTables = false;\r\n    Scale = 1.0f;\r\n    Ascent = Descent = 0.0f;\r\n    MetricsTotalSurface = 0;\r\n    memset(Used4kPagesMap, 0, sizeof(Used4kPagesMap));\r\n}\r\n\r\nImFont::~ImFont()\r\n{\r\n    ClearOutputData();\r\n}\r\n\r\nvoid    ImFont::ClearOutputData()\r\n{\r\n    FontSize = 0.0f;\r\n    FallbackAdvanceX = 0.0f;\r\n    Glyphs.clear();\r\n    IndexAdvanceX.clear();\r\n    IndexLookup.clear();\r\n    FallbackGlyph = NULL;\r\n    ContainerAtlas = NULL;\r\n    DirtyLookupTables = true;\r\n    Ascent = Descent = 0.0f;\r\n    MetricsTotalSurface = 0;\r\n}\r\n\r\nstatic ImWchar FindFirstExistingGlyph(ImFont* font, const ImWchar* candidate_chars, int candidate_chars_count)\r\n{\r\n    for (int n = 0; n < candidate_chars_count; n++)\r\n        if (font->FindGlyphNoFallback(candidate_chars[n]) != NULL)\r\n            return candidate_chars[n];\r\n    return (ImWchar)-1;\r\n}\r\n\r\nvoid ImFont::BuildLookupTable()\r\n{\r\n    int max_codepoint = 0;\r\n    for (int i = 0; i != Glyphs.Size; i++)\r\n        max_codepoint = ImMax(max_codepoint, (int)Glyphs[i].Codepoint);\r\n\r\n    // Build lookup table\r\n    IM_ASSERT(Glyphs.Size < 0xFFFF); // -1 is reserved\r\n    IndexAdvanceX.clear();\r\n    IndexLookup.clear();\r\n    DirtyLookupTables = false;\r\n    memset(Used4kPagesMap, 0, sizeof(Used4kPagesMap));\r\n    GrowIndex(max_codepoint + 1);\r\n    for (int i = 0; i < Glyphs.Size; i++)\r\n    {\r\n        int codepoint = (int)Glyphs[i].Codepoint;\r\n        IndexAdvanceX[codepoint] = Glyphs[i].AdvanceX;\r\n        IndexLookup[codepoint] = (ImWchar)i;\r\n\r\n        // Mark 4K page as used\r\n        const int page_n = codepoint / 4096;\r\n        Used4kPagesMap[page_n >> 3] |= 1 << (page_n & 7);\r\n    }\r\n\r\n    // Create a glyph to handle TAB\r\n    // FIXME: Needs proper TAB handling but it needs to be contextualized (or we could arbitrary say that each string starts at \"column 0\" ?)\r\n    if (FindGlyph((ImWchar)' '))\r\n    {\r\n        if (Glyphs.back().Codepoint != '\\t')   // So we can call this function multiple times (FIXME: Flaky)\r\n            Glyphs.resize(Glyphs.Size + 1);\r\n        ImFontGlyph& tab_glyph = Glyphs.back();\r\n        tab_glyph = *FindGlyph((ImWchar)' ');\r\n        tab_glyph.Codepoint = '\\t';\r\n        tab_glyph.AdvanceX *= IM_TABSIZE;\r\n        IndexAdvanceX[(int)tab_glyph.Codepoint] = (float)tab_glyph.AdvanceX;\r\n        IndexLookup[(int)tab_glyph.Codepoint] = (ImWchar)(Glyphs.Size - 1);\r\n    }\r\n\r\n    // Mark special glyphs as not visible (note that AddGlyph already mark as non-visible glyphs with zero-size polygons)\r\n    SetGlyphVisible((ImWchar)' ', false);\r\n    SetGlyphVisible((ImWchar)'\\t', false);\r\n\r\n    // Ellipsis character is required for rendering elided text. We prefer using U+2026 (horizontal ellipsis).\r\n    // However some old fonts may contain ellipsis at U+0085. Here we auto-detect most suitable ellipsis character.\r\n    // FIXME: Note that 0x2026 is rarely included in our font ranges. Because of this we are more likely to use three individual dots.\r\n    const ImWchar ellipsis_chars[] = { (ImWchar)0x2026, (ImWchar)0x0085 };\r\n    const ImWchar dots_chars[] = { (ImWchar)'.', (ImWchar)0xFF0E };\r\n    if (EllipsisChar == (ImWchar)-1)\r\n        EllipsisChar = FindFirstExistingGlyph(this, ellipsis_chars, IM_ARRAYSIZE(ellipsis_chars));\r\n    if (DotChar == (ImWchar)-1)\r\n        DotChar = FindFirstExistingGlyph(this, dots_chars, IM_ARRAYSIZE(dots_chars));\r\n\r\n    // Setup fallback character\r\n    const ImWchar fallback_chars[] = { (ImWchar)IM_UNICODE_CODEPOINT_INVALID, (ImWchar)'?', (ImWchar)' ' };\r\n    FallbackGlyph = FindGlyphNoFallback(FallbackChar);\r\n    if (FallbackGlyph == NULL)\r\n    {\r\n        FallbackChar = FindFirstExistingGlyph(this, fallback_chars, IM_ARRAYSIZE(fallback_chars));\r\n        FallbackGlyph = FindGlyphNoFallback(FallbackChar);\r\n        if (FallbackGlyph == NULL)\r\n        {\r\n            FallbackGlyph = &Glyphs.back();\r\n            FallbackChar = (ImWchar)FallbackGlyph->Codepoint;\r\n        }\r\n    }\r\n\r\n    FallbackAdvanceX = FallbackGlyph->AdvanceX;\r\n    for (int i = 0; i < max_codepoint + 1; i++)\r\n        if (IndexAdvanceX[i] < 0.0f)\r\n            IndexAdvanceX[i] = FallbackAdvanceX;\r\n}\r\n\r\n// API is designed this way to avoid exposing the 4K page size\r\n// e.g. use with IsGlyphRangeUnused(0, 255)\r\nbool ImFont::IsGlyphRangeUnused(unsigned int c_begin, unsigned int c_last)\r\n{\r\n    unsigned int page_begin = (c_begin / 4096);\r\n    unsigned int page_last = (c_last / 4096);\r\n    for (unsigned int page_n = page_begin; page_n <= page_last; page_n++)\r\n        if ((page_n >> 3) < sizeof(Used4kPagesMap))\r\n            if (Used4kPagesMap[page_n >> 3] & (1 << (page_n & 7)))\r\n                return false;\r\n    return true;\r\n}\r\n\r\nvoid ImFont::SetGlyphVisible(ImWchar c, bool visible)\r\n{\r\n    if (ImFontGlyph* glyph = (ImFontGlyph*)(void*)FindGlyph((ImWchar)c))\r\n        glyph->Visible = visible ? 1 : 0;\r\n}\r\n\r\nvoid ImFont::GrowIndex(int new_size)\r\n{\r\n    IM_ASSERT(IndexAdvanceX.Size == IndexLookup.Size);\r\n    if (new_size <= IndexLookup.Size)\r\n        return;\r\n    IndexAdvanceX.resize(new_size, -1.0f);\r\n    IndexLookup.resize(new_size, (ImWchar)-1);\r\n}\r\n\r\n// x0/y0/x1/y1 are offset from the character upper-left layout position, in pixels. Therefore x0/y0 are often fairly close to zero.\r\n// Not to be mistaken with texture coordinates, which are held by u0/v0/u1/v1 in normalized format (0.0..1.0 on each texture axis).\r\n// 'cfg' is not necessarily == 'this->ConfigData' because multiple source fonts+configs can be used to build one target font.\r\nvoid ImFont::AddGlyph(const ImFontConfig* cfg, ImWchar codepoint, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1, float advance_x)\r\n{\r\n    if (cfg != NULL)\r\n    {\r\n        // Clamp & recenter if needed\r\n        const float advance_x_original = advance_x;\r\n        advance_x = ImClamp(advance_x, cfg->GlyphMinAdvanceX, cfg->GlyphMaxAdvanceX);\r\n        if (advance_x != advance_x_original)\r\n        {\r\n            float char_off_x = cfg->PixelSnapH ? ImFloor((advance_x - advance_x_original) * 0.5f) : (advance_x - advance_x_original) * 0.5f;\r\n            x0 += char_off_x;\r\n            x1 += char_off_x;\r\n        }\r\n\r\n        // Snap to pixel\r\n        if (cfg->PixelSnapH)\r\n            advance_x = IM_ROUND(advance_x);\r\n\r\n        // Bake spacing\r\n        advance_x += cfg->GlyphExtraSpacing.x;\r\n    }\r\n\r\n    Glyphs.resize(Glyphs.Size + 1);\r\n    ImFontGlyph& glyph = Glyphs.back();\r\n    glyph.Codepoint = (unsigned int)codepoint;\r\n    glyph.Visible = (x0 != x1) && (y0 != y1);\r\n    glyph.Colored = false;\r\n    glyph.X0 = x0;\r\n    glyph.Y0 = y0;\r\n    glyph.X1 = x1;\r\n    glyph.Y1 = y1;\r\n    glyph.U0 = u0;\r\n    glyph.V0 = v0;\r\n    glyph.U1 = u1;\r\n    glyph.V1 = v1;\r\n    glyph.AdvanceX = advance_x;\r\n\r\n    // Compute rough surface usage metrics (+1 to account for average padding, +0.99 to round)\r\n    // We use (U1-U0)*TexWidth instead of X1-X0 to account for oversampling.\r\n    float pad = ContainerAtlas->TexGlyphPadding + 0.99f;\r\n    DirtyLookupTables = true;\r\n    MetricsTotalSurface += (int)((glyph.U1 - glyph.U0) * ContainerAtlas->TexWidth + pad) * (int)((glyph.V1 - glyph.V0) * ContainerAtlas->TexHeight + pad);\r\n}\r\n\r\nvoid ImFont::AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst)\r\n{\r\n    IM_ASSERT(IndexLookup.Size > 0);    // Currently this can only be called AFTER the font has been built, aka after calling ImFontAtlas::GetTexDataAs*() function.\r\n    unsigned int index_size = (unsigned int)IndexLookup.Size;\r\n\r\n    if (dst < index_size && IndexLookup.Data[dst] == (ImWchar)-1 && !overwrite_dst) // 'dst' already exists\r\n        return;\r\n    if (src >= index_size && dst >= index_size) // both 'dst' and 'src' don't exist -> no-op\r\n        return;\r\n\r\n    GrowIndex(dst + 1);\r\n    IndexLookup[dst] = (src < index_size) ? IndexLookup.Data[src] : (ImWchar)-1;\r\n    IndexAdvanceX[dst] = (src < index_size) ? IndexAdvanceX.Data[src] : 1.0f;\r\n}\r\n\r\nconst ImFontGlyph* ImFont::FindGlyph(ImWchar c) const\r\n{\r\n    if (c >= (size_t)IndexLookup.Size)\r\n        return FallbackGlyph;\r\n    const ImWchar i = IndexLookup.Data[c];\r\n    if (i == (ImWchar)-1)\r\n        return FallbackGlyph;\r\n    return &Glyphs.Data[i];\r\n}\r\n\r\nconst ImFontGlyph* ImFont::FindGlyphNoFallback(ImWchar c) const\r\n{\r\n    if (c >= (size_t)IndexLookup.Size)\r\n        return NULL;\r\n    const ImWchar i = IndexLookup.Data[c];\r\n    if (i == (ImWchar)-1)\r\n        return NULL;\r\n    return &Glyphs.Data[i];\r\n}\r\n\r\nconst char* ImFont::CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) const\r\n{\r\n    // Simple word-wrapping for English, not full-featured. Please submit failing cases!\r\n    // FIXME: Much possible improvements (don't cut things like \"word !\", \"word!!!\" but cut within \"word,,,,\", more sensible support for punctuations, support for Unicode punctuations, etc.)\r\n\r\n    // For references, possible wrap point marked with ^\r\n    //  \"aaa bbb, ccc,ddd. eee   fff. ggg!\"\r\n    //      ^    ^    ^   ^   ^__    ^    ^\r\n\r\n    // List of hardcoded separators: .,;!?'\"\r\n\r\n    // Skip extra blanks after a line returns (that includes not counting them in width computation)\r\n    // e.g. \"Hello    world\" --> \"Hello\" \"World\"\r\n\r\n    // Cut words that cannot possibly fit within one line.\r\n    // e.g.: \"The tropical fish\" with ~5 characters worth of width --> \"The tr\" \"opical\" \"fish\"\r\n\r\n    float line_width = 0.0f;\r\n    float word_width = 0.0f;\r\n    float blank_width = 0.0f;\r\n    wrap_width /= scale; // We work with unscaled widths to avoid scaling every characters\r\n\r\n    const char* word_end = text;\r\n    const char* prev_word_end = NULL;\r\n    bool inside_word = true;\r\n\r\n    const char* s = text;\r\n    while (s < text_end)\r\n    {\r\n        unsigned int c = (unsigned int)*s;\r\n        const char* next_s;\r\n        if (c < 0x80)\r\n            next_s = s + 1;\r\n        else\r\n            next_s = s + ImTextCharFromUtf8(&c, s, text_end);\r\n        if (c == 0)\r\n            break;\r\n\r\n        if (c < 32)\r\n        {\r\n            if (c == '\\n')\r\n            {\r\n                line_width = word_width = blank_width = 0.0f;\r\n                inside_word = true;\r\n                s = next_s;\r\n                continue;\r\n            }\r\n            if (c == '\\r')\r\n            {\r\n                s = next_s;\r\n                continue;\r\n            }\r\n        }\r\n\r\n        const float char_width = ((int)c < IndexAdvanceX.Size ? IndexAdvanceX.Data[c] : FallbackAdvanceX);\r\n        if (ImCharIsBlankW(c))\r\n        {\r\n            if (inside_word)\r\n            {\r\n                line_width += blank_width;\r\n                blank_width = 0.0f;\r\n                word_end = s;\r\n            }\r\n            blank_width += char_width;\r\n            inside_word = false;\r\n        }\r\n        else\r\n        {\r\n            word_width += char_width;\r\n            if (inside_word)\r\n            {\r\n                word_end = next_s;\r\n            }\r\n            else\r\n            {\r\n                prev_word_end = word_end;\r\n                line_width += word_width + blank_width;\r\n                word_width = blank_width = 0.0f;\r\n            }\r\n\r\n            // Allow wrapping after punctuation.\r\n            inside_word = (c != '.' && c != ',' && c != ';' && c != '!' && c != '?' && c != '\\\"');\r\n        }\r\n\r\n        // We ignore blank width at the end of the line (they can be skipped)\r\n        if (line_width + word_width > wrap_width)\r\n        {\r\n            // Words that cannot possibly fit within an entire line will be cut anywhere.\r\n            if (word_width < wrap_width)\r\n                s = prev_word_end ? prev_word_end : word_end;\r\n            break;\r\n        }\r\n\r\n        s = next_s;\r\n    }\r\n\r\n    return s;\r\n}\r\n\r\nImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end, const char** remaining) const\r\n{\r\n    if (!text_end)\r\n        text_end = text_begin + strlen(text_begin); // FIXME-OPT: Need to avoid this.\r\n\r\n    const float line_height = size;\r\n    const float scale = size / FontSize;\r\n\r\n    ImVec2 text_size = ImVec2(0, 0);\r\n    float line_width = 0.0f;\r\n\r\n    const bool word_wrap_enabled = (wrap_width > 0.0f);\r\n    const char* word_wrap_eol = NULL;\r\n\r\n    const char* s = text_begin;\r\n    while (s < text_end)\r\n    {\r\n        if (word_wrap_enabled)\r\n        {\r\n            // Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature.\r\n            if (!word_wrap_eol)\r\n            {\r\n                word_wrap_eol = CalcWordWrapPositionA(scale, s, text_end, wrap_width - line_width);\r\n                if (word_wrap_eol == s) // Wrap_width is too small to fit anything. Force displaying 1 character to minimize the height discontinuity.\r\n                    word_wrap_eol++;    // +1 may not be a character start point in UTF-8 but it's ok because we use s >= word_wrap_eol below\r\n            }\r\n\r\n            if (s >= word_wrap_eol)\r\n            {\r\n                if (text_size.x < line_width)\r\n                    text_size.x = line_width;\r\n                text_size.y += line_height;\r\n                line_width = 0.0f;\r\n                word_wrap_eol = NULL;\r\n\r\n                // Wrapping skips upcoming blanks\r\n                while (s < text_end)\r\n                {\r\n                    const char c = *s;\r\n                    if (ImCharIsBlankA(c)) { s++; } else if (c == '\\n') { s++; break; } else { break; }\r\n                }\r\n                continue;\r\n            }\r\n        }\r\n\r\n        // Decode and advance source\r\n        const char* prev_s = s;\r\n        unsigned int c = (unsigned int)*s;\r\n        if (c < 0x80)\r\n        {\r\n            s += 1;\r\n        }\r\n        else\r\n        {\r\n            s += ImTextCharFromUtf8(&c, s, text_end);\r\n            if (c == 0) // Malformed UTF-8?\r\n                break;\r\n        }\r\n\r\n        if (c < 32)\r\n        {\r\n            if (c == '\\n')\r\n            {\r\n                text_size.x = ImMax(text_size.x, line_width);\r\n                text_size.y += line_height;\r\n                line_width = 0.0f;\r\n                continue;\r\n            }\r\n            if (c == '\\r')\r\n                continue;\r\n        }\r\n\r\n        const float char_width = ((int)c < IndexAdvanceX.Size ? IndexAdvanceX.Data[c] : FallbackAdvanceX) * scale;\r\n        if (line_width + char_width >= max_width)\r\n        {\r\n            s = prev_s;\r\n            break;\r\n        }\r\n\r\n        line_width += char_width;\r\n    }\r\n\r\n    if (text_size.x < line_width)\r\n        text_size.x = line_width;\r\n\r\n    if (line_width > 0 || text_size.y == 0.0f)\r\n        text_size.y += line_height;\r\n\r\n    if (remaining)\r\n        *remaining = s;\r\n\r\n    return text_size;\r\n}\r\n\r\n// Note: as with every ImDrawList drawing function, this expects that the font atlas texture is bound.\r\nvoid ImFont::RenderChar(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, ImWchar c) const\r\n{\r\n    const ImFontGlyph* glyph = FindGlyph(c);\r\n    if (!glyph || !glyph->Visible)\r\n        return;\r\n    if (glyph->Colored)\r\n        col |= ~IM_COL32_A_MASK;\r\n    float scale = (size >= 0.0f) ? (size / FontSize) : 1.0f;\r\n    pos.x = IM_FLOOR(pos.x);\r\n    pos.y = IM_FLOOR(pos.y);\r\n    draw_list->PrimReserve(6, 4);\r\n    draw_list->PrimRectUV(ImVec2(pos.x + glyph->X0 * scale, pos.y + glyph->Y0 * scale), ImVec2(pos.x + glyph->X1 * scale, pos.y + glyph->Y1 * scale), ImVec2(glyph->U0, glyph->V0), ImVec2(glyph->U1, glyph->V1), col);\r\n}\r\n\r\n// Note: as with every ImDrawList drawing function, this expects that the font atlas texture is bound.\r\nvoid ImFont::RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width, bool cpu_fine_clip) const\r\n{\r\n    if (!text_end)\r\n        text_end = text_begin + strlen(text_begin); // ImGui:: functions generally already provides a valid text_end, so this is merely to handle direct calls.\r\n\r\n    // Align to be pixel perfect\r\n    pos.x = IM_FLOOR(pos.x);\r\n    pos.y = IM_FLOOR(pos.y);\r\n    float x = pos.x;\r\n    float y = pos.y;\r\n    if (y > clip_rect.w)\r\n        return;\r\n\r\n    const float scale = size / FontSize;\r\n    const float line_height = FontSize * scale;\r\n    const bool word_wrap_enabled = (wrap_width > 0.0f);\r\n    const char* word_wrap_eol = NULL;\r\n\r\n    // Fast-forward to first visible line\r\n    const char* s = text_begin;\r\n    if (y + line_height < clip_rect.y && !word_wrap_enabled)\r\n        while (y + line_height < clip_rect.y && s < text_end)\r\n        {\r\n            s = (const char*)memchr(s, '\\n', text_end - s);\r\n            s = s ? s + 1 : text_end;\r\n            y += line_height;\r\n        }\r\n\r\n    // For large text, scan for the last visible line in order to avoid over-reserving in the call to PrimReserve()\r\n    // Note that very large horizontal line will still be affected by the issue (e.g. a one megabyte string buffer without a newline will likely crash atm)\r\n    if (text_end - s > 10000 && !word_wrap_enabled)\r\n    {\r\n        const char* s_end = s;\r\n        float y_end = y;\r\n        while (y_end < clip_rect.w && s_end < text_end)\r\n        {\r\n            s_end = (const char*)memchr(s_end, '\\n', text_end - s_end);\r\n            s_end = s_end ? s_end + 1 : text_end;\r\n            y_end += line_height;\r\n        }\r\n        text_end = s_end;\r\n    }\r\n    if (s == text_end)\r\n        return;\r\n\r\n    // Reserve vertices for remaining worse case (over-reserving is useful and easily amortized)\r\n    const int vtx_count_max = (int)(text_end - s) * 4;\r\n    const int idx_count_max = (int)(text_end - s) * 6;\r\n    const int idx_expected_size = draw_list->IdxBuffer.Size + idx_count_max;\r\n    draw_list->PrimReserve(idx_count_max, vtx_count_max);\r\n\r\n    ImDrawVert* vtx_write = draw_list->_VtxWritePtr;\r\n    ImDrawIdx* idx_write = draw_list->_IdxWritePtr;\r\n    unsigned int vtx_current_idx = draw_list->_VtxCurrentIdx;\r\n\r\n    const ImU32 col_untinted = col | ~IM_COL32_A_MASK;\r\n\r\n    while (s < text_end)\r\n    {\r\n        if (word_wrap_enabled)\r\n        {\r\n            // Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature.\r\n            if (!word_wrap_eol)\r\n            {\r\n                word_wrap_eol = CalcWordWrapPositionA(scale, s, text_end, wrap_width - (x - pos.x));\r\n                if (word_wrap_eol == s) // Wrap_width is too small to fit anything. Force displaying 1 character to minimize the height discontinuity.\r\n                    word_wrap_eol++;    // +1 may not be a character start point in UTF-8 but it's ok because we use s >= word_wrap_eol below\r\n            }\r\n\r\n            if (s >= word_wrap_eol)\r\n            {\r\n                x = pos.x;\r\n                y += line_height;\r\n                word_wrap_eol = NULL;\r\n\r\n                // Wrapping skips upcoming blanks\r\n                while (s < text_end)\r\n                {\r\n                    const char c = *s;\r\n                    if (ImCharIsBlankA(c)) { s++; } else if (c == '\\n') { s++; break; } else { break; }\r\n                }\r\n                continue;\r\n            }\r\n        }\r\n\r\n        // Decode and advance source\r\n        unsigned int c = (unsigned int)*s;\r\n        if (c < 0x80)\r\n        {\r\n            s += 1;\r\n        }\r\n        else\r\n        {\r\n            s += ImTextCharFromUtf8(&c, s, text_end);\r\n            if (c == 0) // Malformed UTF-8?\r\n                break;\r\n        }\r\n\r\n        if (c < 32)\r\n        {\r\n            if (c == '\\n')\r\n            {\r\n                x = pos.x;\r\n                y += line_height;\r\n                if (y > clip_rect.w)\r\n                    break; // break out of main loop\r\n                continue;\r\n            }\r\n            if (c == '\\r')\r\n                continue;\r\n        }\r\n\r\n        const ImFontGlyph* glyph = FindGlyph((ImWchar)c);\r\n        if (glyph == NULL)\r\n            continue;\r\n\r\n        float char_width = glyph->AdvanceX * scale;\r\n        if (glyph->Visible)\r\n        {\r\n            // We don't do a second finer clipping test on the Y axis as we've already skipped anything before clip_rect.y and exit once we pass clip_rect.w\r\n            float x1 = x + glyph->X0 * scale;\r\n            float x2 = x + glyph->X1 * scale;\r\n            float y1 = y + glyph->Y0 * scale;\r\n            float y2 = y + glyph->Y1 * scale;\r\n            if (x1 <= clip_rect.z && x2 >= clip_rect.x)\r\n            {\r\n                // Render a character\r\n                float u1 = glyph->U0;\r\n                float v1 = glyph->V0;\r\n                float u2 = glyph->U1;\r\n                float v2 = glyph->V1;\r\n\r\n                // CPU side clipping used to fit text in their frame when the frame is too small. Only does clipping for axis aligned quads.\r\n                if (cpu_fine_clip)\r\n                {\r\n                    if (x1 < clip_rect.x)\r\n                    {\r\n                        u1 = u1 + (1.0f - (x2 - clip_rect.x) / (x2 - x1)) * (u2 - u1);\r\n                        x1 = clip_rect.x;\r\n                    }\r\n                    if (y1 < clip_rect.y)\r\n                    {\r\n                        v1 = v1 + (1.0f - (y2 - clip_rect.y) / (y2 - y1)) * (v2 - v1);\r\n                        y1 = clip_rect.y;\r\n                    }\r\n                    if (x2 > clip_rect.z)\r\n                    {\r\n                        u2 = u1 + ((clip_rect.z - x1) / (x2 - x1)) * (u2 - u1);\r\n                        x2 = clip_rect.z;\r\n                    }\r\n                    if (y2 > clip_rect.w)\r\n                    {\r\n                        v2 = v1 + ((clip_rect.w - y1) / (y2 - y1)) * (v2 - v1);\r\n                        y2 = clip_rect.w;\r\n                    }\r\n                    if (y1 >= y2)\r\n                    {\r\n                        x += char_width;\r\n                        continue;\r\n                    }\r\n                }\r\n\r\n                // Support for untinted glyphs\r\n                ImU32 glyph_col = glyph->Colored ? col_untinted : col;\r\n\r\n                // We are NOT calling PrimRectUV() here because non-inlined causes too much overhead in a debug builds. Inlined here:\r\n                {\r\n                    idx_write[0] = (ImDrawIdx)(vtx_current_idx); idx_write[1] = (ImDrawIdx)(vtx_current_idx+1); idx_write[2] = (ImDrawIdx)(vtx_current_idx+2);\r\n                    idx_write[3] = (ImDrawIdx)(vtx_current_idx); idx_write[4] = (ImDrawIdx)(vtx_current_idx+2); idx_write[5] = (ImDrawIdx)(vtx_current_idx+3);\r\n                    vtx_write[0].pos.x = x1; vtx_write[0].pos.y = y1; vtx_write[0].col = glyph_col; vtx_write[0].uv.x = u1; vtx_write[0].uv.y = v1;\r\n                    vtx_write[1].pos.x = x2; vtx_write[1].pos.y = y1; vtx_write[1].col = glyph_col; vtx_write[1].uv.x = u2; vtx_write[1].uv.y = v1;\r\n                    vtx_write[2].pos.x = x2; vtx_write[2].pos.y = y2; vtx_write[2].col = glyph_col; vtx_write[2].uv.x = u2; vtx_write[2].uv.y = v2;\r\n                    vtx_write[3].pos.x = x1; vtx_write[3].pos.y = y2; vtx_write[3].col = glyph_col; vtx_write[3].uv.x = u1; vtx_write[3].uv.y = v2;\r\n                    vtx_write += 4;\r\n                    vtx_current_idx += 4;\r\n                    idx_write += 6;\r\n                }\r\n            }\r\n        }\r\n        x += char_width;\r\n    }\r\n\r\n    // Give back unused vertices (clipped ones, blanks) ~ this is essentially a PrimUnreserve() action.\r\n    draw_list->VtxBuffer.Size = (int)(vtx_write - draw_list->VtxBuffer.Data); // Same as calling shrink()\r\n    draw_list->IdxBuffer.Size = (int)(idx_write - draw_list->IdxBuffer.Data);\r\n    draw_list->CmdBuffer[draw_list->CmdBuffer.Size - 1].ElemCount -= (idx_expected_size - draw_list->IdxBuffer.Size);\r\n    draw_list->_VtxWritePtr = vtx_write;\r\n    draw_list->_IdxWritePtr = idx_write;\r\n    draw_list->_VtxCurrentIdx = vtx_current_idx;\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] ImGui Internal Render Helpers\r\n//-----------------------------------------------------------------------------\r\n// Vaguely redesigned to stop accessing ImGui global state:\r\n// - RenderArrow()\r\n// - RenderBullet()\r\n// - RenderCheckMark()\r\n// - RenderMouseCursor()\r\n// - RenderArrowPointingAt()\r\n// - RenderRectFilledRangeH()\r\n// - RenderRectFilledWithHole()\r\n//-----------------------------------------------------------------------------\r\n// Function in need of a redesign (legacy mess)\r\n// - RenderColorRectWithAlphaCheckerboard()\r\n//-----------------------------------------------------------------------------\r\n\r\n// Render an arrow aimed to be aligned with text (p_min is a position in the same space text would be positioned). To e.g. denote expanded/collapsed state\r\nvoid ImGui::RenderArrow(ImDrawList* draw_list, ImVec2 pos, ImU32 col, ImGuiDir dir, float scale)\r\n{\r\n    const float h = draw_list->_Data->FontSize * 1.00f;\r\n    float r = h * 0.40f * scale;\r\n    ImVec2 center = pos + ImVec2(h * 0.50f, h * 0.50f * scale);\r\n\r\n    ImVec2 a, b, c;\r\n    switch (dir)\r\n    {\r\n    case ImGuiDir_Up:\r\n    case ImGuiDir_Down:\r\n        if (dir == ImGuiDir_Up) r = -r;\r\n        a = ImVec2(+0.000f, +0.750f) * r;\r\n        b = ImVec2(-0.866f, -0.750f) * r;\r\n        c = ImVec2(+0.866f, -0.750f) * r;\r\n        break;\r\n    case ImGuiDir_Left:\r\n    case ImGuiDir_Right:\r\n        if (dir == ImGuiDir_Left) r = -r;\r\n        a = ImVec2(+0.750f, +0.000f) * r;\r\n        b = ImVec2(-0.750f, +0.866f) * r;\r\n        c = ImVec2(-0.750f, -0.866f) * r;\r\n        break;\r\n    case ImGuiDir_None:\r\n    case ImGuiDir_COUNT:\r\n        IM_ASSERT(0);\r\n        break;\r\n    }\r\n    draw_list->AddTriangleFilled(center + a, center + b, center + c, col);\r\n}\r\n\r\nvoid ImGui::RenderBullet(ImDrawList* draw_list, ImVec2 pos, ImU32 col)\r\n{\r\n    draw_list->AddCircleFilled(pos, draw_list->_Data->FontSize * 0.20f, col, 8);\r\n}\r\n\r\nvoid ImGui::RenderCheckMark(ImDrawList* draw_list, ImVec2 pos, ImU32 col, float sz)\r\n{\r\n    float thickness = ImMax(sz / 5.0f, 1.0f);\r\n    sz -= thickness * 0.5f;\r\n    pos += ImVec2(thickness * 0.25f, thickness * 0.25f);\r\n\r\n    float third = sz / 3.0f;\r\n    float bx = pos.x + third;\r\n    float by = pos.y + sz - third * 0.5f;\r\n    draw_list->PathLineTo(ImVec2(bx - third, by - third));\r\n    draw_list->PathLineTo(ImVec2(bx, by));\r\n    draw_list->PathLineTo(ImVec2(bx + third * 2.0f, by - third * 2.0f));\r\n    draw_list->PathStroke(col, 0, thickness);\r\n}\r\n\r\nvoid ImGui::RenderMouseCursor(ImDrawList* draw_list, ImVec2 pos, float scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow)\r\n{\r\n    if (mouse_cursor == ImGuiMouseCursor_None)\r\n        return;\r\n    IM_ASSERT(mouse_cursor > ImGuiMouseCursor_None && mouse_cursor < ImGuiMouseCursor_COUNT);\r\n\r\n    ImFontAtlas* font_atlas = draw_list->_Data->Font->ContainerAtlas;\r\n    ImVec2 offset, size, uv[4];\r\n    if (font_atlas->GetMouseCursorTexData(mouse_cursor, &offset, &size, &uv[0], &uv[2]))\r\n    {\r\n        pos -= offset;\r\n        ImTextureID tex_id = font_atlas->TexID;\r\n        draw_list->PushTextureID(tex_id);\r\n        draw_list->AddImage(tex_id, pos + ImVec2(1, 0) * scale, pos + (ImVec2(1, 0) + size) * scale,    uv[2], uv[3], col_shadow);\r\n        draw_list->AddImage(tex_id, pos + ImVec2(2, 0) * scale, pos + (ImVec2(2, 0) + size) * scale,    uv[2], uv[3], col_shadow);\r\n        draw_list->AddImage(tex_id, pos,                        pos + size * scale,                     uv[2], uv[3], col_border);\r\n        draw_list->AddImage(tex_id, pos,                        pos + size * scale,                     uv[0], uv[1], col_fill);\r\n        draw_list->PopTextureID();\r\n    }\r\n}\r\n\r\n// Render an arrow. 'pos' is position of the arrow tip. half_sz.x is length from base to tip. half_sz.y is length on each side.\r\nvoid ImGui::RenderArrowPointingAt(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, ImGuiDir direction, ImU32 col)\r\n{\r\n    switch (direction)\r\n    {\r\n    case ImGuiDir_Left:  draw_list->AddTriangleFilled(ImVec2(pos.x + half_sz.x, pos.y - half_sz.y), ImVec2(pos.x + half_sz.x, pos.y + half_sz.y), pos, col); return;\r\n    case ImGuiDir_Right: draw_list->AddTriangleFilled(ImVec2(pos.x - half_sz.x, pos.y + half_sz.y), ImVec2(pos.x - half_sz.x, pos.y - half_sz.y), pos, col); return;\r\n    case ImGuiDir_Up:    draw_list->AddTriangleFilled(ImVec2(pos.x + half_sz.x, pos.y + half_sz.y), ImVec2(pos.x - half_sz.x, pos.y + half_sz.y), pos, col); return;\r\n    case ImGuiDir_Down:  draw_list->AddTriangleFilled(ImVec2(pos.x - half_sz.x, pos.y - half_sz.y), ImVec2(pos.x + half_sz.x, pos.y - half_sz.y), pos, col); return;\r\n    case ImGuiDir_None: case ImGuiDir_COUNT: break; // Fix warnings\r\n    }\r\n}\r\n\r\nstatic inline float ImAcos01(float x)\r\n{\r\n    if (x <= 0.0f) return IM_PI * 0.5f;\r\n    if (x >= 1.0f) return 0.0f;\r\n    return ImAcos(x);\r\n    //return (-0.69813170079773212f * x * x - 0.87266462599716477f) * x + 1.5707963267948966f; // Cheap approximation, may be enough for what we do.\r\n}\r\n\r\n// FIXME: Cleanup and move code to ImDrawList.\r\nvoid ImGui::RenderRectFilledRangeH(ImDrawList* draw_list, const ImRect& rect, ImU32 col, float x_start_norm, float x_end_norm, float rounding)\r\n{\r\n    if (x_end_norm == x_start_norm)\r\n        return;\r\n    if (x_start_norm > x_end_norm)\r\n        ImSwap(x_start_norm, x_end_norm);\r\n\r\n    ImVec2 p0 = ImVec2(ImLerp(rect.Min.x, rect.Max.x, x_start_norm), rect.Min.y);\r\n    ImVec2 p1 = ImVec2(ImLerp(rect.Min.x, rect.Max.x, x_end_norm), rect.Max.y);\r\n    if (rounding == 0.0f)\r\n    {\r\n        draw_list->AddRectFilled(p0, p1, col, 0.0f);\r\n        return;\r\n    }\r\n\r\n    rounding = ImClamp(ImMin((rect.Max.x - rect.Min.x) * 0.5f, (rect.Max.y - rect.Min.y) * 0.5f) - 1.0f, 0.0f, rounding);\r\n    const float inv_rounding = 1.0f / rounding;\r\n    const float arc0_b = ImAcos01(1.0f - (p0.x - rect.Min.x) * inv_rounding);\r\n    const float arc0_e = ImAcos01(1.0f - (p1.x - rect.Min.x) * inv_rounding);\r\n    const float half_pi = IM_PI * 0.5f; // We will == compare to this because we know this is the exact value ImAcos01 can return.\r\n    const float x0 = ImMax(p0.x, rect.Min.x + rounding);\r\n    if (arc0_b == arc0_e)\r\n    {\r\n        draw_list->PathLineTo(ImVec2(x0, p1.y));\r\n        draw_list->PathLineTo(ImVec2(x0, p0.y));\r\n    }\r\n    else if (arc0_b == 0.0f && arc0_e == half_pi)\r\n    {\r\n        draw_list->PathArcToFast(ImVec2(x0, p1.y - rounding), rounding, 3, 6); // BL\r\n        draw_list->PathArcToFast(ImVec2(x0, p0.y + rounding), rounding, 6, 9); // TR\r\n    }\r\n    else\r\n    {\r\n        draw_list->PathArcTo(ImVec2(x0, p1.y - rounding), rounding, IM_PI - arc0_e, IM_PI - arc0_b, 3); // BL\r\n        draw_list->PathArcTo(ImVec2(x0, p0.y + rounding), rounding, IM_PI + arc0_b, IM_PI + arc0_e, 3); // TR\r\n    }\r\n    if (p1.x > rect.Min.x + rounding)\r\n    {\r\n        const float arc1_b = ImAcos01(1.0f - (rect.Max.x - p1.x) * inv_rounding);\r\n        const float arc1_e = ImAcos01(1.0f - (rect.Max.x - p0.x) * inv_rounding);\r\n        const float x1 = ImMin(p1.x, rect.Max.x - rounding);\r\n        if (arc1_b == arc1_e)\r\n        {\r\n            draw_list->PathLineTo(ImVec2(x1, p0.y));\r\n            draw_list->PathLineTo(ImVec2(x1, p1.y));\r\n        }\r\n        else if (arc1_b == 0.0f && arc1_e == half_pi)\r\n        {\r\n            draw_list->PathArcToFast(ImVec2(x1, p0.y + rounding), rounding, 9, 12); // TR\r\n            draw_list->PathArcToFast(ImVec2(x1, p1.y - rounding), rounding, 0, 3);  // BR\r\n        }\r\n        else\r\n        {\r\n            draw_list->PathArcTo(ImVec2(x1, p0.y + rounding), rounding, -arc1_e, -arc1_b, 3); // TR\r\n            draw_list->PathArcTo(ImVec2(x1, p1.y - rounding), rounding, +arc1_b, +arc1_e, 3); // BR\r\n        }\r\n    }\r\n    draw_list->PathFillConvex(col);\r\n}\r\n\r\nvoid ImGui::RenderRectFilledWithHole(ImDrawList* draw_list, ImRect outer, ImRect inner, ImU32 col, float rounding)\r\n{\r\n    const bool fill_L = (inner.Min.x > outer.Min.x);\r\n    const bool fill_R = (inner.Max.x < outer.Max.x);\r\n    const bool fill_U = (inner.Min.y > outer.Min.y);\r\n    const bool fill_D = (inner.Max.y < outer.Max.y);\r\n    if (fill_L) draw_list->AddRectFilled(ImVec2(outer.Min.x, inner.Min.y), ImVec2(inner.Min.x, inner.Max.y), col, rounding, ImDrawFlags_RoundCornersNone | (fill_U ? 0 : ImDrawFlags_RoundCornersTopLeft)    | (fill_D ? 0 : ImDrawFlags_RoundCornersBottomLeft));\r\n    if (fill_R) draw_list->AddRectFilled(ImVec2(inner.Max.x, inner.Min.y), ImVec2(outer.Max.x, inner.Max.y), col, rounding, ImDrawFlags_RoundCornersNone | (fill_U ? 0 : ImDrawFlags_RoundCornersTopRight)   | (fill_D ? 0 : ImDrawFlags_RoundCornersBottomRight));\r\n    if (fill_U) draw_list->AddRectFilled(ImVec2(inner.Min.x, outer.Min.y), ImVec2(inner.Max.x, inner.Min.y), col, rounding, ImDrawFlags_RoundCornersNone | (fill_L ? 0 : ImDrawFlags_RoundCornersTopLeft)    | (fill_R ? 0 : ImDrawFlags_RoundCornersTopRight));\r\n    if (fill_D) draw_list->AddRectFilled(ImVec2(inner.Min.x, inner.Max.y), ImVec2(inner.Max.x, outer.Max.y), col, rounding, ImDrawFlags_RoundCornersNone | (fill_L ? 0 : ImDrawFlags_RoundCornersBottomLeft) | (fill_R ? 0 : ImDrawFlags_RoundCornersBottomRight));\r\n    if (fill_L && fill_U) draw_list->AddRectFilled(ImVec2(outer.Min.x, outer.Min.y), ImVec2(inner.Min.x, inner.Min.y), col, rounding, ImDrawFlags_RoundCornersTopLeft);\r\n    if (fill_R && fill_U) draw_list->AddRectFilled(ImVec2(inner.Max.x, outer.Min.y), ImVec2(outer.Max.x, inner.Min.y), col, rounding, ImDrawFlags_RoundCornersTopRight);\r\n    if (fill_L && fill_D) draw_list->AddRectFilled(ImVec2(outer.Min.x, inner.Max.y), ImVec2(inner.Min.x, outer.Max.y), col, rounding, ImDrawFlags_RoundCornersBottomLeft);\r\n    if (fill_R && fill_D) draw_list->AddRectFilled(ImVec2(inner.Max.x, inner.Max.y), ImVec2(outer.Max.x, outer.Max.y), col, rounding, ImDrawFlags_RoundCornersBottomRight);\r\n}\r\n\r\n// Helper for ColorPicker4()\r\n// NB: This is rather brittle and will show artifact when rounding this enabled if rounded corners overlap multiple cells. Caller currently responsible for avoiding that.\r\n// Spent a non reasonable amount of time trying to getting this right for ColorButton with rounding+anti-aliasing+ImGuiColorEditFlags_HalfAlphaPreview flag + various grid sizes and offsets, and eventually gave up... probably more reasonable to disable rounding altogether.\r\n// FIXME: uses ImGui::GetColorU32\r\nvoid ImGui::RenderColorRectWithAlphaCheckerboard(ImDrawList* draw_list, ImVec2 p_min, ImVec2 p_max, ImU32 col, float grid_step, ImVec2 grid_off, float rounding, ImDrawFlags flags)\r\n{\r\n    if ((flags & ImDrawFlags_RoundCornersMask_) == 0)\r\n        flags = ImDrawFlags_RoundCornersDefault_;\r\n    if (((col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT) < 0xFF)\r\n    {\r\n        ImU32 col_bg1 = GetColorU32(ImAlphaBlendColors(IM_COL32(204, 204, 204, 255), col));\r\n        ImU32 col_bg2 = GetColorU32(ImAlphaBlendColors(IM_COL32(128, 128, 128, 255), col));\r\n        draw_list->AddRectFilled(p_min, p_max, col_bg1, rounding, flags);\r\n\r\n        int yi = 0;\r\n        for (float y = p_min.y + grid_off.y; y < p_max.y; y += grid_step, yi++)\r\n        {\r\n            float y1 = ImClamp(y, p_min.y, p_max.y), y2 = ImMin(y + grid_step, p_max.y);\r\n            if (y2 <= y1)\r\n                continue;\r\n            for (float x = p_min.x + grid_off.x + (yi & 1) * grid_step; x < p_max.x; x += grid_step * 2.0f)\r\n            {\r\n                float x1 = ImClamp(x, p_min.x, p_max.x), x2 = ImMin(x + grid_step, p_max.x);\r\n                if (x2 <= x1)\r\n                    continue;\r\n                ImDrawFlags cell_flags = ImDrawFlags_RoundCornersNone;\r\n                if (y1 <= p_min.y) { if (x1 <= p_min.x) cell_flags |= ImDrawFlags_RoundCornersTopLeft; if (x2 >= p_max.x) cell_flags |= ImDrawFlags_RoundCornersTopRight; }\r\n                if (y2 >= p_max.y) { if (x1 <= p_min.x) cell_flags |= ImDrawFlags_RoundCornersBottomLeft; if (x2 >= p_max.x) cell_flags |= ImDrawFlags_RoundCornersBottomRight; }\r\n\r\n                // Combine flags\r\n                cell_flags = (flags == ImDrawFlags_RoundCornersNone || cell_flags == ImDrawFlags_RoundCornersNone) ? ImDrawFlags_RoundCornersNone : (cell_flags & flags);\r\n                draw_list->AddRectFilled(ImVec2(x1, y1), ImVec2(x2, y2), col_bg2, rounding, cell_flags);\r\n            }\r\n        }\r\n    }\r\n    else\r\n    {\r\n        draw_list->AddRectFilled(p_min, p_max, col, rounding, flags);\r\n    }\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Decompression code\r\n//-----------------------------------------------------------------------------\r\n// Compressed with stb_compress() then converted to a C array and encoded as base85.\r\n// Use the program in misc/fonts/binary_to_compressed_c.cpp to create the array from a TTF file.\r\n// The purpose of encoding as base85 instead of \"0x00,0x01,...\" style is only save on _source code_ size.\r\n// Decompression from stb.h (public domain) by Sean Barrett https://github.com/nothings/stb/blob/master/stb.h\r\n//-----------------------------------------------------------------------------\r\n\r\nstatic unsigned int stb_decompress_length(const unsigned char *input)\r\n{\r\n    return (input[8] << 24) + (input[9] << 16) + (input[10] << 8) + input[11];\r\n}\r\n\r\nstatic unsigned char *stb__barrier_out_e, *stb__barrier_out_b;\r\nstatic const unsigned char *stb__barrier_in_b;\r\nstatic unsigned char *stb__dout;\r\nstatic void stb__match(const unsigned char *data, unsigned int length)\r\n{\r\n    // INVERSE of memmove... write each byte before copying the next...\r\n    IM_ASSERT(stb__dout + length <= stb__barrier_out_e);\r\n    if (stb__dout + length > stb__barrier_out_e) { stb__dout += length; return; }\r\n    if (data < stb__barrier_out_b) { stb__dout = stb__barrier_out_e+1; return; }\r\n    while (length--) *stb__dout++ = *data++;\r\n}\r\n\r\nstatic void stb__lit(const unsigned char *data, unsigned int length)\r\n{\r\n    IM_ASSERT(stb__dout + length <= stb__barrier_out_e);\r\n    if (stb__dout + length > stb__barrier_out_e) { stb__dout += length; return; }\r\n    if (data < stb__barrier_in_b) { stb__dout = stb__barrier_out_e+1; return; }\r\n    memcpy(stb__dout, data, length);\r\n    stb__dout += length;\r\n}\r\n\r\n#define stb__in2(x)   ((i[x] << 8) + i[(x)+1])\r\n#define stb__in3(x)   ((i[x] << 16) + stb__in2((x)+1))\r\n#define stb__in4(x)   ((i[x] << 24) + stb__in3((x)+1))\r\n\r\nstatic const unsigned char *stb_decompress_token(const unsigned char *i)\r\n{\r\n    if (*i >= 0x20) { // use fewer if's for cases that expand small\r\n        if (*i >= 0x80)       stb__match(stb__dout-i[1]-1, i[0] - 0x80 + 1), i += 2;\r\n        else if (*i >= 0x40)  stb__match(stb__dout-(stb__in2(0) - 0x4000 + 1), i[2]+1), i += 3;\r\n        else /* *i >= 0x20 */ stb__lit(i+1, i[0] - 0x20 + 1), i += 1 + (i[0] - 0x20 + 1);\r\n    } else { // more ifs for cases that expand large, since overhead is amortized\r\n        if (*i >= 0x18)       stb__match(stb__dout-(stb__in3(0) - 0x180000 + 1), i[3]+1), i += 4;\r\n        else if (*i >= 0x10)  stb__match(stb__dout-(stb__in3(0) - 0x100000 + 1), stb__in2(3)+1), i += 5;\r\n        else if (*i >= 0x08)  stb__lit(i+2, stb__in2(0) - 0x0800 + 1), i += 2 + (stb__in2(0) - 0x0800 + 1);\r\n        else if (*i == 0x07)  stb__lit(i+3, stb__in2(1) + 1), i += 3 + (stb__in2(1) + 1);\r\n        else if (*i == 0x06)  stb__match(stb__dout-(stb__in3(1)+1), i[4]+1), i += 5;\r\n        else if (*i == 0x04)  stb__match(stb__dout-(stb__in3(1)+1), stb__in2(4)+1), i += 6;\r\n    }\r\n    return i;\r\n}\r\n\r\nstatic unsigned int stb_adler32(unsigned int adler32, unsigned char *buffer, unsigned int buflen)\r\n{\r\n    const unsigned long ADLER_MOD = 65521;\r\n    unsigned long s1 = adler32 & 0xffff, s2 = adler32 >> 16;\r\n    unsigned long blocklen = buflen % 5552;\r\n\r\n    unsigned long i;\r\n    while (buflen) {\r\n        for (i=0; i + 7 < blocklen; i += 8) {\r\n            s1 += buffer[0], s2 += s1;\r\n            s1 += buffer[1], s2 += s1;\r\n            s1 += buffer[2], s2 += s1;\r\n            s1 += buffer[3], s2 += s1;\r\n            s1 += buffer[4], s2 += s1;\r\n            s1 += buffer[5], s2 += s1;\r\n            s1 += buffer[6], s2 += s1;\r\n            s1 += buffer[7], s2 += s1;\r\n\r\n            buffer += 8;\r\n        }\r\n\r\n        for (; i < blocklen; ++i)\r\n            s1 += *buffer++, s2 += s1;\r\n\r\n        s1 %= ADLER_MOD, s2 %= ADLER_MOD;\r\n        buflen -= blocklen;\r\n        blocklen = 5552;\r\n    }\r\n    return (unsigned int)(s2 << 16) + (unsigned int)s1;\r\n}\r\n\r\nstatic unsigned int stb_decompress(unsigned char *output, const unsigned char *i, unsigned int /*length*/)\r\n{\r\n    if (stb__in4(0) != 0x57bC0000) return 0;\r\n    if (stb__in4(4) != 0)          return 0; // error! stream is > 4GB\r\n    const unsigned int olen = stb_decompress_length(i);\r\n    stb__barrier_in_b = i;\r\n    stb__barrier_out_e = output + olen;\r\n    stb__barrier_out_b = output;\r\n    i += 16;\r\n\r\n    stb__dout = output;\r\n    for (;;) {\r\n        const unsigned char *old_i = i;\r\n        i = stb_decompress_token(i);\r\n        if (i == old_i) {\r\n            if (*i == 0x05 && i[1] == 0xfa) {\r\n                IM_ASSERT(stb__dout == output + olen);\r\n                if (stb__dout != output + olen) return 0;\r\n                if (stb_adler32(1, output, olen) != (unsigned int) stb__in4(2))\r\n                    return 0;\r\n                return olen;\r\n            } else {\r\n                IM_ASSERT(0); /* NOTREACHED */\r\n                return 0;\r\n            }\r\n        }\r\n        IM_ASSERT(stb__dout <= output + olen);\r\n        if (stb__dout > output + olen)\r\n            return 0;\r\n    }\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Default font data (ProggyClean.ttf)\r\n//-----------------------------------------------------------------------------\r\n// ProggyClean.ttf\r\n// Copyright (c) 2004, 2005 Tristan Grimmer\r\n// MIT license (see License.txt in http://www.upperbounds.net/download/ProggyClean.ttf.zip)\r\n// Download and more information at http://upperbounds.net\r\n//-----------------------------------------------------------------------------\r\n// File: 'ProggyClean.ttf' (41208 bytes)\r\n// Exported using misc/fonts/binary_to_compressed_c.cpp (with compression + base85 string encoding).\r\n// The purpose of encoding as base85 instead of \"0x00,0x01,...\" style is only save on _source code_ size.\r\n//-----------------------------------------------------------------------------\r\nstatic const char proggy_clean_ttf_compressed_data_base85[11980 + 1] =\r\n    \"7])#######hV0qs'/###[),##/l:$#Q6>##5[n42>c-TH`->>#/e>11NNV=Bv(*:.F?uu#(gRU.o0XGH`$vhLG1hxt9?W`#,5LsCp#-i>.r$<$6pD>Lb';9Crc6tgXmKVeU2cD4Eo3R/\"\r\n    \"2*>]b(MC;$jPfY.;h^`IWM9<Lh2TlS+f-s$o6Q<BWH`YiU.xfLq$N;$0iR/GX:U(jcW2p/W*q?-qmnUCI;jHSAiFWM.R*kU@C=GH?a9wp8f$e.-4^Qg1)Q-GL(lf(r/7GrRgwV%MS=C#\"\r\n    \"`8ND>Qo#t'X#(v#Y9w0#1D$CIf;W'#pWUPXOuxXuU(H9M(1<q-UE31#^-V'8IRUo7Qf./L>=Ke$$'5F%)]0^#0X@U.a<r:QLtFsLcL6##lOj)#.Y5<-R&KgLwqJfLgN&;Q?gI^#DY2uL\"\r\n    \"i@^rMl9t=cWq6##weg>$FBjVQTSDgEKnIS7EM9>ZY9w0#L;>>#Mx&4Mvt//L[MkA#W@lK.N'[0#7RL_&#w+F%HtG9M#XL`N&.,GM4Pg;-<nLENhvx>-VsM.M0rJfLH2eTM`*oJMHRC`N\"\r\n    \"kfimM2J,W-jXS:)r0wK#@Fge$U>`w'N7G#$#fB#$E^$#:9:hk+eOe--6x)F7*E%?76%^GMHePW-Z5l'&GiF#$956:rS?dA#fiK:)Yr+`&#0j@'DbG&#^$PG.Ll+DNa<XCMKEV*N)LN/N\"\r\n    \"*b=%Q6pia-Xg8I$<MR&,VdJe$<(7G;Ckl'&hF;;$<_=X(b.RS%%)###MPBuuE1V:v&cX&#2m#(&cV]`k9OhLMbn%s$G2,B$BfD3X*sp5#l,$R#]x_X1xKX%b5U*[r5iMfUo9U`N99hG)\"\r\n    \"tm+/Us9pG)XPu`<0s-)WTt(gCRxIg(%6sfh=ktMKn3j)<6<b5Sk_/0(^]AaN#(p/L>&VZ>1i%h1S9u5o@YaaW$e+b<TWFn/Z:Oh(Cx2$lNEoN^e)#CFY@@I;BOQ*sRwZtZxRcU7uW6CX\"\r\n    \"ow0i(?$Q[cjOd[P4d)]>ROPOpxTO7Stwi1::iB1q)C_=dV26J;2,]7op$]uQr@_V7$q^%lQwtuHY]=DX,n3L#0PHDO4f9>dC@O>HBuKPpP*E,N+b3L#lpR/MrTEH.IAQk.a>D[.e;mc.\"\r\n    \"x]Ip.PH^'/aqUO/$1WxLoW0[iLA<QT;5HKD+@qQ'NQ(3_PLhE48R.qAPSwQ0/WK?Z,[x?-J;jQTWA0X@KJ(_Y8N-:/M74:/-ZpKrUss?d#dZq]DAbkU*JqkL+nwX@@47`5>w=4h(9.`G\"\r\n    \"CRUxHPeR`5Mjol(dUWxZa(>STrPkrJiWx`5U7F#.g*jrohGg`cg:lSTvEY/EV_7H4Q9[Z%cnv;JQYZ5q.l7Zeas:HOIZOB?G<Nald$qs]@]L<J7bR*>gv:[7MI2k).'2($5FNP&EQ(,)\"\r\n    \"U]W]+fh18.vsai00);D3@4ku5P?DP8aJt+;qUM]=+b'8@;mViBKx0DE[-auGl8:PJ&Dj+M6OC]O^((##]`0i)drT;-7X`=-H3[igUnPG-NZlo.#k@h#=Ork$m>a>$-?Tm$UV(?#P6YY#\"\r\n    \"'/###xe7q.73rI3*pP/$1>s9)W,JrM7SN]'/4C#v$U`0#V.[0>xQsH$fEmPMgY2u7Kh(G%siIfLSoS+MK2eTM$=5,M8p`A.;_R%#u[K#$x4AG8.kK/HSB==-'Ie/QTtG?-.*^N-4B/ZM\"\r\n    \"_3YlQC7(p7q)&](`6_c)$/*JL(L-^(]$wIM`dPtOdGA,U3:w2M-0<q-]L_?^)1vw'.,MRsqVr.L;aN&#/EgJ)PBc[-f>+WomX2u7lqM2iEumMTcsF?-aT=Z-97UEnXglEn1K-bnEO`gu\"\r\n    \"Ft(c%=;Am_Qs@jLooI&NX;]0#j4#F14;gl8-GQpgwhrq8'=l_f-b49'UOqkLu7-##oDY2L(te+Mch&gLYtJ,MEtJfLh'x'M=$CS-ZZ%P]8bZ>#S?YY#%Q&q'3^Fw&?D)UDNrocM3A76/\"\r\n    \"/oL?#h7gl85[qW/NDOk%16ij;+:1a'iNIdb-ou8.P*w,v5#EI$TWS>Pot-R*H'-SEpA:g)f+O$%%`kA#G=8RMmG1&O`>to8bC]T&$,n.LoO>29sp3dt-52U%VM#q7'DHpg+#Z9%H[K<L\"\r\n    \"%a2E-grWVM3@2=-k22tL]4$##6We'8UJCKE[d_=%wI;'6X-GsLX4j^SgJ$##R*w,vP3wK#iiW&#*h^D&R?jp7+/u&#(AP##XU8c$fSYW-J95_-Dp[g9wcO&#M-h1OcJlc-*vpw0xUX&#\"\r\n    \"OQFKNX@QI'IoPp7nb,QU//MQ&ZDkKP)X<WSVL(68uVl&#c'[0#(s1X&xm$Y%B7*K:eDA323j998GXbA#pwMs-jgD$9QISB-A_(aN4xoFM^@C58D0+Q+q3n0#3U1InDjF682-SjMXJK)(\"\r\n    \"h$hxua_K]ul92%'BOU&#BRRh-slg8KDlr:%L71Ka:.A;%YULjDPmL<LYs8i#XwJOYaKPKc1h:'9Ke,g)b),78=I39B;xiY$bgGw-&.Zi9InXDuYa%G*f2Bq7mn9^#p1vv%#(Wi-;/Z5h\"\r\n    \"o;#2:;%d&#x9v68C5g?ntX0X)pT`;%pB3q7mgGN)3%(P8nTd5L7GeA-GL@+%J3u2:(Yf>et`e;)f#Km8&+DC$I46>#Kr]]u-[=99tts1.qb#q72g1WJO81q+eN'03'eM>&1XxY-caEnO\"\r\n    \"j%2n8)),?ILR5^.Ibn<-X-Mq7[a82Lq:F&#ce+S9wsCK*x`569E8ew'He]h:sI[2LM$[guka3ZRd6:t%IG:;$%YiJ:Nq=?eAw;/:nnDq0(CYcMpG)qLN4$##&J<j$UpK<Q4a1]MupW^-\"\r\n    \"sj_$%[HK%'F####QRZJ::Y3EGl4'@%FkiAOg#p[##O`gukTfBHagL<LHw%q&OV0##F=6/:chIm0@eCP8X]:kFI%hl8hgO@RcBhS-@Qb$%+m=hPDLg*%K8ln(wcf3/'DW-$.lR?n[nCH-\"\r\n    \"eXOONTJlh:.RYF%3'p6sq:UIMA945&^HFS87@$EP2iG<-lCO$%c`uKGD3rC$x0BL8aFn--`ke%#HMP'vh1/R&O_J9'um,.<tx[@%wsJk&bUT2`0uMv7gg#qp/ij.L56'hl;.s5CUrxjO\"\r\n    \"M7-##.l+Au'A&O:-T72L]P`&=;ctp'XScX*rU.>-XTt,%OVU4)S1+R-#dg0/Nn?Ku1^0f$B*P:Rowwm-`0PKjYDDM'3]d39VZHEl4,.j']Pk-M.h^&:0FACm$maq-&sgw0t7/6(^xtk%\"\r\n    \"LuH88Fj-ekm>GA#_>568x6(OFRl-IZp`&b,_P'$M<Jnq79VsJW/mWS*PUiq76;]/NM_>hLbxfc$mj`,O;&%W2m`Zh:/)Uetw:aJ%]K9h:TcF]u_-Sj9,VK3M.*'&0D[Ca]J9gp8,kAW]\"\r\n    \"%(?A%R$f<->Zts'^kn=-^@c4%-pY6qI%J%1IGxfLU9CP8cbPlXv);C=b),<2mOvP8up,UVf3839acAWAW-W?#ao/^#%KYo8fRULNd2.>%m]UK:n%r$'sw]J;5pAoO_#2mO3n,'=H5(et\"\r\n    \"Hg*`+RLgv>=4U8guD$I%D:W>-r5V*%j*W:Kvej.Lp$<M-SGZ':+Q_k+uvOSLiEo(<aD/K<CCc`'Lx>'?;++O'>()jLR-^u68PHm8ZFWe+ej8h:9r6L*0//c&iH&R8pRbA#Kjm%upV1g:\"\r\n    \"a_#Ur7FuA#(tRh#.Y5K+@?3<-8m0$PEn;J:rh6?I6uG<-`wMU'ircp0LaE_OtlMb&1#6T.#FDKu#1Lw%u%+GM+X'e?YLfjM[VO0MbuFp7;>Q&#WIo)0@F%q7c#4XAXN-U&VB<HFF*qL(\"\r\n    \"$/V,;(kXZejWO`<[5?\\?ewY(*9=%wDc;,u<'9t3W-(H1th3+G]ucQ]kLs7df($/*JL]@*t7Bu_G3_7mp7<iaQjO@.kLg;x3B0lqp7Hf,^Ze7-##@/c58Mo(3;knp0%)A7?-W+eI'o8)b<\"\r\n    \"nKnw'Ho8C=Y>pqB>0ie&jhZ[?iLR@@_AvA-iQC(=ksRZRVp7`.=+NpBC%rh&3]R:8XDmE5^V8O(x<<aG/1N$#FX$0V5Y6x'aErI3I$7x%E`v<-BY,)%-?Psf*l?%C3.mM(=/M0:JxG'?\"\r\n    \"7WhH%o'a<-80g0NBxoO(GH<dM]n.+%q@jH?f.UsJ2Ggs&4<-e47&Kl+f//9@`b+?.TeN_&B8Ss?v;^Trk;f#YvJkl&w$]>-+k?'(<S:68tq*WoDfZu';mM?8X[ma8W%*`-=;D.(nc7/;\"\r\n    \")g:T1=^J$&BRV(-lTmNB6xqB[@0*o.erM*<SWF]u2=st-*(6v>^](H.aREZSi,#1:[IXaZFOm<-ui#qUq2$##Ri;u75OK#(RtaW-K-F`S+cF]uN`-KMQ%rP/Xri.LRcB##=YL3BgM/3M\"\r\n    \"D?@f&1'BW-)Ju<L25gl8uhVm1hL$##*8###'A3/LkKW+(^rWX?5W_8g)a(m&K8P>#bmmWCMkk&#TR`C,5d>g)F;t,4:@_l8G/5h4vUd%&%950:VXD'QdWoY-F$BtUwmfe$YqL'8(PWX(\"\r\n    \"P?^@Po3$##`MSs?DWBZ/S>+4%>fX,VWv/w'KD`LP5IbH;rTV>n3cEK8U#bX]l-/V+^lj3;vlMb&[5YQ8#pekX9JP3XUC72L,,?+Ni&co7ApnO*5NK,((W-i:$,kp'UDAO(G0Sq7MVjJs\"\r\n    \"bIu)'Z,*[>br5fX^:FPAWr-m2KgL<LUN098kTF&#lvo58=/vjDo;.;)Ka*hLR#/k=rKbxuV`>Q_nN6'8uTG&#1T5g)uLv:873UpTLgH+#FgpH'_o1780Ph8KmxQJ8#H72L4@768@Tm&Q\"\r\n    \"h4CB/5OvmA&,Q&QbUoi$a_%3M01H)4x7I^&KQVgtFnV+;[Pc>[m4k//,]1?#`VY[Jr*3&&slRfLiVZJ:]?=K3Sw=[$=uRB?3xk48@aeg<Z'<$#4H)6,>e0jT6'N#(q%.O=?2S]u*(m<-\"\r\n    \"V8J'(1)G][68hW$5'q[GC&5j`TE?m'esFGNRM)j,ffZ?-qx8;->g4t*:CIP/[Qap7/9'#(1sao7w-.qNUdkJ)tCF&#B^;xGvn2r9FEPFFFcL@.iFNkTve$m%#QvQS8U@)2Z+3K:AKM5i\"\r\n    \"sZ88+dKQ)W6>J%CL<KE>`.d*(B`-n8D9oK<Up]c$X$(,)M8Zt7/[rdkqTgl-0cuGMv'?>-XV1q['-5k'cAZ69e;D_?$ZPP&s^+7])$*$#@QYi9,5P&#9r+$%CE=68>K8r0=dSC%%(@p7\"\r\n    \".m7jilQ02'0-VWAg<a/''3u.=4L$Y)6k/K:_[3=&jvL<L0C/2'v:^;-DIBW,B4E68:kZ;%?8(Q8BH=kO65BW?xSG&#@uU,DS*,?.+(o(#1vCS8#CHF>TlGW'b)Tq7VT9q^*^$$.:&N@@\"\r\n    \"$&)WHtPm*5_rO0&e%K&#-30j(E4#'Zb.o/(Tpm$>K'f@[PvFl,hfINTNU6u'0pao7%XUp9]5.>%h`8_=VYbxuel.NTSsJfLacFu3B'lQSu/m6-Oqem8T+oE--$0a/k]uj9EwsG>%veR*\"\r\n    \"hv^BFpQj:K'#SJ,sB-'#](j.Lg92rTw-*n%@/;39rrJF,l#qV%OrtBeC6/,;qB3ebNW[?,Hqj2L.1NP&GjUR=1D8QaS3Up&@*9wP?+lo7b?@%'k4`p0Z$22%K3+iCZj?XJN4Nm&+YF]u\"\r\n    \"@-W$U%VEQ/,,>>#)D<h#`)h0:<Q6909ua+&VU%n2:cG3FJ-%@Bj-DgLr`Hw&HAKjKjseK</xKT*)B,N9X3]krc12t'pgTV(Lv-tL[xg_%=M_q7a^x?7Ubd>#%8cY#YZ?=,`Wdxu/ae&#\"\r\n    \"w6)R89tI#6@s'(6Bf7a&?S=^ZI_kS&ai`&=tE72L_D,;^R)7[$s<Eh#c&)q.MXI%#v9ROa5FZO%sF7q7Nwb&#ptUJ:aqJe$Sl68%.D###EC><?-aF&#RNQv>o8lKN%5/$(vdfq7+ebA#\"\r\n    \"u1p]ovUKW&Y%q]'>$1@-[xfn$7ZTp7mM,G,Ko7a&Gu%G[RMxJs[0MM%wci.LFDK)(<c`Q8N)jEIF*+?P2a8g%)$q]o2aH8C&<SibC/q,(e:v;-b#6[$NtDZ84Je2KNvB#$P5?tQ3nt(0\"\r\n    \"d=j.LQf./Ll33+(;q3L-w=8dX$#WF&uIJ@-bfI>%:_i2B5CsR8&9Z&#=mPEnm0f`<&c)QL5uJ#%u%lJj+D-r;BoF&#4DoS97h5g)E#o:&S4weDF,9^Hoe`h*L+_a*NrLW-1pG_&2UdB8\"\r\n    \"6e%B/:=>)N4xeW.*wft-;$'58-ESqr<b?UI(_%@[P46>#U`'6AQ]m&6/`Z>#S?YY#Vc;r7U2&326d=w&H####?TZ`*4?&.MK?LP8Vxg>$[QXc%QJv92.(Db*B)gb*BM9dM*hJMAo*c&#\"\r\n    \"b0v=Pjer]$gG&JXDf->'StvU7505l9$AFvgYRI^&<^b68?j#q9QX4SM'RO#&sL1IM.rJfLUAj221]d##DW=m83u5;'bYx,*Sl0hL(W;;$doB&O/TQ:(Z^xBdLjL<Lni;''X.`$#8+1GD\"\r\n    \":k$YUWsbn8ogh6rxZ2Z9]%nd+>V#*8U_72Lh+2Q8Cj0i:6hp&$C/:p(HK>T8Y[gHQ4`4)'$Ab(Nof%V'8hL&#<NEdtg(n'=S1A(Q1/I&4([%dM`,Iu'1:_hL>SfD07&6D<fp8dHM7/g+\"\r\n    \"tlPN9J*rKaPct&?'uBCem^jn%9_K)<,C5K3s=5g&GmJb*[SYq7K;TRLGCsM-$$;S%:Y@r7AK0pprpL<Lrh,q7e/%KWK:50I^+m'vi`3?%Zp+<-d+$L-Sv:@.o19n$s0&39;kn;S%BSq*\"\r\n    \"$3WoJSCLweV[aZ'MQIjO<7;X-X;&+dMLvu#^UsGEC9WEc[X(wI7#2.(F0jV*eZf<-Qv3J-c+J5AlrB#$p(H68LvEA'q3n0#m,[`*8Ft)FcYgEud]CWfm68,(aLA$@EFTgLXoBq/UPlp7\"\r\n    \":d[/;r_ix=:TF`S5H-b<LI&HY(K=h#)]Lk$K14lVfm:x$H<3^Ql<M`$OhapBnkup'D#L$Pb_`N*g]2e;X/Dtg,bsj&K#2[-:iYr'_wgH)NUIR8a1n#S?Yej'h8^58UbZd+^FKD*T@;6A\"\r\n    \"7aQC[K8d-(v6GI$x:T<&'Gp5Uf>@M.*J:;$-rv29'M]8qMv-tLp,'886iaC=Hb*YJoKJ,(j%K=H`K.v9HggqBIiZu'QvBT.#=)0ukruV&.)3=(^1`o*Pj4<-<aN((^7('#Z0wK#5GX@7\"\r\n    \"u][`*S^43933A4rl][`*O4CgLEl]v$1Q3AeF37dbXk,.)vj#x'd`;qgbQR%FW,2(?LO=s%Sc68%NP'##Aotl8x=BE#j1UD([3$M(]UI2LX3RpKN@;/#f'f/&_mt&F)XdF<9t4)Qa.*kT\"\r\n    \"LwQ'(TTB9.xH'>#MJ+gLq9-##@HuZPN0]u:h7.T..G:;$/Usj(T7`Q8tT72LnYl<-qx8;-HV7Q-&Xdx%1a,hC=0u+HlsV>nuIQL-5<N?)NBS)QN*_I,?&)2'IM%L3I)X((e/dl2&8'<M\"\r\n    \":^#M*Q+[T.Xri.LYS3v%fF`68h;b-X[/En'CR.q7E)p'/kle2HM,u;^%OKC-N+Ll%F9CF<Nf'^#t2L,;27W:0O@6##U6W7:$rJfLWHj$#)woqBefIZ.PK<b*t7ed;p*_m;4ExK#h@&]>\"\r\n    \"_>@kXQtMacfD.m-VAb8;IReM3$wf0''hra*so568'Ip&vRs849'MRYSp%:t:h5qSgwpEr$B>Q,;s(C#$)`svQuF$##-D,##,g68@2[T;.XSdN9Qe)rpt._K-#5wF)sP'##p#C0c%-Gb%\"\r\n    \"hd+<-j'Ai*x&&HMkT]C'OSl##5RG[JXaHN;d'uA#x._U;.`PU@(Z3dt4r152@:v,'R.Sj'w#0<-;kPI)FfJ&#AYJ&#//)>-k=m=*XnK$>=)72L]0I%>.G690a:$##<,);?;72#?x9+d;\"\r\n    \"^V'9;jY@;)br#q^YQpx:X#Te$Z^'=-=bGhLf:D6&bNwZ9-ZD#n^9HhLMr5G;']d&6'wYmTFmL<LD)F^%[tC'8;+9E#C$g%#5Y>q9wI>P(9mI[>kC-ekLC/R&CH+s'B;K-M6$EB%is00:\"\r\n    \"+A4[7xks.LrNk0&E)wILYF@2L'0Nb$+pv<(2.768/FrY&h$^3i&@+G%JT'<-,v`3;_)I9M^AE]CN?Cl2AZg+%4iTpT3<n-&%H%b<FDj2M<hH=&Eh<2Len$b*aTX=-8QxN)k11IM1c^j%\"\r\n    \"9s<L<NFSo)B?+<-(GxsF,^-Eh@$4dXhN$+#rxK8'je'D7k`e;)2pYwPA'_p9&@^18ml1^[@g4t*[JOa*[=Qp7(qJ_oOL^('7fB&Hq-:sf,sNj8xq^>$U4O]GKx'm9)b@p7YsvK3w^YR-\"\r\n    \"CdQ*:Ir<($u&)#(&?L9Rg3H)4fiEp^iI9O8KnTj,]H?D*r7'M;PwZ9K0E^k&-cpI;.p/6_vwoFMV<->#%Xi.LxVnrU(4&8/P+:hLSKj$#U%]49t'I:rgMi'FL@a:0Y-uA[39',(vbma*\"\r\n    \"hU%<-SRF`Tt:542R_VV$p@[p8DV[A,?1839FWdF<TddF<9Ah-6&9tWoDlh]&1SpGMq>Ti1O*H&#(AL8[_P%.M>v^-))qOT*F5Cq0`Ye%+$B6i:7@0IX<N+T+0MlMBPQ*Vj>SsD<U4JHY\"\r\n    \"8kD2)2fU/M#$e.)T4,_=8hLim[&);?UkK'-x?'(:siIfL<$pFM`i<?%W(mGDHM%>iWP,##P`%/L<eXi:@Z9C.7o=@(pXdAO/NLQ8lPl+HPOQa8wD8=^GlPa8TKI1CjhsCTSLJM'/Wl>-\"\r\n    \"S(qw%sf/@%#B6;/U7K]uZbi^Oc^2n<bhPmUkMw>%t<)'mEVE''n`WnJra$^TKvX5B>;_aSEK',(hwa0:i4G?.Bci.(X[?b*($,=-n<.Q%`(X=?+@Am*Js0&=3bh8K]mL<LoNs'6,'85`\"\r\n    \"0?t/'_U59@]ddF<#LdF<eWdF<OuN/45rY<-L@&#+fm>69=Lb,OcZV/);TTm8VI;?%OtJ<(b4mq7M6:u?KRdF<gR@2L=FNU-<b[(9c/ML3m;Z[$oF3g)GAWqpARc=<ROu7cL5l;-[A]%/\"\r\n    \"+fsd;l#SafT/f*W]0=O'$(Tb<[)*@e775R-:Yob%g*>l*:xP?Yb.5)%w_I?7uk5JC+FS(m#i'k.'a0i)9<7b'fs'59hq$*5Uhv##pi^8+hIEBF`nvo`;'l0.^S1<-wUK2/Coh58KKhLj\"\r\n    \"M=SO*rfO`+qC`W-On.=AJ56>>i2@2LH6A:&5q`?9I3@@'04&p2/LVa*T-4<-i3;M9UvZd+N7>b*eIwg:CC)c<>nO&#<IGe;__.thjZl<%w(Wk2xmp4Q@I#I9,DF]u7-P=.-_:YJ]aS@V\"\r\n    \"?6*C()dOp7:WL,b&3Rg/.cmM9&r^>$(>.Z-I&J(Q0Hd5Q%7Co-b`-c<N(6r@ip+AurK<m86QIth*#v;-OBqi+L7wDE-Ir8K['m+DDSLwK&/.?-V%U_%3:qKNu$_b*B-kp7NaD'QdWQPK\"\r\n    \"Yq[@>P)hI;*_F]u`Rb[.j8_Q/<&>uu+VsH$sM9TA%?)(vmJ80),P7E>)tjD%2L=-t#fK[%`v=Q8<FfNkgg^oIbah*#8/Qt$F&:K*-(N/'+1vMB,u()-a.VUU*#[e%gAAO(S>WlA2);Sa\"\r\n    \">gXm8YB`1d@K#n]76-a$U,mF<fX]idqd)<3,]J7JmW4`6]uks=4-72L(jEk+:bJ0M^q-8Dm_Z?0olP1C9Sa&H[d&c$ooQUj]Exd*3ZM@-WGW2%s',B-_M%>%Ul:#/'xoFM9QX-$.QN'>\"\r\n    \"[%$Z$uF6pA6Ki2O5:8w*vP1<-1`[G,)-m#>0`P&#eb#.3i)rtB61(o'$?X3B</R90;eZ]%Ncq;-Tl]#F>2Qft^ae_5tKL9MUe9b*sLEQ95C&`=G?@Mj=wh*'3E>=-<)Gt*Iw)'QG:`@I\"\r\n    \"wOf7&]1i'S01B+Ev/Nac#9S;=;YQpg_6U`*kVY39xK,[/6Aj7:'1Bm-_1EYfa1+o&o4hp7KN_Q(OlIo@S%;jVdn0'1<Vc52=u`3^o-n1'g4v58Hj&6_t7$##?M)c<$bgQ_'SY((-xkA#\"\r\n    \"Y(,p'H9rIVY-b,'%bCPF7.J<Up^,(dU1VY*5#WkTU>h19w,WQhLI)3S#f$2(eb,jr*b;3Vw]*7NH%$c4Vs,eD9>XW8?N]o+(*pgC%/72LV-u<Hp,3@e^9UB1J+ak9-TN/mhKPg+AJYd$\"\r\n    \"MlvAF_jCK*.O-^(63adMT->W%iewS8W6m2rtCpo'RS1R84=@paTKt)>=%&1[)*vp'u+x,VrwN;&]kuO9JDbg=pO$J*.jVe;u'm0dr9l,<*wMK*Oe=g8lV_KEBFkO'oU]^=[-792#ok,)\"\r\n    \"i]lR8qQ2oA8wcRCZ^7w/Njh;?.stX?Q1>S1q4Bn$)K1<-rGdO'$Wr.Lc.CG)$/*JL4tNR/,SVO3,aUw'DJN:)Ss;wGn9A32ijw%FL+Z0Fn.U9;reSq)bmI32U==5ALuG&#Vf1398/pVo\"\r\n    \"1*c-(aY168o<`JsSbk-,1N;$>0:OUas(3:8Z972LSfF8eb=c-;>SPw7.6hn3m`9^Xkn(r.qS[0;T%&Qc=+STRxX'q1BNk3&*eu2;&8q$&x>Q#Q7^Tf+6<(d%ZVmj2bDi%.3L2n+4W'$P\"\r\n    \"iDDG)g,r%+?,$@?uou5tSe2aN_AQU*<h`e-GI7)?OK2A.d7_c)?wQ5AS@DL3r#7fSkgl6-++D:'A,uq7SvlB$pcpH'q3n0#_%dY#xCpr-l<F0NR@-##FEV6NTF6##$l84N1w?AO>'IAO\"\r\n    \"URQ##V^Fv-XFbGM7Fl(N<3DhLGF%q.1rC$#:T__&Pi68%0xi_&[qFJ(77j_&JWoF.V735&T,[R*:xFR*K5>>#`bW-?4Ne_&6Ne_&6Ne_&n`kr-#GJcM6X;uM6X;uM(.a..^2TkL%oR(#\"\r\n    \";u.T%fAr%4tJ8&><1=GHZ_+m9/#H1F^R#SC#*N=BA9(D?v[UiFY>>^8p,KKF.W]L29uLkLlu/+4T<XoIB&hx=T1PcDaB&;HH+-AFr?(m9HZV)FKS8JCw;SD=6[^/DZUL`EUDf]GGlG&>\"\r\n    \"w$)F./^n3+rlo+DB;5sIYGNk+i1t-69Jg--0pao7Sm#K)pdHW&;LuDNH@H>#/X-TI(;P>#,Gc>#0Su>#4`1?#8lC?#<xU?#@.i?#D:%@#HF7@#LRI@#P_[@#Tkn@#Xw*A#]-=A#a9OA#\"\r\n    \"d<F&#*;G##.GY##2Sl##6`($#:l:$#>xL$#B.`$#F:r$#JF.%#NR@%#R_R%#Vke%#Zww%#_-4&#3^Rh%Sflr-k'MS.o?.5/sWel/wpEM0%3'/1)K^f1-d>G21&v(35>V`39V7A4=onx4\"\r\n    \"A1OY5EI0;6Ibgr6M$HS7Q<)58C5w,;WoA*#[%T*#`1g*#d=#+#hI5+#lUG+#pbY+#tnl+#x$),#&1;,#*=M,#.I`,#2Ur,#6b.-#;w[H#iQtA#m^0B#qjBB#uvTB##-hB#'9$C#+E6C#\"\r\n    \"/QHC#3^ZC#7jmC#;v)D#?,<D#C8ND#GDaD#KPsD#O]/E#g1A5#KA*1#gC17#MGd;#8(02#L-d3#rWM4#Hga1#,<w0#T.j<#O#'2#CYN1#qa^:#_4m3#o@/=#eG8=#t8J5#`+78#4uI-#\"\r\n    \"m3B2#SB[8#Q0@8#i[*9#iOn8#1Nm;#^sN9#qh<9#:=x-#P;K2#$%X9#bC+.#Rg;<#mN=.#MTF.#RZO.#2?)4#Y#(/#[)1/#b;L/#dAU/#0Sv;#lY$0#n`-0#sf60#(F24#wrH0#%/e0#\"\r\n    \"TmD<#%JSMFove:CTBEXI:<eh2g)B,3h2^G3i;#d3jD>)4kMYD4lVu`4m`:&5niUA5@(A5BA1]PBB:xlBCC=2CDLXMCEUtiCf&0g2'tN?PGT4CPGT4CPGT4CPGT4CPGT4CPGT4CPGT4CP\"\r\n    \"GT4CPGT4CPGT4CPGT4CPGT4CPGT4CP-qekC`.9kEg^+F$kwViFJTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5o,^<-28ZI'O?;xp\"\r\n    \"O?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xp;7q-#lLYI:xvD=#\";\r\n\r\nstatic const char* GetDefaultCompressedFontDataTTFBase85()\r\n{\r\n    return proggy_clean_ttf_compressed_data_base85;\r\n}\r\n\r\n#endif // #ifndef IMGUI_DISABLE\r\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/imgui/imgui_internal.h",
    "content": "// dear imgui, v1.87 WIP\r\n// (internal structures/api)\r\n\r\n// You may use this file to debug, understand or extend ImGui features but we don't provide any guarantee of forward compatibility!\r\n// Set:\r\n//   #define IMGUI_DEFINE_MATH_OPERATORS\r\n// To implement maths operators for ImVec2 (disabled by default to not collide with using IM_VEC2_CLASS_EXTRA along with your own math types+operators)\r\n\r\n/*\r\n\r\nIndex of this file:\r\n\r\n// [SECTION] Header mess\r\n// [SECTION] Forward declarations\r\n// [SECTION] Context pointer\r\n// [SECTION] STB libraries includes\r\n// [SECTION] Macros\r\n// [SECTION] Generic helpers\r\n// [SECTION] ImDrawList support\r\n// [SECTION] Widgets support: flags, enums, data structures\r\n// [SECTION] Inputs support\r\n// [SECTION] Clipper support\r\n// [SECTION] Navigation support\r\n// [SECTION] Columns support\r\n// [SECTION] Multi-select support\r\n// [SECTION] Docking support\r\n// [SECTION] Viewport support\r\n// [SECTION] Settings support\r\n// [SECTION] Metrics, Debug tools\r\n// [SECTION] Generic context hooks\r\n// [SECTION] ImGuiContext (main imgui context)\r\n// [SECTION] ImGuiWindowTempData, ImGuiWindow\r\n// [SECTION] Tab bar, Tab item support\r\n// [SECTION] Table support\r\n// [SECTION] ImGui internal API\r\n// [SECTION] ImFontAtlas internal API\r\n// [SECTION] Test Engine specific hooks (imgui_test_engine)\r\n\r\n*/\r\n\r\n#pragma once\r\n#ifndef IMGUI_DISABLE\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Header mess\r\n//-----------------------------------------------------------------------------\r\n\r\n#ifndef IMGUI_VERSION\r\n#include \"imgui.h\"\r\n#endif\r\n\r\n#include <stdio.h>      // FILE*, sscanf\r\n#include <stdlib.h>     // NULL, malloc, free, qsort, atoi, atof\r\n#include <math.h>       // sqrtf, fabsf, fmodf, powf, floorf, ceilf, cosf, sinf\r\n#include <limits.h>     // INT_MIN, INT_MAX\r\n\r\n// Enable SSE intrinsics if available\r\n#if (defined __SSE__ || defined __x86_64__ || defined _M_X64) && !defined(IMGUI_DISABLE_SSE)\r\n#define IMGUI_ENABLE_SSE\r\n#include <immintrin.h>\r\n#endif\r\n\r\n// Visual Studio warnings\r\n#ifdef _MSC_VER\r\n#pragma warning (push)\r\n#pragma warning (disable: 4251)     // class 'xxx' needs to have dll-interface to be used by clients of struct 'xxx' // when IMGUI_API is set to__declspec(dllexport)\r\n#pragma warning (disable: 26812)    // The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3). [MSVC Static Analyzer)\r\n#pragma warning (disable: 26495)    // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6).\r\n#if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later\r\n#pragma warning (disable: 5054)     // operator '|': deprecated between enumerations of different types\r\n#endif\r\n#endif\r\n\r\n// Clang/GCC warnings with -Weverything\r\n#if defined(__clang__)\r\n#pragma clang diagnostic push\r\n#if __has_warning(\"-Wunknown-warning-option\")\r\n#pragma clang diagnostic ignored \"-Wunknown-warning-option\"         // warning: unknown warning group 'xxx'\r\n#endif\r\n#pragma clang diagnostic ignored \"-Wunknown-pragmas\"                // warning: unknown warning group 'xxx'\r\n#pragma clang diagnostic ignored \"-Wfloat-equal\"                    // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants ok, for ImFloorSigned()\r\n#pragma clang diagnostic ignored \"-Wunused-function\"                // for stb_textedit.h\r\n#pragma clang diagnostic ignored \"-Wmissing-prototypes\"             // for stb_textedit.h\r\n#pragma clang diagnostic ignored \"-Wold-style-cast\"\r\n#pragma clang diagnostic ignored \"-Wzero-as-null-pointer-constant\"\r\n#pragma clang diagnostic ignored \"-Wdouble-promotion\"\r\n#pragma clang diagnostic ignored \"-Wimplicit-int-float-conversion\"  // warning: implicit conversion from 'xxx' to 'float' may lose precision\r\n#pragma clang diagnostic ignored \"-Wmissing-noreturn\"               // warning: function 'xxx' could be declared with attribute 'noreturn'\r\n#elif defined(__GNUC__)\r\n#pragma GCC diagnostic push\r\n#pragma GCC diagnostic ignored \"-Wpragmas\"              // warning: unknown option after '#pragma GCC diagnostic' kind\r\n#pragma GCC diagnostic ignored \"-Wclass-memaccess\"      // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead\r\n#endif\r\n\r\n// Legacy defines\r\n#ifdef IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS            // Renamed in 1.74\r\n#error Use IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS\r\n#endif\r\n#ifdef IMGUI_DISABLE_MATH_FUNCTIONS                     // Renamed in 1.74\r\n#error Use IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS\r\n#endif\r\n\r\n// Enable stb_truetype by default unless FreeType is enabled.\r\n// You can compile with both by defining both IMGUI_ENABLE_FREETYPE and IMGUI_ENABLE_STB_TRUETYPE together.\r\n#ifndef IMGUI_ENABLE_FREETYPE\r\n#define IMGUI_ENABLE_STB_TRUETYPE\r\n#endif\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Forward declarations\r\n//-----------------------------------------------------------------------------\r\n\r\nstruct ImBitVector;                 // Store 1-bit per value\r\nstruct ImRect;                      // An axis-aligned rectangle (2 points)\r\nstruct ImDrawDataBuilder;           // Helper to build a ImDrawData instance\r\nstruct ImDrawListSharedData;        // Data shared between all ImDrawList instances\r\nstruct ImGuiColorMod;               // Stacked color modifier, backup of modified data so we can restore it\r\nstruct ImGuiContext;                // Main Dear ImGui context\r\nstruct ImGuiContextHook;            // Hook for extensions like ImGuiTestEngine\r\nstruct ImGuiDataTypeInfo;           // Type information associated to a ImGuiDataType enum\r\nstruct ImGuiGroupData;              // Stacked storage data for BeginGroup()/EndGroup()\r\nstruct ImGuiInputTextState;         // Internal state of the currently focused/edited text input box\r\nstruct ImGuiLastItemData;           // Status storage for last submitted items\r\nstruct ImGuiMenuColumns;            // Simple column measurement, currently used for MenuItem() only\r\nstruct ImGuiNavItemData;            // Result of a gamepad/keyboard directional navigation move query result\r\nstruct ImGuiMetricsConfig;          // Storage for ShowMetricsWindow() and DebugNodeXXX() functions\r\nstruct ImGuiNextWindowData;         // Storage for SetNextWindow** functions\r\nstruct ImGuiNextItemData;           // Storage for SetNextItem** functions\r\nstruct ImGuiOldColumnData;          // Storage data for a single column for legacy Columns() api\r\nstruct ImGuiOldColumns;             // Storage data for a columns set for legacy Columns() api\r\nstruct ImGuiPopupData;              // Storage for current popup stack\r\nstruct ImGuiSettingsHandler;        // Storage for one type registered in the .ini file\r\nstruct ImGuiStackSizes;             // Storage of stack sizes for debugging/asserting\r\nstruct ImGuiStyleMod;               // Stacked style modifier, backup of modified data so we can restore it\r\nstruct ImGuiTabBar;                 // Storage for a tab bar\r\nstruct ImGuiTabItem;                // Storage for a tab item (within a tab bar)\r\nstruct ImGuiTable;                  // Storage for a table\r\nstruct ImGuiTableColumn;            // Storage for one column of a table\r\nstruct ImGuiTableTempData;          // Temporary storage for one table (one per table in the stack), shared between tables.\r\nstruct ImGuiTableSettings;          // Storage for a table .ini settings\r\nstruct ImGuiTableColumnsSettings;   // Storage for a column .ini settings\r\nstruct ImGuiWindow;                 // Storage for one window\r\nstruct ImGuiWindowTempData;         // Temporary storage for one window (that's the data which in theory we could ditch at the end of the frame, in practice we currently keep it for each window)\r\nstruct ImGuiWindowSettings;         // Storage for a window .ini settings (we keep one of those even if the actual window wasn't instanced during this session)\r\n\r\n// Use your programming IDE \"Go to definition\" facility on the names of the center columns to find the actual flags/enum lists.\r\ntypedef int ImGuiLayoutType;            // -> enum ImGuiLayoutType_         // Enum: Horizontal or vertical\r\ntypedef int ImGuiActivateFlags;         // -> enum ImGuiActivateFlags_      // Flags: for navigation/focus function (will be for ActivateItem() later)\r\ntypedef int ImGuiItemFlags;             // -> enum ImGuiItemFlags_          // Flags: for PushItemFlag()\r\ntypedef int ImGuiItemStatusFlags;       // -> enum ImGuiItemStatusFlags_    // Flags: for DC.LastItemStatusFlags\r\ntypedef int ImGuiOldColumnFlags;        // -> enum ImGuiOldColumnFlags_     // Flags: for BeginColumns()\r\ntypedef int ImGuiNavHighlightFlags;     // -> enum ImGuiNavHighlightFlags_  // Flags: for RenderNavHighlight()\r\ntypedef int ImGuiNavDirSourceFlags;     // -> enum ImGuiNavDirSourceFlags_  // Flags: for GetNavInputAmount2d()\r\ntypedef int ImGuiNavMoveFlags;          // -> enum ImGuiNavMoveFlags_       // Flags: for navigation requests\r\ntypedef int ImGuiNextItemDataFlags;     // -> enum ImGuiNextItemDataFlags_  // Flags: for SetNextItemXXX() functions\r\ntypedef int ImGuiNextWindowDataFlags;   // -> enum ImGuiNextWindowDataFlags_// Flags: for SetNextWindowXXX() functions\r\ntypedef int ImGuiScrollFlags;           // -> enum ImGuiScrollFlags_        // Flags: for ScrollToItem() and navigation requests\r\ntypedef int ImGuiSeparatorFlags;        // -> enum ImGuiSeparatorFlags_     // Flags: for SeparatorEx()\r\ntypedef int ImGuiTextFlags;             // -> enum ImGuiTextFlags_          // Flags: for TextEx()\r\ntypedef int ImGuiTooltipFlags;          // -> enum ImGuiTooltipFlags_       // Flags: for BeginTooltipEx()\r\n\r\ntypedef void (*ImGuiErrorLogCallback)(void* user_data, const char* fmt, ...);\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Context pointer\r\n// See implementation of this variable in imgui.cpp for comments and details.\r\n//-----------------------------------------------------------------------------\r\n\r\n#ifndef GImGui\r\nextern IMGUI_API ImGuiContext* GImGui;  // Current implicit context pointer\r\n#endif\r\n\r\n//-------------------------------------------------------------------------\r\n// [SECTION] STB libraries includes\r\n//-------------------------------------------------------------------------\r\n\r\nnamespace ImStb\r\n{\r\n\r\n#undef STB_TEXTEDIT_STRING\r\n#undef STB_TEXTEDIT_CHARTYPE\r\n#define STB_TEXTEDIT_STRING             ImGuiInputTextState\r\n#define STB_TEXTEDIT_CHARTYPE           ImWchar\r\n#define STB_TEXTEDIT_GETWIDTH_NEWLINE   (-1.0f)\r\n#define STB_TEXTEDIT_UNDOSTATECOUNT     99\r\n#define STB_TEXTEDIT_UNDOCHARCOUNT      999\r\n#include \"imstb_textedit.h\"\r\n\r\n} // namespace ImStb\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Macros\r\n//-----------------------------------------------------------------------------\r\n\r\n// Debug Logging\r\n#ifndef IMGUI_DEBUG_LOG\r\n#define IMGUI_DEBUG_LOG(_FMT,...)       printf(\"[%05d] \" _FMT, GImGui->FrameCount, __VA_ARGS__)\r\n#endif\r\n\r\n// Debug Logging for selected systems. Remove the '((void)0) //' to enable.\r\n//#define IMGUI_DEBUG_LOG_POPUP         IMGUI_DEBUG_LOG // Enable log\r\n//#define IMGUI_DEBUG_LOG_NAV           IMGUI_DEBUG_LOG // Enable log\r\n//#define IMGUI_DEBUG_LOG_IO            IMGUI_DEBUG_LOG // Enable log\r\n#define IMGUI_DEBUG_LOG_POPUP(...)      ((void)0)       // Disable log\r\n#define IMGUI_DEBUG_LOG_NAV(...)        ((void)0)       // Disable log\r\n#define IMGUI_DEBUG_LOG_IO(...)         ((void)0)       // Disable log\r\n\r\n// Static Asserts\r\n#define IM_STATIC_ASSERT(_COND)         static_assert(_COND, \"\")\r\n\r\n// \"Paranoid\" Debug Asserts are meant to only be enabled during specific debugging/work, otherwise would slow down the code too much.\r\n// We currently don't have many of those so the effect is currently negligible, but onward intent to add more aggressive ones in the code.\r\n//#define IMGUI_DEBUG_PARANOID\r\n#ifdef IMGUI_DEBUG_PARANOID\r\n#define IM_ASSERT_PARANOID(_EXPR)       IM_ASSERT(_EXPR)\r\n#else\r\n#define IM_ASSERT_PARANOID(_EXPR)\r\n#endif\r\n\r\n// Error handling\r\n// Down the line in some frameworks/languages we would like to have a way to redirect those to the programmer and recover from more faults.\r\n#ifndef IM_ASSERT_USER_ERROR\r\n#define IM_ASSERT_USER_ERROR(_EXP,_MSG) IM_ASSERT((_EXP) && _MSG)   // Recoverable User Error\r\n#endif\r\n\r\n// Misc Macros\r\n#define IM_PI                           3.14159265358979323846f\r\n#ifdef _WIN32\r\n#define IM_NEWLINE                      \"\\r\\n\"   // Play it nice with Windows users (Update: since 2018-05, Notepad finally appears to support Unix-style carriage returns!)\r\n#else\r\n#define IM_NEWLINE                      \"\\n\"\r\n#endif\r\n#define IM_TABSIZE                      (4)\r\n#define IM_MEMALIGN(_OFF,_ALIGN)        (((_OFF) + (_ALIGN - 1)) & ~(_ALIGN - 1))               // Memory align e.g. IM_ALIGN(0,4)=0, IM_ALIGN(1,4)=4, IM_ALIGN(4,4)=4, IM_ALIGN(5,4)=8\r\n#define IM_F32_TO_INT8_UNBOUND(_VAL)    ((int)((_VAL) * 255.0f + ((_VAL)>=0 ? 0.5f : -0.5f)))   // Unsaturated, for display purpose\r\n#define IM_F32_TO_INT8_SAT(_VAL)        ((int)(ImSaturate(_VAL) * 255.0f + 0.5f))               // Saturated, always output 0..255\r\n#define IM_FLOOR(_VAL)                  ((float)(int)(_VAL))                                    // ImFloor() is not inlined in MSVC debug builds\r\n#define IM_ROUND(_VAL)                  ((float)(int)((_VAL) + 0.5f))                           //\r\n\r\n// Enforce cdecl calling convention for functions called by the standard library, in case compilation settings changed the default to e.g. __vectorcall\r\n#ifdef _MSC_VER\r\n#define IMGUI_CDECL __cdecl\r\n#else\r\n#define IMGUI_CDECL\r\n#endif\r\n\r\n// Warnings\r\n#if defined(_MSC_VER) && !defined(__clang__)\r\n#define IM_MSVC_WARNING_SUPPRESS(XXXX)  __pragma(warning(suppress: XXXX))\r\n#else\r\n#define IM_MSVC_WARNING_SUPPRESS(XXXX)\r\n#endif\r\n\r\n// Debug Tools\r\n// Use 'Metrics/Debugger->Tools->Item Picker' to break into the call-stack of a specific item.\r\n// This will call IM_DEBUG_BREAK() which you may redefine yourself. See https://github.com/scottt/debugbreak for more reference.\r\n#ifndef IM_DEBUG_BREAK\r\n#if defined (_MSC_VER)\r\n#define IM_DEBUG_BREAK()    __debugbreak()\r\n#elif defined(__clang__)\r\n#define IM_DEBUG_BREAK()    __builtin_debugtrap()\r\n#elif defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))\r\n#define IM_DEBUG_BREAK()    __asm__ volatile(\"int $0x03\")\r\n#elif defined(__GNUC__) && defined(__thumb__)\r\n#define IM_DEBUG_BREAK()    __asm__ volatile(\".inst 0xde01\")\r\n#elif defined(__GNUC__) && defined(__arm__) && !defined(__thumb__)\r\n#define IM_DEBUG_BREAK()    __asm__ volatile(\".inst 0xe7f001f0\");\r\n#else\r\n#define IM_DEBUG_BREAK()    IM_ASSERT(0)    // It is expected that you define IM_DEBUG_BREAK() into something that will break nicely in a debugger!\r\n#endif\r\n#endif // #ifndef IM_DEBUG_BREAK\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Generic helpers\r\n// Note that the ImXXX helpers functions are lower-level than ImGui functions.\r\n// ImGui functions or the ImGui context are never called/used from other ImXXX functions.\r\n//-----------------------------------------------------------------------------\r\n// - Helpers: Hashing\r\n// - Helpers: Sorting\r\n// - Helpers: Bit manipulation\r\n// - Helpers: String, Formatting\r\n// - Helpers: UTF-8 <> wchar conversions\r\n// - Helpers: ImVec2/ImVec4 operators\r\n// - Helpers: Maths\r\n// - Helpers: Geometry\r\n// - Helper: ImVec1\r\n// - Helper: ImVec2ih\r\n// - Helper: ImRect\r\n// - Helper: ImBitArray\r\n// - Helper: ImBitVector\r\n// - Helper: ImSpan<>, ImSpanAllocator<>\r\n// - Helper: ImPool<>\r\n// - Helper: ImChunkStream<>\r\n//-----------------------------------------------------------------------------\r\n\r\n// Helpers: Hashing\r\nIMGUI_API ImGuiID       ImHashData(const void* data, size_t data_size, ImU32 seed = 0);\r\nIMGUI_API ImGuiID       ImHashStr(const char* data, size_t data_size = 0, ImU32 seed = 0);\r\n#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS\r\nstatic inline ImGuiID   ImHash(const void* data, int size, ImU32 seed = 0) { return size ? ImHashData(data, (size_t)size, seed) : ImHashStr((const char*)data, 0, seed); } // [moved to ImHashStr/ImHashData in 1.68]\r\n#endif\r\n\r\n// Helpers: Sorting\r\n#ifndef ImQsort\r\nstatic inline void      ImQsort(void* base, size_t count, size_t size_of_element, int(IMGUI_CDECL *compare_func)(void const*, void const*)) { if (count > 1) qsort(base, count, size_of_element, compare_func); }\r\n#endif\r\n\r\n// Helpers: Color Blending\r\nIMGUI_API ImU32         ImAlphaBlendColors(ImU32 col_a, ImU32 col_b);\r\n\r\n// Helpers: Bit manipulation\r\nstatic inline bool      ImIsPowerOfTwo(int v)           { return v != 0 && (v & (v - 1)) == 0; }\r\nstatic inline bool      ImIsPowerOfTwo(ImU64 v)         { return v != 0 && (v & (v - 1)) == 0; }\r\nstatic inline int       ImUpperPowerOfTwo(int v)        { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; }\r\n\r\n// Helpers: String, Formatting\r\nIMGUI_API int           ImStricmp(const char* str1, const char* str2);\r\nIMGUI_API int           ImStrnicmp(const char* str1, const char* str2, size_t count);\r\nIMGUI_API void          ImStrncpy(char* dst, const char* src, size_t count);\r\nIMGUI_API char*         ImStrdup(const char* str);\r\nIMGUI_API char*         ImStrdupcpy(char* dst, size_t* p_dst_size, const char* str);\r\nIMGUI_API const char*   ImStrchrRange(const char* str_begin, const char* str_end, char c);\r\nIMGUI_API int           ImStrlenW(const ImWchar* str);\r\nIMGUI_API const char*   ImStreolRange(const char* str, const char* str_end);                // End end-of-line\r\nIMGUI_API const ImWchar*ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin);   // Find beginning-of-line\r\nIMGUI_API const char*   ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end);\r\nIMGUI_API void          ImStrTrimBlanks(char* str);\r\nIMGUI_API const char*   ImStrSkipBlank(const char* str);\r\nIMGUI_API int           ImFormatString(char* buf, size_t buf_size, const char* fmt, ...) IM_FMTARGS(3);\r\nIMGUI_API int           ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args) IM_FMTLIST(3);\r\nIMGUI_API const char*   ImParseFormatFindStart(const char* format);\r\nIMGUI_API const char*   ImParseFormatFindEnd(const char* format);\r\nIMGUI_API const char*   ImParseFormatTrimDecorations(const char* format, char* buf, size_t buf_size);\r\nIMGUI_API int           ImParseFormatPrecision(const char* format, int default_value);\r\nstatic inline bool      ImCharIsBlankA(char c)          { return c == ' ' || c == '\\t'; }\r\nstatic inline bool      ImCharIsBlankW(unsigned int c)  { return c == ' ' || c == '\\t' || c == 0x3000; }\r\n\r\n// Helpers: UTF-8 <> wchar conversions\r\nIMGUI_API const char*   ImTextCharToUtf8(char out_buf[5], unsigned int c);                                                      // return out_buf\r\nIMGUI_API int           ImTextStrToUtf8(char* out_buf, int out_buf_size, const ImWchar* in_text, const ImWchar* in_text_end);   // return output UTF-8 bytes count\r\nIMGUI_API int           ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end);               // read one character. return input UTF-8 bytes count\r\nIMGUI_API int           ImTextStrFromUtf8(ImWchar* out_buf, int out_buf_size, const char* in_text, const char* in_text_end, const char** in_remaining = NULL);   // return input UTF-8 bytes count\r\nIMGUI_API int           ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end);                                 // return number of UTF-8 code-points (NOT bytes count)\r\nIMGUI_API int           ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end);                             // return number of bytes to express one char in UTF-8\r\nIMGUI_API int           ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end);                        // return number of bytes to express string in UTF-8\r\n\r\n// Helpers: ImVec2/ImVec4 operators\r\n// We are keeping those disabled by default so they don't leak in user space, to allow user enabling implicit cast operators between ImVec2 and their own types (using IM_VEC2_CLASS_EXTRA etc.)\r\n// We unfortunately don't have a unary- operator for ImVec2 because this would needs to be defined inside the class itself.\r\n#ifdef IMGUI_DEFINE_MATH_OPERATORS\r\nIM_MSVC_RUNTIME_CHECKS_OFF\r\nstatic inline ImVec2 operator*(const ImVec2& lhs, const float rhs)              { return ImVec2(lhs.x * rhs, lhs.y * rhs); }\r\nstatic inline ImVec2 operator/(const ImVec2& lhs, const float rhs)              { return ImVec2(lhs.x / rhs, lhs.y / rhs); }\r\nstatic inline ImVec2 operator+(const ImVec2& lhs, const ImVec2& rhs)            { return ImVec2(lhs.x + rhs.x, lhs.y + rhs.y); }\r\nstatic inline ImVec2 operator-(const ImVec2& lhs, const ImVec2& rhs)            { return ImVec2(lhs.x - rhs.x, lhs.y - rhs.y); }\r\nstatic inline ImVec2 operator*(const ImVec2& lhs, const ImVec2& rhs)            { return ImVec2(lhs.x * rhs.x, lhs.y * rhs.y); }\r\nstatic inline ImVec2 operator/(const ImVec2& lhs, const ImVec2& rhs)            { return ImVec2(lhs.x / rhs.x, lhs.y / rhs.y); }\r\nstatic inline ImVec2& operator*=(ImVec2& lhs, const float rhs)                  { lhs.x *= rhs; lhs.y *= rhs; return lhs; }\r\nstatic inline ImVec2& operator/=(ImVec2& lhs, const float rhs)                  { lhs.x /= rhs; lhs.y /= rhs; return lhs; }\r\nstatic inline ImVec2& operator+=(ImVec2& lhs, const ImVec2& rhs)                { lhs.x += rhs.x; lhs.y += rhs.y; return lhs; }\r\nstatic inline ImVec2& operator-=(ImVec2& lhs, const ImVec2& rhs)                { lhs.x -= rhs.x; lhs.y -= rhs.y; return lhs; }\r\nstatic inline ImVec2& operator*=(ImVec2& lhs, const ImVec2& rhs)                { lhs.x *= rhs.x; lhs.y *= rhs.y; return lhs; }\r\nstatic inline ImVec2& operator/=(ImVec2& lhs, const ImVec2& rhs)                { lhs.x /= rhs.x; lhs.y /= rhs.y; return lhs; }\r\nstatic inline ImVec4 operator+(const ImVec4& lhs, const ImVec4& rhs)            { return ImVec4(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z, lhs.w + rhs.w); }\r\nstatic inline ImVec4 operator-(const ImVec4& lhs, const ImVec4& rhs)            { return ImVec4(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z, lhs.w - rhs.w); }\r\nstatic inline ImVec4 operator*(const ImVec4& lhs, const ImVec4& rhs)            { return ImVec4(lhs.x * rhs.x, lhs.y * rhs.y, lhs.z * rhs.z, lhs.w * rhs.w); }\r\nIM_MSVC_RUNTIME_CHECKS_RESTORE\r\n#endif\r\n\r\n// Helpers: File System\r\n#ifdef IMGUI_DISABLE_FILE_FUNCTIONS\r\n#define IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS\r\ntypedef void* ImFileHandle;\r\nstatic inline ImFileHandle  ImFileOpen(const char*, const char*)                    { return NULL; }\r\nstatic inline bool          ImFileClose(ImFileHandle)                               { return false; }\r\nstatic inline ImU64         ImFileGetSize(ImFileHandle)                             { return (ImU64)-1; }\r\nstatic inline ImU64         ImFileRead(void*, ImU64, ImU64, ImFileHandle)           { return 0; }\r\nstatic inline ImU64         ImFileWrite(const void*, ImU64, ImU64, ImFileHandle)    { return 0; }\r\n#endif\r\n#ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS\r\ntypedef FILE* ImFileHandle;\r\nIMGUI_API ImFileHandle      ImFileOpen(const char* filename, const char* mode);\r\nIMGUI_API bool              ImFileClose(ImFileHandle file);\r\nIMGUI_API ImU64             ImFileGetSize(ImFileHandle file);\r\nIMGUI_API ImU64             ImFileRead(void* data, ImU64 size, ImU64 count, ImFileHandle file);\r\nIMGUI_API ImU64             ImFileWrite(const void* data, ImU64 size, ImU64 count, ImFileHandle file);\r\n#else\r\n#define IMGUI_DISABLE_TTY_FUNCTIONS // Can't use stdout, fflush if we are not using default file functions\r\n#endif\r\nIMGUI_API void*             ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size = NULL, int padding_bytes = 0);\r\n\r\n// Helpers: Maths\r\nIM_MSVC_RUNTIME_CHECKS_OFF\r\n// - Wrapper for standard libs functions. (Note that imgui_demo.cpp does _not_ use them to keep the code easy to copy)\r\n#ifndef IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS\r\n#define ImFabs(X)           fabsf(X)\r\n#define ImSqrt(X)           sqrtf(X)\r\n#define ImFmod(X, Y)        fmodf((X), (Y))\r\n#define ImCos(X)            cosf(X)\r\n#define ImSin(X)            sinf(X)\r\n#define ImAcos(X)           acosf(X)\r\n#define ImAtan2(Y, X)       atan2f((Y), (X))\r\n#define ImAtof(STR)         atof(STR)\r\n//#define ImFloorStd(X)     floorf(X)           // We use our own, see ImFloor() and ImFloorSigned()\r\n#define ImCeil(X)           ceilf(X)\r\nstatic inline float  ImPow(float x, float y)    { return powf(x, y); }          // DragBehaviorT/SliderBehaviorT uses ImPow with either float/double and need the precision\r\nstatic inline double ImPow(double x, double y)  { return pow(x, y); }\r\nstatic inline float  ImLog(float x)             { return logf(x); }             // DragBehaviorT/SliderBehaviorT uses ImLog with either float/double and need the precision\r\nstatic inline double ImLog(double x)            { return log(x); }\r\nstatic inline int    ImAbs(int x)               { return x < 0 ? -x : x; }\r\nstatic inline float  ImAbs(float x)             { return fabsf(x); }\r\nstatic inline double ImAbs(double x)            { return fabs(x); }\r\nstatic inline float  ImSign(float x)            { return (x < 0.0f) ? -1.0f : (x > 0.0f) ? 1.0f : 0.0f; } // Sign operator - returns -1, 0 or 1 based on sign of argument\r\nstatic inline double ImSign(double x)           { return (x < 0.0) ? -1.0 : (x > 0.0) ? 1.0 : 0.0; }\r\n#ifdef IMGUI_ENABLE_SSE\r\nstatic inline float  ImRsqrt(float x)           { return _mm_cvtss_f32(_mm_rsqrt_ss(_mm_set_ss(x))); }\r\n#else\r\nstatic inline float  ImRsqrt(float x)           { return 1.0f / sqrtf(x); }\r\n#endif\r\nstatic inline double ImRsqrt(double x)          { return 1.0 / sqrt(x); }\r\n#endif\r\n// - ImMin/ImMax/ImClamp/ImLerp/ImSwap are used by widgets which support variety of types: signed/unsigned int/long long float/double\r\n// (Exceptionally using templates here but we could also redefine them for those types)\r\ntemplate<typename T> static inline T ImMin(T lhs, T rhs)                        { return lhs < rhs ? lhs : rhs; }\r\ntemplate<typename T> static inline T ImMax(T lhs, T rhs)                        { return lhs >= rhs ? lhs : rhs; }\r\ntemplate<typename T> static inline T ImClamp(T v, T mn, T mx)                   { return (v < mn) ? mn : (v > mx) ? mx : v; }\r\ntemplate<typename T> static inline T ImLerp(T a, T b, float t)                  { return (T)(a + (b - a) * t); }\r\ntemplate<typename T> static inline void ImSwap(T& a, T& b)                      { T tmp = a; a = b; b = tmp; }\r\ntemplate<typename T> static inline T ImAddClampOverflow(T a, T b, T mn, T mx)   { if (b < 0 && (a < mn - b)) return mn; if (b > 0 && (a > mx - b)) return mx; return a + b; }\r\ntemplate<typename T> static inline T ImSubClampOverflow(T a, T b, T mn, T mx)   { if (b > 0 && (a < mn + b)) return mn; if (b < 0 && (a > mx + b)) return mx; return a - b; }\r\n// - Misc maths helpers\r\nstatic inline ImVec2 ImMin(const ImVec2& lhs, const ImVec2& rhs)                { return ImVec2(lhs.x < rhs.x ? lhs.x : rhs.x, lhs.y < rhs.y ? lhs.y : rhs.y); }\r\nstatic inline ImVec2 ImMax(const ImVec2& lhs, const ImVec2& rhs)                { return ImVec2(lhs.x >= rhs.x ? lhs.x : rhs.x, lhs.y >= rhs.y ? lhs.y : rhs.y); }\r\nstatic inline ImVec2 ImClamp(const ImVec2& v, const ImVec2& mn, ImVec2 mx)      { return ImVec2((v.x < mn.x) ? mn.x : (v.x > mx.x) ? mx.x : v.x, (v.y < mn.y) ? mn.y : (v.y > mx.y) ? mx.y : v.y); }\r\nstatic inline ImVec2 ImLerp(const ImVec2& a, const ImVec2& b, float t)          { return ImVec2(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t); }\r\nstatic inline ImVec2 ImLerp(const ImVec2& a, const ImVec2& b, const ImVec2& t)  { return ImVec2(a.x + (b.x - a.x) * t.x, a.y + (b.y - a.y) * t.y); }\r\nstatic inline ImVec4 ImLerp(const ImVec4& a, const ImVec4& b, float t)          { return ImVec4(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t, a.z + (b.z - a.z) * t, a.w + (b.w - a.w) * t); }\r\nstatic inline float  ImSaturate(float f)                                        { return (f < 0.0f) ? 0.0f : (f > 1.0f) ? 1.0f : f; }\r\nstatic inline float  ImLengthSqr(const ImVec2& lhs)                             { return (lhs.x * lhs.x) + (lhs.y * lhs.y); }\r\nstatic inline float  ImLengthSqr(const ImVec4& lhs)                             { return (lhs.x * lhs.x) + (lhs.y * lhs.y) + (lhs.z * lhs.z) + (lhs.w * lhs.w); }\r\nstatic inline float  ImInvLength(const ImVec2& lhs, float fail_value)           { float d = (lhs.x * lhs.x) + (lhs.y * lhs.y); if (d > 0.0f) return ImRsqrt(d); return fail_value; }\r\nstatic inline float  ImFloor(float f)                                           { return (float)(int)(f); }\r\nstatic inline float  ImFloorSigned(float f)                                     { return (float)((f >= 0 || (float)(int)f == f) ? (int)f : (int)f - 1); } // Decent replacement for floorf()\r\nstatic inline ImVec2 ImFloor(const ImVec2& v)                                   { return ImVec2((float)(int)(v.x), (float)(int)(v.y)); }\r\nstatic inline ImVec2 ImFloorSigned(const ImVec2& v)                             { return ImVec2(ImFloorSigned(v.x), ImFloorSigned(v.y)); }\r\nstatic inline int    ImModPositive(int a, int b)                                { return (a + b) % b; }\r\nstatic inline float  ImDot(const ImVec2& a, const ImVec2& b)                    { return a.x * b.x + a.y * b.y; }\r\nstatic inline ImVec2 ImRotate(const ImVec2& v, float cos_a, float sin_a)        { return ImVec2(v.x * cos_a - v.y * sin_a, v.x * sin_a + v.y * cos_a); }\r\nstatic inline float  ImLinearSweep(float current, float target, float speed)    { if (current < target) return ImMin(current + speed, target); if (current > target) return ImMax(current - speed, target); return current; }\r\nstatic inline ImVec2 ImMul(const ImVec2& lhs, const ImVec2& rhs)                { return ImVec2(lhs.x * rhs.x, lhs.y * rhs.y); }\r\nstatic inline bool   ImIsFloatAboveGuaranteedIntegerPrecision(float f)          { return f <= -16777216 || f >= 16777216; }\r\nIM_MSVC_RUNTIME_CHECKS_RESTORE\r\n\r\n// Helpers: Geometry\r\nIMGUI_API ImVec2     ImBezierCubicCalc(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, float t);\r\nIMGUI_API ImVec2     ImBezierCubicClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments);       // For curves with explicit number of segments\r\nIMGUI_API ImVec2     ImBezierCubicClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol);// For auto-tessellated curves you can use tess_tol = style.CurveTessellationTol\r\nIMGUI_API ImVec2     ImBezierQuadraticCalc(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, float t);\r\nIMGUI_API ImVec2     ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p);\r\nIMGUI_API bool       ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p);\r\nIMGUI_API ImVec2     ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p);\r\nIMGUI_API void       ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w);\r\ninline float         ImTriangleArea(const ImVec2& a, const ImVec2& b, const ImVec2& c) { return ImFabs((a.x * (b.y - c.y)) + (b.x * (c.y - a.y)) + (c.x * (a.y - b.y))) * 0.5f; }\r\nIMGUI_API ImGuiDir   ImGetDirQuadrantFromDelta(float dx, float dy);\r\n\r\n// Helper: ImVec1 (1D vector)\r\n// (this odd construct is used to facilitate the transition between 1D and 2D, and the maintenance of some branches/patches)\r\nIM_MSVC_RUNTIME_CHECKS_OFF\r\nstruct ImVec1\r\n{\r\n    float   x;\r\n    ImVec1()         { x = 0.0f; }\r\n    ImVec1(float _x) { x = _x; }\r\n};\r\n\r\n// Helper: ImVec2ih (2D vector, half-size integer, for long-term packed storage)\r\nstruct ImVec2ih\r\n{\r\n    short   x, y;\r\n    ImVec2ih()                           { x = y = 0; }\r\n    ImVec2ih(short _x, short _y)         { x = _x; y = _y; }\r\n    explicit ImVec2ih(const ImVec2& rhs) { x = (short)rhs.x; y = (short)rhs.y; }\r\n};\r\n\r\n// Helper: ImRect (2D axis aligned bounding-box)\r\n// NB: we can't rely on ImVec2 math operators being available here!\r\nstruct IMGUI_API ImRect\r\n{\r\n    ImVec2      Min;    // Upper-left\r\n    ImVec2      Max;    // Lower-right\r\n\r\n    ImRect()                                        : Min(0.0f, 0.0f), Max(0.0f, 0.0f)  {}\r\n    ImRect(const ImVec2& min, const ImVec2& max)    : Min(min), Max(max)                {}\r\n    ImRect(const ImVec4& v)                         : Min(v.x, v.y), Max(v.z, v.w)      {}\r\n    ImRect(float x1, float y1, float x2, float y2)  : Min(x1, y1), Max(x2, y2)          {}\r\n\r\n    ImVec2      GetCenter() const                   { return ImVec2((Min.x + Max.x) * 0.5f, (Min.y + Max.y) * 0.5f); }\r\n    ImVec2      GetSize() const                     { return ImVec2(Max.x - Min.x, Max.y - Min.y); }\r\n    float       GetWidth() const                    { return Max.x - Min.x; }\r\n    float       GetHeight() const                   { return Max.y - Min.y; }\r\n    float       GetArea() const                     { return (Max.x - Min.x) * (Max.y - Min.y); }\r\n    ImVec2      GetTL() const                       { return Min; }                   // Top-left\r\n    ImVec2      GetTR() const                       { return ImVec2(Max.x, Min.y); }  // Top-right\r\n    ImVec2      GetBL() const                       { return ImVec2(Min.x, Max.y); }  // Bottom-left\r\n    ImVec2      GetBR() const                       { return Max; }                   // Bottom-right\r\n    bool        Contains(const ImVec2& p) const     { return p.x     >= Min.x && p.y     >= Min.y && p.x     <  Max.x && p.y     <  Max.y; }\r\n    bool        Contains(const ImRect& r) const     { return r.Min.x >= Min.x && r.Min.y >= Min.y && r.Max.x <= Max.x && r.Max.y <= Max.y; }\r\n    bool        Overlaps(const ImRect& r) const     { return r.Min.y <  Max.y && r.Max.y >  Min.y && r.Min.x <  Max.x && r.Max.x >  Min.x; }\r\n    void        Add(const ImVec2& p)                { if (Min.x > p.x)     Min.x = p.x;     if (Min.y > p.y)     Min.y = p.y;     if (Max.x < p.x)     Max.x = p.x;     if (Max.y < p.y)     Max.y = p.y; }\r\n    void        Add(const ImRect& r)                { if (Min.x > r.Min.x) Min.x = r.Min.x; if (Min.y > r.Min.y) Min.y = r.Min.y; if (Max.x < r.Max.x) Max.x = r.Max.x; if (Max.y < r.Max.y) Max.y = r.Max.y; }\r\n    void        Expand(const float amount)          { Min.x -= amount;   Min.y -= amount;   Max.x += amount;   Max.y += amount; }\r\n    void        Expand(const ImVec2& amount)        { Min.x -= amount.x; Min.y -= amount.y; Max.x += amount.x; Max.y += amount.y; }\r\n    void        Translate(const ImVec2& d)          { Min.x += d.x; Min.y += d.y; Max.x += d.x; Max.y += d.y; }\r\n    void        TranslateX(float dx)                { Min.x += dx; Max.x += dx; }\r\n    void        TranslateY(float dy)                { Min.y += dy; Max.y += dy; }\r\n    void        ClipWith(const ImRect& r)           { Min = ImMax(Min, r.Min); Max = ImMin(Max, r.Max); }                   // Simple version, may lead to an inverted rectangle, which is fine for Contains/Overlaps test but not for display.\r\n    void        ClipWithFull(const ImRect& r)       { Min = ImClamp(Min, r.Min, r.Max); Max = ImClamp(Max, r.Min, r.Max); } // Full version, ensure both points are fully clipped.\r\n    void        Floor()                             { Min.x = IM_FLOOR(Min.x); Min.y = IM_FLOOR(Min.y); Max.x = IM_FLOOR(Max.x); Max.y = IM_FLOOR(Max.y); }\r\n    bool        IsInverted() const                  { return Min.x > Max.x || Min.y > Max.y; }\r\n    ImVec4      ToVec4() const                      { return ImVec4(Min.x, Min.y, Max.x, Max.y); }\r\n};\r\nIM_MSVC_RUNTIME_CHECKS_RESTORE\r\n\r\n// Helper: ImBitArray\r\ninline bool     ImBitArrayTestBit(const ImU32* arr, int n)      { ImU32 mask = (ImU32)1 << (n & 31); return (arr[n >> 5] & mask) != 0; }\r\ninline void     ImBitArrayClearBit(ImU32* arr, int n)           { ImU32 mask = (ImU32)1 << (n & 31); arr[n >> 5] &= ~mask; }\r\ninline void     ImBitArraySetBit(ImU32* arr, int n)             { ImU32 mask = (ImU32)1 << (n & 31); arr[n >> 5] |= mask; }\r\ninline void     ImBitArraySetBitRange(ImU32* arr, int n, int n2) // Works on range [n..n2)\r\n{\r\n    n2--;\r\n    while (n <= n2)\r\n    {\r\n        int a_mod = (n & 31);\r\n        int b_mod = (n2 > (n | 31) ? 31 : (n2 & 31)) + 1;\r\n        ImU32 mask = (ImU32)(((ImU64)1 << b_mod) - 1) & ~(ImU32)(((ImU64)1 << a_mod) - 1);\r\n        arr[n >> 5] |= mask;\r\n        n = (n + 32) & ~31;\r\n    }\r\n}\r\n\r\n// Helper: ImBitArray class (wrapper over ImBitArray functions)\r\n// Store 1-bit per value.\r\ntemplate<int BITCOUNT, int OFFSET = 0>\r\nstruct ImBitArray\r\n{\r\n    ImU32           Storage[(BITCOUNT + 31) >> 5];\r\n    ImBitArray()                                { ClearAllBits(); }\r\n    void            ClearAllBits()              { memset(Storage, 0, sizeof(Storage)); }\r\n    void            SetAllBits()                { memset(Storage, 255, sizeof(Storage)); }\r\n    bool            TestBit(int n) const        { IM_ASSERT(n + OFFSET < BITCOUNT); return ImBitArrayTestBit(Storage, n + OFFSET); }\r\n    void            SetBit(int n)               { IM_ASSERT(n + OFFSET < BITCOUNT); ImBitArraySetBit(Storage, n + OFFSET); }\r\n    void            ClearBit(int n)             { IM_ASSERT(n + OFFSET < BITCOUNT); ImBitArrayClearBit(Storage, n + OFFSET); }\r\n    void            SetBitRange(int n, int n2)  { ImBitArraySetBitRange(Storage, n + OFFSET, n2 + OFFSET); } // Works on range [n..n2)\r\n    bool            operator[](int n) const     { IM_ASSERT(n + OFFSET < BITCOUNT); return ImBitArrayTestBit(Storage, n + OFFSET); }\r\n};\r\n\r\n// Helper: ImBitVector\r\n// Store 1-bit per value.\r\nstruct IMGUI_API ImBitVector\r\n{\r\n    ImVector<ImU32> Storage;\r\n    void            Create(int sz)              { Storage.resize((sz + 31) >> 5); memset(Storage.Data, 0, (size_t)Storage.Size * sizeof(Storage.Data[0])); }\r\n    void            Clear()                     { Storage.clear(); }\r\n    bool            TestBit(int n) const        { IM_ASSERT(n < (Storage.Size << 5)); return ImBitArrayTestBit(Storage.Data, n); }\r\n    void            SetBit(int n)               { IM_ASSERT(n < (Storage.Size << 5)); ImBitArraySetBit(Storage.Data, n); }\r\n    void            ClearBit(int n)             { IM_ASSERT(n < (Storage.Size << 5)); ImBitArrayClearBit(Storage.Data, n); }\r\n};\r\n\r\n// Helper: ImSpan<>\r\n// Pointing to a span of data we don't own.\r\ntemplate<typename T>\r\nstruct ImSpan\r\n{\r\n    T*                  Data;\r\n    T*                  DataEnd;\r\n\r\n    // Constructors, destructor\r\n    inline ImSpan()                                 { Data = DataEnd = NULL; }\r\n    inline ImSpan(T* data, int size)                { Data = data; DataEnd = data + size; }\r\n    inline ImSpan(T* data, T* data_end)             { Data = data; DataEnd = data_end; }\r\n\r\n    inline void         set(T* data, int size)      { Data = data; DataEnd = data + size; }\r\n    inline void         set(T* data, T* data_end)   { Data = data; DataEnd = data_end; }\r\n    inline int          size() const                { return (int)(ptrdiff_t)(DataEnd - Data); }\r\n    inline int          size_in_bytes() const       { return (int)(ptrdiff_t)(DataEnd - Data) * (int)sizeof(T); }\r\n    inline T&           operator[](int i)           { T* p = Data + i; IM_ASSERT(p >= Data && p < DataEnd); return *p; }\r\n    inline const T&     operator[](int i) const     { const T* p = Data + i; IM_ASSERT(p >= Data && p < DataEnd); return *p; }\r\n\r\n    inline T*           begin()                     { return Data; }\r\n    inline const T*     begin() const               { return Data; }\r\n    inline T*           end()                       { return DataEnd; }\r\n    inline const T*     end() const                 { return DataEnd; }\r\n\r\n    // Utilities\r\n    inline int  index_from_ptr(const T* it) const   { IM_ASSERT(it >= Data && it < DataEnd); const ptrdiff_t off = it - Data; return (int)off; }\r\n};\r\n\r\n// Helper: ImSpanAllocator<>\r\n// Facilitate storing multiple chunks into a single large block (the \"arena\")\r\n// - Usage: call Reserve() N times, allocate GetArenaSizeInBytes() worth, pass it to SetArenaBasePtr(), call GetSpan() N times to retrieve the aligned ranges.\r\ntemplate<int CHUNKS>\r\nstruct ImSpanAllocator\r\n{\r\n    char*   BasePtr;\r\n    int     CurrOff;\r\n    int     CurrIdx;\r\n    int     Offsets[CHUNKS];\r\n    int     Sizes[CHUNKS];\r\n\r\n    ImSpanAllocator()                               { memset(this, 0, sizeof(*this)); }\r\n    inline void  Reserve(int n, size_t sz, int a=4) { IM_ASSERT(n == CurrIdx && n < CHUNKS); CurrOff = IM_MEMALIGN(CurrOff, a); Offsets[n] = CurrOff; Sizes[n] = (int)sz; CurrIdx++; CurrOff += (int)sz; }\r\n    inline int   GetArenaSizeInBytes()              { return CurrOff; }\r\n    inline void  SetArenaBasePtr(void* base_ptr)    { BasePtr = (char*)base_ptr; }\r\n    inline void* GetSpanPtrBegin(int n)             { IM_ASSERT(n >= 0 && n < CHUNKS && CurrIdx == CHUNKS); return (void*)(BasePtr + Offsets[n]); }\r\n    inline void* GetSpanPtrEnd(int n)               { IM_ASSERT(n >= 0 && n < CHUNKS && CurrIdx == CHUNKS); return (void*)(BasePtr + Offsets[n] + Sizes[n]); }\r\n    template<typename T>\r\n    inline void  GetSpan(int n, ImSpan<T>* span)    { span->set((T*)GetSpanPtrBegin(n), (T*)GetSpanPtrEnd(n)); }\r\n};\r\n\r\n// Helper: ImPool<>\r\n// Basic keyed storage for contiguous instances, slow/amortized insertion, O(1) indexable, O(Log N) queries by ID over a dense/hot buffer,\r\n// Honor constructor/destructor. Add/remove invalidate all pointers. Indexes have the same lifetime as the associated object.\r\ntypedef int ImPoolIdx;\r\ntemplate<typename T>\r\nstruct ImPool\r\n{\r\n    ImVector<T>     Buf;        // Contiguous data\r\n    ImGuiStorage    Map;        // ID->Index\r\n    ImPoolIdx       FreeIdx;    // Next free idx to use\r\n    ImPoolIdx       AliveCount; // Number of active/alive items (for display purpose)\r\n\r\n    ImPool()    { FreeIdx = AliveCount = 0; }\r\n    ~ImPool()   { Clear(); }\r\n    T*          GetByKey(ImGuiID key)               { int idx = Map.GetInt(key, -1); return (idx != -1) ? &Buf[idx] : NULL; }\r\n    T*          GetByIndex(ImPoolIdx n)             { return &Buf[n]; }\r\n    ImPoolIdx   GetIndex(const T* p) const          { IM_ASSERT(p >= Buf.Data && p < Buf.Data + Buf.Size); return (ImPoolIdx)(p - Buf.Data); }\r\n    T*          GetOrAddByKey(ImGuiID key)          { int* p_idx = Map.GetIntRef(key, -1); if (*p_idx != -1) return &Buf[*p_idx]; *p_idx = FreeIdx; return Add(); }\r\n    bool        Contains(const T* p) const          { return (p >= Buf.Data && p < Buf.Data + Buf.Size); }\r\n    void        Clear()                             { for (int n = 0; n < Map.Data.Size; n++) { int idx = Map.Data[n].val_i; if (idx != -1) Buf[idx].~T(); } Map.Clear(); Buf.clear(); FreeIdx = AliveCount = 0; }\r\n    T*          Add()                               { int idx = FreeIdx; if (idx == Buf.Size) { Buf.resize(Buf.Size + 1); FreeIdx++; } else { FreeIdx = *(int*)&Buf[idx]; } IM_PLACEMENT_NEW(&Buf[idx]) T(); AliveCount++; return &Buf[idx]; }\r\n    void        Remove(ImGuiID key, const T* p)     { Remove(key, GetIndex(p)); }\r\n    void        Remove(ImGuiID key, ImPoolIdx idx)  { Buf[idx].~T(); *(int*)&Buf[idx] = FreeIdx; FreeIdx = idx; Map.SetInt(key, -1); AliveCount--; }\r\n    void        Reserve(int capacity)               { Buf.reserve(capacity); Map.Data.reserve(capacity); }\r\n\r\n    // To iterate a ImPool: for (int n = 0; n < pool.GetMapSize(); n++) if (T* t = pool.TryGetMapData(n)) { ... }\r\n    // Can be avoided if you know .Remove() has never been called on the pool, or AliveCount == GetMapSize()\r\n    int         GetAliveCount() const               { return AliveCount; }      // Number of active/alive items in the pool (for display purpose)\r\n    int         GetBufSize() const                  { return Buf.Size; }\r\n    int         GetMapSize() const                  { return Map.Data.Size; }   // It is the map we need iterate to find valid items, since we don't have \"alive\" storage anywhere\r\n    T*          TryGetMapData(ImPoolIdx n)          { int idx = Map.Data[n].val_i; if (idx == -1) return NULL; return GetByIndex(idx); }\r\n#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS\r\n    int         GetSize()                           { return GetMapSize(); } // For ImPlot: should use GetMapSize() from (IMGUI_VERSION_NUM >= 18304)\r\n#endif\r\n};\r\n\r\n// Helper: ImChunkStream<>\r\n// Build and iterate a contiguous stream of variable-sized structures.\r\n// This is used by Settings to store persistent data while reducing allocation count.\r\n// We store the chunk size first, and align the final size on 4 bytes boundaries.\r\n// The tedious/zealous amount of casting is to avoid -Wcast-align warnings.\r\ntemplate<typename T>\r\nstruct ImChunkStream\r\n{\r\n    ImVector<char>  Buf;\r\n\r\n    void    clear()                     { Buf.clear(); }\r\n    bool    empty() const               { return Buf.Size == 0; }\r\n    int     size() const                { return Buf.Size; }\r\n    T*      alloc_chunk(size_t sz)      { size_t HDR_SZ = 4; sz = IM_MEMALIGN(HDR_SZ + sz, 4u); int off = Buf.Size; Buf.resize(off + (int)sz); ((int*)(void*)(Buf.Data + off))[0] = (int)sz; return (T*)(void*)(Buf.Data + off + (int)HDR_SZ); }\r\n    T*      begin()                     { size_t HDR_SZ = 4; if (!Buf.Data) return NULL; return (T*)(void*)(Buf.Data + HDR_SZ); }\r\n    T*      next_chunk(T* p)            { size_t HDR_SZ = 4; IM_ASSERT(p >= begin() && p < end()); p = (T*)(void*)((char*)(void*)p + chunk_size(p)); if (p == (T*)(void*)((char*)end() + HDR_SZ)) return (T*)0; IM_ASSERT(p < end()); return p; }\r\n    int     chunk_size(const T* p)      { return ((const int*)p)[-1]; }\r\n    T*      end()                       { return (T*)(void*)(Buf.Data + Buf.Size); }\r\n    int     offset_from_ptr(const T* p) { IM_ASSERT(p >= begin() && p < end()); const ptrdiff_t off = (const char*)p - Buf.Data; return (int)off; }\r\n    T*      ptr_from_offset(int off)    { IM_ASSERT(off >= 4 && off < Buf.Size); return (T*)(void*)(Buf.Data + off); }\r\n    void    swap(ImChunkStream<T>& rhs) { rhs.Buf.swap(Buf); }\r\n\r\n};\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] ImDrawList support\r\n//-----------------------------------------------------------------------------\r\n\r\n// ImDrawList: Helper function to calculate a circle's segment count given its radius and a \"maximum error\" value.\r\n// Estimation of number of circle segment based on error is derived using method described in https://stackoverflow.com/a/2244088/15194693\r\n// Number of segments (N) is calculated using equation:\r\n//   N = ceil ( pi / acos(1 - error / r) )     where r > 0, error <= r\r\n// Our equation is significantly simpler that one in the post thanks for choosing segment that is\r\n// perpendicular to X axis. Follow steps in the article from this starting condition and you will\r\n// will get this result.\r\n//\r\n// Rendering circles with an odd number of segments, while mathematically correct will produce\r\n// asymmetrical results on the raster grid. Therefore we're rounding N to next even number (7->8, 8->8, 9->10 etc.)\r\n//\r\n#define IM_ROUNDUP_TO_EVEN(_V)                                  ((((_V) + 1) / 2) * 2)\r\n#define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MIN                     4\r\n#define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX                     512\r\n#define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(_RAD,_MAXERROR)    ImClamp(IM_ROUNDUP_TO_EVEN((int)ImCeil(IM_PI / ImAcos(1 - ImMin((_MAXERROR), (_RAD)) / (_RAD)))), IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MIN, IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX)\r\n\r\n// Raw equation from IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC rewritten for 'r' and 'error'.\r\n#define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC_R(_N,_MAXERROR)    ((_MAXERROR) / (1 - ImCos(IM_PI / ImMax((float)(_N), IM_PI))))\r\n#define IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC_ERROR(_N,_RAD)     ((1 - ImCos(IM_PI / ImMax((float)(_N), IM_PI))) / (_RAD))\r\n\r\n// ImDrawList: Lookup table size for adaptive arc drawing, cover full circle.\r\n#ifndef IM_DRAWLIST_ARCFAST_TABLE_SIZE\r\n#define IM_DRAWLIST_ARCFAST_TABLE_SIZE                          48 // Number of samples in lookup table.\r\n#endif\r\n#define IM_DRAWLIST_ARCFAST_SAMPLE_MAX                          IM_DRAWLIST_ARCFAST_TABLE_SIZE // Sample index _PathArcToFastEx() for 360 angle.\r\n\r\n// Data shared between all ImDrawList instances\r\n// You may want to create your own instance of this if you want to use ImDrawList completely without ImGui. In that case, watch out for future changes to this structure.\r\nstruct IMGUI_API ImDrawListSharedData\r\n{\r\n    ImVec2          TexUvWhitePixel;            // UV of white pixel in the atlas\r\n    ImFont*         Font;                       // Current/default font (optional, for simplified AddText overload)\r\n    float           FontSize;                   // Current/default font size (optional, for simplified AddText overload)\r\n    float           CurveTessellationTol;       // Tessellation tolerance when using PathBezierCurveTo()\r\n    float           CircleSegmentMaxError;      // Number of circle segments to use per pixel of radius for AddCircle() etc\r\n    ImVec4          ClipRectFullscreen;         // Value for PushClipRectFullscreen()\r\n    ImDrawListFlags InitialFlags;               // Initial flags at the beginning of the frame (it is possible to alter flags on a per-drawlist basis afterwards)\r\n\r\n    // [Internal] Lookup tables\r\n    ImVec2          ArcFastVtx[IM_DRAWLIST_ARCFAST_TABLE_SIZE]; // Sample points on the quarter of the circle.\r\n    float           ArcFastRadiusCutoff;                        // Cutoff radius after which arc drawing will fallback to slower PathArcTo()\r\n    ImU8            CircleSegmentCounts[64];    // Precomputed segment count for given radius before we calculate it dynamically (to avoid calculation overhead)\r\n    const ImVec4*   TexUvLines;                 // UV of anti-aliased lines in the atlas\r\n\r\n    ImDrawListSharedData();\r\n    void SetCircleTessellationMaxError(float max_error);\r\n};\r\n\r\nstruct ImDrawDataBuilder\r\n{\r\n    ImVector<ImDrawList*>   Layers[2];           // Global layers for: regular, tooltip\r\n\r\n    void Clear()                    { for (int n = 0; n < IM_ARRAYSIZE(Layers); n++) Layers[n].resize(0); }\r\n    void ClearFreeMemory()          { for (int n = 0; n < IM_ARRAYSIZE(Layers); n++) Layers[n].clear(); }\r\n    int  GetDrawListCount() const   { int count = 0; for (int n = 0; n < IM_ARRAYSIZE(Layers); n++) count += Layers[n].Size; return count; }\r\n    IMGUI_API void FlattenIntoSingleLayer();\r\n};\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Widgets support: flags, enums, data structures\r\n//-----------------------------------------------------------------------------\r\n\r\n// Transient per-window flags, reset at the beginning of the frame. For child window, inherited from parent on first Begin().\r\n// This is going to be exposed in imgui.h when stabilized enough.\r\nenum ImGuiItemFlags_\r\n{\r\n    ImGuiItemFlags_None                     = 0,\r\n    ImGuiItemFlags_NoTabStop                = 1 << 0,  // false     // Disable keyboard tabbing (FIXME: should merge with _NoNav)\r\n    ImGuiItemFlags_ButtonRepeat             = 1 << 1,  // false     // Button() will return true multiple times based on io.KeyRepeatDelay and io.KeyRepeatRate settings.\r\n    ImGuiItemFlags_Disabled                 = 1 << 2,  // false     // Disable interactions but doesn't affect visuals. See BeginDisabled()/EndDisabled(). See github.com/ocornut/imgui/issues/211\r\n    ImGuiItemFlags_NoNav                    = 1 << 3,  // false     // Disable keyboard/gamepad directional navigation (FIXME: should merge with _NoTabStop)\r\n    ImGuiItemFlags_NoNavDefaultFocus        = 1 << 4,  // false     // Disable item being a candidate for default focus (e.g. used by title bar items)\r\n    ImGuiItemFlags_SelectableDontClosePopup = 1 << 5,  // false     // Disable MenuItem/Selectable() automatically closing their popup window\r\n    ImGuiItemFlags_MixedValue               = 1 << 6,  // false     // [BETA] Represent a mixed/indeterminate value, generally multi-selection where values differ. Currently only supported by Checkbox() (later should support all sorts of widgets)\r\n    ImGuiItemFlags_ReadOnly                 = 1 << 7,  // false     // [ALPHA] Allow hovering interactions but underlying value is not changed.\r\n    ImGuiItemFlags_Inputable                = 1 << 8   // false     // [WIP] Auto-activate input mode when tab focused. Currently only used and supported by a few items before it becomes a generic feature.\r\n};\r\n\r\n// Storage for LastItem data\r\nenum ImGuiItemStatusFlags_\r\n{\r\n    ImGuiItemStatusFlags_None               = 0,\r\n    ImGuiItemStatusFlags_HoveredRect        = 1 << 0,   // Mouse position is within item rectangle (does NOT mean that the window is in correct z-order and can be hovered!, this is only one part of the most-common IsItemHovered test)\r\n    ImGuiItemStatusFlags_HasDisplayRect     = 1 << 1,   // g.LastItemData.DisplayRect is valid\r\n    ImGuiItemStatusFlags_Edited             = 1 << 2,   // Value exposed by item was edited in the current frame (should match the bool return value of most widgets)\r\n    ImGuiItemStatusFlags_ToggledSelection   = 1 << 3,   // Set when Selectable(), TreeNode() reports toggling a selection. We can't report \"Selected\", only state changes, in order to easily handle clipping with less issues.\r\n    ImGuiItemStatusFlags_ToggledOpen        = 1 << 4,   // Set when TreeNode() reports toggling their open state.\r\n    ImGuiItemStatusFlags_HasDeactivated     = 1 << 5,   // Set if the widget/group is able to provide data for the ImGuiItemStatusFlags_Deactivated flag.\r\n    ImGuiItemStatusFlags_Deactivated        = 1 << 6,   // Only valid if ImGuiItemStatusFlags_HasDeactivated is set.\r\n    ImGuiItemStatusFlags_HoveredWindow      = 1 << 7,   // Override the HoveredWindow test to allow cross-window hover testing.\r\n    ImGuiItemStatusFlags_FocusedByTabbing   = 1 << 8    // Set when the Focusable item just got focused by Tabbing (FIXME: to be removed soon)\r\n\r\n#ifdef IMGUI_ENABLE_TEST_ENGINE\r\n    , // [imgui_tests only]\r\n    ImGuiItemStatusFlags_Openable           = 1 << 20,  //\r\n    ImGuiItemStatusFlags_Opened             = 1 << 21,  //\r\n    ImGuiItemStatusFlags_Checkable          = 1 << 22,  //\r\n    ImGuiItemStatusFlags_Checked            = 1 << 23   //\r\n#endif\r\n};\r\n\r\n// Extend ImGuiInputTextFlags_\r\nenum ImGuiInputTextFlagsPrivate_\r\n{\r\n    // [Internal]\r\n    ImGuiInputTextFlags_Multiline           = 1 << 26,  // For internal use by InputTextMultiline()\r\n    ImGuiInputTextFlags_NoMarkEdited        = 1 << 27,  // For internal use by functions using InputText() before reformatting data\r\n    ImGuiInputTextFlags_MergedItem          = 1 << 28   // For internal use by TempInputText(), will skip calling ItemAdd(). Require bounding-box to strictly match.\r\n};\r\n\r\n// Extend ImGuiButtonFlags_\r\nenum ImGuiButtonFlagsPrivate_\r\n{\r\n    ImGuiButtonFlags_PressedOnClick         = 1 << 4,   // return true on click (mouse down event)\r\n    ImGuiButtonFlags_PressedOnClickRelease  = 1 << 5,   // [Default] return true on click + release on same item <-- this is what the majority of Button are using\r\n    ImGuiButtonFlags_PressedOnClickReleaseAnywhere = 1 << 6, // return true on click + release even if the release event is not done while hovering the item\r\n    ImGuiButtonFlags_PressedOnRelease       = 1 << 7,   // return true on release (default requires click+release)\r\n    ImGuiButtonFlags_PressedOnDoubleClick   = 1 << 8,   // return true on double-click (default requires click+release)\r\n    ImGuiButtonFlags_PressedOnDragDropHold  = 1 << 9,   // return true when held into while we are drag and dropping another item (used by e.g. tree nodes, collapsing headers)\r\n    ImGuiButtonFlags_Repeat                 = 1 << 10,  // hold to repeat\r\n    ImGuiButtonFlags_FlattenChildren        = 1 << 11,  // allow interactions even if a child window is overlapping\r\n    ImGuiButtonFlags_AllowItemOverlap       = 1 << 12,  // require previous frame HoveredId to either match id or be null before being usable, use along with SetItemAllowOverlap()\r\n    ImGuiButtonFlags_DontClosePopups        = 1 << 13,  // disable automatically closing parent popup on press // [UNUSED]\r\n    //ImGuiButtonFlags_Disabled             = 1 << 14,  // disable interactions -> use BeginDisabled() or ImGuiItemFlags_Disabled\r\n    ImGuiButtonFlags_AlignTextBaseLine      = 1 << 15,  // vertically align button to match text baseline - ButtonEx() only // FIXME: Should be removed and handled by SmallButton(), not possible currently because of DC.CursorPosPrevLine\r\n    ImGuiButtonFlags_NoKeyModifiers         = 1 << 16,  // disable mouse interaction if a key modifier is held\r\n    ImGuiButtonFlags_NoHoldingActiveId      = 1 << 17,  // don't set ActiveId while holding the mouse (ImGuiButtonFlags_PressedOnClick only)\r\n    ImGuiButtonFlags_NoNavFocus             = 1 << 18,  // don't override navigation focus when activated\r\n    ImGuiButtonFlags_NoHoveredOnFocus       = 1 << 19,  // don't report as hovered when nav focus is on this item\r\n    ImGuiButtonFlags_PressedOnMask_         = ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClickReleaseAnywhere | ImGuiButtonFlags_PressedOnRelease | ImGuiButtonFlags_PressedOnDoubleClick | ImGuiButtonFlags_PressedOnDragDropHold,\r\n    ImGuiButtonFlags_PressedOnDefault_      = ImGuiButtonFlags_PressedOnClickRelease\r\n};\r\n\r\n// Extend ImGuiComboFlags_\r\nenum ImGuiComboFlagsPrivate_\r\n{\r\n    ImGuiComboFlags_CustomPreview           = 1 << 20   // enable BeginComboPreview()\r\n};\r\n\r\n// Extend ImGuiSliderFlags_\r\nenum ImGuiSliderFlagsPrivate_\r\n{\r\n    ImGuiSliderFlags_Vertical               = 1 << 20,  // Should this slider be orientated vertically?\r\n    ImGuiSliderFlags_ReadOnly               = 1 << 21\r\n};\r\n\r\n// Extend ImGuiSelectableFlags_\r\nenum ImGuiSelectableFlagsPrivate_\r\n{\r\n    // NB: need to be in sync with last value of ImGuiSelectableFlags_\r\n    ImGuiSelectableFlags_NoHoldingActiveID      = 1 << 20,\r\n    ImGuiSelectableFlags_SelectOnNav            = 1 << 21,  // (WIP) Auto-select when moved into. This is not exposed in public API as to handle multi-select and modifiers we will need user to explicitly control focus scope. May be replaced with a BeginSelection() API.\r\n    ImGuiSelectableFlags_SelectOnClick          = 1 << 22,  // Override button behavior to react on Click (default is Click+Release)\r\n    ImGuiSelectableFlags_SelectOnRelease        = 1 << 23,  // Override button behavior to react on Release (default is Click+Release)\r\n    ImGuiSelectableFlags_SpanAvailWidth         = 1 << 24,  // Span all avail width even if we declared less for layout purpose. FIXME: We may be able to remove this (added in 6251d379, 2bcafc86 for menus)\r\n    ImGuiSelectableFlags_DrawHoveredWhenHeld    = 1 << 25,  // Always show active when held, even is not hovered. This concept could probably be renamed/formalized somehow.\r\n    ImGuiSelectableFlags_SetNavIdOnHover        = 1 << 26,  // Set Nav/Focus ID on mouse hover (used by MenuItem)\r\n    ImGuiSelectableFlags_NoPadWithHalfSpacing   = 1 << 27   // Disable padding each side with ItemSpacing * 0.5f\r\n};\r\n\r\n// Extend ImGuiTreeNodeFlags_\r\nenum ImGuiTreeNodeFlagsPrivate_\r\n{\r\n    ImGuiTreeNodeFlags_ClipLabelForTrailingButton = 1 << 20\r\n};\r\n\r\nenum ImGuiSeparatorFlags_\r\n{\r\n    ImGuiSeparatorFlags_None                = 0,\r\n    ImGuiSeparatorFlags_Horizontal          = 1 << 0,   // Axis default to current layout type, so generally Horizontal unless e.g. in a menu bar\r\n    ImGuiSeparatorFlags_Vertical            = 1 << 1,\r\n    ImGuiSeparatorFlags_SpanAllColumns      = 1 << 2\r\n};\r\n\r\nenum ImGuiTextFlags_\r\n{\r\n    ImGuiTextFlags_None = 0,\r\n    ImGuiTextFlags_NoWidthForLargeClippedText = 1 << 0\r\n};\r\n\r\nenum ImGuiTooltipFlags_\r\n{\r\n    ImGuiTooltipFlags_None = 0,\r\n    ImGuiTooltipFlags_OverridePreviousTooltip = 1 << 0      // Override will clear/ignore previously submitted tooltip (defaults to append)\r\n};\r\n\r\n// FIXME: this is in development, not exposed/functional as a generic feature yet.\r\n// Horizontal/Vertical enums are fixed to 0/1 so they may be used to index ImVec2\r\nenum ImGuiLayoutType_\r\n{\r\n    ImGuiLayoutType_Horizontal = 0,\r\n    ImGuiLayoutType_Vertical = 1\r\n};\r\n\r\nenum ImGuiLogType\r\n{\r\n    ImGuiLogType_None = 0,\r\n    ImGuiLogType_TTY,\r\n    ImGuiLogType_File,\r\n    ImGuiLogType_Buffer,\r\n    ImGuiLogType_Clipboard\r\n};\r\n\r\n// X/Y enums are fixed to 0/1 so they may be used to index ImVec2\r\nenum ImGuiAxis\r\n{\r\n    ImGuiAxis_None = -1,\r\n    ImGuiAxis_X = 0,\r\n    ImGuiAxis_Y = 1\r\n};\r\n\r\nenum ImGuiPlotType\r\n{\r\n    ImGuiPlotType_Lines,\r\n    ImGuiPlotType_Histogram\r\n};\r\n\r\nenum ImGuiPopupPositionPolicy\r\n{\r\n    ImGuiPopupPositionPolicy_Default,\r\n    ImGuiPopupPositionPolicy_ComboBox,\r\n    ImGuiPopupPositionPolicy_Tooltip\r\n};\r\n\r\nstruct ImGuiDataTypeTempStorage\r\n{\r\n    ImU8        Data[8];        // Can fit any data up to ImGuiDataType_COUNT\r\n};\r\n\r\n// Type information associated to one ImGuiDataType. Retrieve with DataTypeGetInfo().\r\nstruct ImGuiDataTypeInfo\r\n{\r\n    size_t      Size;           // Size in bytes\r\n    const char* Name;           // Short descriptive name for the type, for debugging\r\n    const char* PrintFmt;       // Default printf format for the type\r\n    const char* ScanFmt;        // Default scanf format for the type\r\n};\r\n\r\n// Extend ImGuiDataType_\r\nenum ImGuiDataTypePrivate_\r\n{\r\n    ImGuiDataType_String = ImGuiDataType_COUNT + 1,\r\n    ImGuiDataType_Pointer,\r\n    ImGuiDataType_ID\r\n};\r\n\r\n// Stacked color modifier, backup of modified data so we can restore it\r\nstruct ImGuiColorMod\r\n{\r\n    ImGuiCol    Col;\r\n    ImVec4      BackupValue;\r\n};\r\n\r\n// Stacked style modifier, backup of modified data so we can restore it. Data type inferred from the variable.\r\nstruct ImGuiStyleMod\r\n{\r\n    ImGuiStyleVar   VarIdx;\r\n    union           { int BackupInt[2]; float BackupFloat[2]; };\r\n    ImGuiStyleMod(ImGuiStyleVar idx, int v)     { VarIdx = idx; BackupInt[0] = v; }\r\n    ImGuiStyleMod(ImGuiStyleVar idx, float v)   { VarIdx = idx; BackupFloat[0] = v; }\r\n    ImGuiStyleMod(ImGuiStyleVar idx, ImVec2 v)  { VarIdx = idx; BackupFloat[0] = v.x; BackupFloat[1] = v.y; }\r\n};\r\n\r\n// Storage data for BeginComboPreview()/EndComboPreview()\r\nstruct IMGUI_API ImGuiComboPreviewData\r\n{\r\n    ImRect          PreviewRect;\r\n    ImVec2          BackupCursorPos;\r\n    ImVec2          BackupCursorMaxPos;\r\n    ImVec2          BackupCursorPosPrevLine;\r\n    float           BackupPrevLineTextBaseOffset;\r\n    ImGuiLayoutType BackupLayout;\r\n\r\n    ImGuiComboPreviewData() { memset(this, 0, sizeof(*this)); }\r\n};\r\n\r\n// Stacked storage data for BeginGroup()/EndGroup()\r\nstruct IMGUI_API ImGuiGroupData\r\n{\r\n    ImGuiID     WindowID;\r\n    ImVec2      BackupCursorPos;\r\n    ImVec2      BackupCursorMaxPos;\r\n    ImVec1      BackupIndent;\r\n    ImVec1      BackupGroupOffset;\r\n    ImVec2      BackupCurrLineSize;\r\n    float       BackupCurrLineTextBaseOffset;\r\n    ImGuiID     BackupActiveIdIsAlive;\r\n    bool        BackupActiveIdPreviousFrameIsAlive;\r\n    bool        BackupHoveredIdIsAlive;\r\n    bool        EmitItem;\r\n};\r\n\r\n// Simple column measurement, currently used for MenuItem() only.. This is very short-sighted/throw-away code and NOT a generic helper.\r\nstruct IMGUI_API ImGuiMenuColumns\r\n{\r\n    ImU32       TotalWidth;\r\n    ImU32       NextTotalWidth;\r\n    ImU16       Spacing;\r\n    ImU16       OffsetIcon;         // Always zero for now\r\n    ImU16       OffsetLabel;        // Offsets are locked in Update()\r\n    ImU16       OffsetShortcut;\r\n    ImU16       OffsetMark;\r\n    ImU16       Widths[4];          // Width of:   Icon, Label, Shortcut, Mark  (accumulators for current frame)\r\n\r\n    ImGuiMenuColumns() { memset(this, 0, sizeof(*this)); }\r\n    void        Update(float spacing, bool window_reappearing);\r\n    float       DeclColumns(float w_icon, float w_label, float w_shortcut, float w_mark);\r\n    void        CalcNextTotalWidth(bool update_offsets);\r\n};\r\n\r\n// Internal state of the currently focused/edited text input box\r\n// For a given item ID, access with ImGui::GetInputTextState()\r\nstruct IMGUI_API ImGuiInputTextState\r\n{\r\n    ImGuiID                 ID;                     // widget id owning the text state\r\n    int                     CurLenW, CurLenA;       // we need to maintain our buffer length in both UTF-8 and wchar format. UTF-8 length is valid even if TextA is not.\r\n    ImVector<ImWchar>       TextW;                  // edit buffer, we need to persist but can't guarantee the persistence of the user-provided buffer. so we copy into own buffer.\r\n    ImVector<char>          TextA;                  // temporary UTF8 buffer for callbacks and other operations. this is not updated in every code-path! size=capacity.\r\n    ImVector<char>          InitialTextA;           // backup of end-user buffer at the time of focus (in UTF-8, unaltered)\r\n    bool                    TextAIsValid;           // temporary UTF8 buffer is not initially valid before we make the widget active (until then we pull the data from user argument)\r\n    int                     BufCapacityA;           // end-user buffer capacity\r\n    float                   ScrollX;                // horizontal scrolling/offset\r\n    ImStb::STB_TexteditState Stb;                   // state for stb_textedit.h\r\n    float                   CursorAnim;             // timer for cursor blink, reset on every user action so the cursor reappears immediately\r\n    bool                    CursorFollow;           // set when we want scrolling to follow the current cursor position (not always!)\r\n    bool                    SelectedAllMouseLock;   // after a double-click to select all, we ignore further mouse drags to update selection\r\n    bool                    Edited;                 // edited this frame\r\n    ImGuiInputTextFlags     Flags;                  // copy of InputText() flags\r\n\r\n    ImGuiInputTextState()                   { memset(this, 0, sizeof(*this)); }\r\n    void        ClearText()                 { CurLenW = CurLenA = 0; TextW[0] = 0; TextA[0] = 0; CursorClamp(); }\r\n    void        ClearFreeMemory()           { TextW.clear(); TextA.clear(); InitialTextA.clear(); }\r\n    int         GetUndoAvailCount() const   { return Stb.undostate.undo_point; }\r\n    int         GetRedoAvailCount() const   { return STB_TEXTEDIT_UNDOSTATECOUNT - Stb.undostate.redo_point; }\r\n    void        OnKeyPressed(int key);      // Cannot be inline because we call in code in stb_textedit.h implementation\r\n\r\n    // Cursor & Selection\r\n    void        CursorAnimReset()           { CursorAnim = -0.30f; }                                   // After a user-input the cursor stays on for a while without blinking\r\n    void        CursorClamp()               { Stb.cursor = ImMin(Stb.cursor, CurLenW); Stb.select_start = ImMin(Stb.select_start, CurLenW); Stb.select_end = ImMin(Stb.select_end, CurLenW); }\r\n    bool        HasSelection() const        { return Stb.select_start != Stb.select_end; }\r\n    void        ClearSelection()            { Stb.select_start = Stb.select_end = Stb.cursor; }\r\n    int         GetCursorPos() const        { return Stb.cursor; }\r\n    int         GetSelectionStart() const   { return Stb.select_start; }\r\n    int         GetSelectionEnd() const     { return Stb.select_end; }\r\n    void        SelectAll()                 { Stb.select_start = 0; Stb.cursor = Stb.select_end = CurLenW; Stb.has_preferred_x = 0; }\r\n};\r\n\r\n// Storage for current popup stack\r\nstruct ImGuiPopupData\r\n{\r\n    ImGuiID             PopupId;        // Set on OpenPopup()\r\n    ImGuiWindow*        Window;         // Resolved on BeginPopup() - may stay unresolved if user never calls OpenPopup()\r\n    ImGuiWindow*        SourceWindow;   // Set on OpenPopup() copy of NavWindow at the time of opening the popup\r\n    int                 OpenFrameCount; // Set on OpenPopup()\r\n    ImGuiID             OpenParentId;   // Set on OpenPopup(), we need this to differentiate multiple menu sets from each others (e.g. inside menu bar vs loose menu items)\r\n    ImVec2              OpenPopupPos;   // Set on OpenPopup(), preferred popup position (typically == OpenMousePos when using mouse)\r\n    ImVec2              OpenMousePos;   // Set on OpenPopup(), copy of mouse position at the time of opening popup\r\n\r\n    ImGuiPopupData()    { memset(this, 0, sizeof(*this)); OpenFrameCount = -1; }\r\n};\r\n\r\nenum ImGuiNextWindowDataFlags_\r\n{\r\n    ImGuiNextWindowDataFlags_None               = 0,\r\n    ImGuiNextWindowDataFlags_HasPos             = 1 << 0,\r\n    ImGuiNextWindowDataFlags_HasSize            = 1 << 1,\r\n    ImGuiNextWindowDataFlags_HasContentSize     = 1 << 2,\r\n    ImGuiNextWindowDataFlags_HasCollapsed       = 1 << 3,\r\n    ImGuiNextWindowDataFlags_HasSizeConstraint  = 1 << 4,\r\n    ImGuiNextWindowDataFlags_HasFocus           = 1 << 5,\r\n    ImGuiNextWindowDataFlags_HasBgAlpha         = 1 << 6,\r\n    ImGuiNextWindowDataFlags_HasScroll          = 1 << 7\r\n};\r\n\r\n// Storage for SetNexWindow** functions\r\nstruct ImGuiNextWindowData\r\n{\r\n    ImGuiNextWindowDataFlags    Flags;\r\n    ImGuiCond                   PosCond;\r\n    ImGuiCond                   SizeCond;\r\n    ImGuiCond                   CollapsedCond;\r\n    ImVec2                      PosVal;\r\n    ImVec2                      PosPivotVal;\r\n    ImVec2                      SizeVal;\r\n    ImVec2                      ContentSizeVal;\r\n    ImVec2                      ScrollVal;\r\n    bool                        CollapsedVal;\r\n    ImRect                      SizeConstraintRect;\r\n    ImGuiSizeCallback           SizeCallback;\r\n    void*                       SizeCallbackUserData;\r\n    float                       BgAlphaVal;             // Override background alpha\r\n    ImVec2                      MenuBarOffsetMinVal;    // (Always on) This is not exposed publicly, so we don't clear it and it doesn't have a corresponding flag (could we? for consistency?)\r\n\r\n    ImGuiNextWindowData()       { memset(this, 0, sizeof(*this)); }\r\n    inline void ClearFlags()    { Flags = ImGuiNextWindowDataFlags_None; }\r\n};\r\n\r\nenum ImGuiNextItemDataFlags_\r\n{\r\n    ImGuiNextItemDataFlags_None     = 0,\r\n    ImGuiNextItemDataFlags_HasWidth = 1 << 0,\r\n    ImGuiNextItemDataFlags_HasOpen  = 1 << 1\r\n};\r\n\r\nstruct ImGuiNextItemData\r\n{\r\n    ImGuiNextItemDataFlags      Flags;\r\n    float                       Width;          // Set by SetNextItemWidth()\r\n    ImGuiID                     FocusScopeId;   // Set by SetNextItemMultiSelectData() (!= 0 signify value has been set, so it's an alternate version of HasSelectionData, we don't use Flags for this because they are cleared too early. This is mostly used for debugging)\r\n    ImGuiCond                   OpenCond;\r\n    bool                        OpenVal;        // Set by SetNextItemOpen()\r\n\r\n    ImGuiNextItemData()         { memset(this, 0, sizeof(*this)); }\r\n    inline void ClearFlags()    { Flags = ImGuiNextItemDataFlags_None; } // Also cleared manually by ItemAdd()!\r\n};\r\n\r\n// Status storage for the last submitted item\r\nstruct ImGuiLastItemData\r\n{\r\n    ImGuiID                 ID;\r\n    ImGuiItemFlags          InFlags;            // See ImGuiItemFlags_\r\n    ImGuiItemStatusFlags    StatusFlags;        // See ImGuiItemStatusFlags_\r\n    ImRect                  Rect;               // Full rectangle\r\n    ImRect                  NavRect;            // Navigation scoring rectangle (not displayed)\r\n    ImRect                  DisplayRect;        // Display rectangle (only if ImGuiItemStatusFlags_HasDisplayRect is set)\r\n\r\n    ImGuiLastItemData()     { memset(this, 0, sizeof(*this)); }\r\n};\r\n\r\nstruct IMGUI_API ImGuiStackSizes\r\n{\r\n    short   SizeOfIDStack;\r\n    short   SizeOfColorStack;\r\n    short   SizeOfStyleVarStack;\r\n    short   SizeOfFontStack;\r\n    short   SizeOfFocusScopeStack;\r\n    short   SizeOfGroupStack;\r\n    short   SizeOfItemFlagsStack;\r\n    short   SizeOfBeginPopupStack;\r\n    short   SizeOfDisabledStack;\r\n\r\n    ImGuiStackSizes() { memset(this, 0, sizeof(*this)); }\r\n    void SetToCurrentState();\r\n    void CompareWithCurrentState();\r\n};\r\n\r\n// Data saved for each window pushed into the stack\r\nstruct ImGuiWindowStackData\r\n{\r\n    ImGuiWindow*            Window;\r\n    ImGuiLastItemData       ParentLastItemDataBackup;\r\n    ImGuiStackSizes         StackSizesOnBegin;      // Store size of various stacks for asserting\r\n};\r\n\r\nstruct ImGuiShrinkWidthItem\r\n{\r\n    int         Index;\r\n    float       Width;\r\n};\r\n\r\nstruct ImGuiPtrOrIndex\r\n{\r\n    void*       Ptr;            // Either field can be set, not both. e.g. Dock node tab bars are loose while BeginTabBar() ones are in a pool.\r\n    int         Index;          // Usually index in a main pool.\r\n\r\n    ImGuiPtrOrIndex(void* ptr)  { Ptr = ptr; Index = -1; }\r\n    ImGuiPtrOrIndex(int index)  { Ptr = NULL; Index = index; }\r\n};\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Inputs support\r\n//-----------------------------------------------------------------------------\r\n\r\ntypedef ImBitArray<ImGuiKey_NamedKey_COUNT, -ImGuiKey_NamedKey_BEGIN>    ImBitArrayForNamedKeys;\r\n\r\nenum ImGuiKeyPrivate_\r\n{\r\n    ImGuiKey_LegacyNativeKey_BEGIN  = 0,\r\n    ImGuiKey_LegacyNativeKey_END    = 512,\r\n    ImGuiKey_Gamepad_BEGIN          = ImGuiKey_GamepadStart,\r\n    ImGuiKey_Gamepad_END            = ImGuiKey_GamepadRStickRight + 1\r\n};\r\n\r\nenum ImGuiInputEventType\r\n{\r\n    ImGuiInputEventType_None = 0,\r\n    ImGuiInputEventType_MousePos,\r\n    ImGuiInputEventType_MouseWheel,\r\n    ImGuiInputEventType_MouseButton,\r\n    ImGuiInputEventType_Key,\r\n    ImGuiInputEventType_Char,\r\n    ImGuiInputEventType_Focus,\r\n    ImGuiInputEventType_COUNT\r\n};\r\n\r\nenum ImGuiInputSource\r\n{\r\n    ImGuiInputSource_None = 0,\r\n    ImGuiInputSource_Mouse,\r\n    ImGuiInputSource_Keyboard,\r\n    ImGuiInputSource_Gamepad,\r\n    ImGuiInputSource_Clipboard,     // Currently only used by InputText()\r\n    ImGuiInputSource_Nav,           // Stored in g.ActiveIdSource only\r\n    ImGuiInputSource_COUNT\r\n};\r\n\r\n// FIXME: Structures in the union below need to be declared as anonymous unions appears to be an extension?\r\n// Using ImVec2() would fail on Clang 'union member 'MousePos' has a non-trivial default constructor'\r\nstruct ImGuiInputEventMousePos      { float PosX, PosY; };\r\nstruct ImGuiInputEventMouseWheel    { float WheelX, WheelY; };\r\nstruct ImGuiInputEventMouseButton   { int Button; bool Down; };\r\nstruct ImGuiInputEventKey           { ImGuiKey Key; bool Down; float AnalogValue; };\r\nstruct ImGuiInputEventText          { unsigned int Char; };\r\nstruct ImGuiInputEventAppFocused    { bool Focused; };\r\n\r\nstruct ImGuiInputEvent\r\n{\r\n    ImGuiInputEventType             Type;\r\n    ImGuiInputSource                Source;\r\n    union\r\n    {\r\n        ImGuiInputEventMousePos     MousePos;       // if Type == ImGuiInputEventType_MousePos\r\n        ImGuiInputEventMouseWheel   MouseWheel;     // if Type == ImGuiInputEventType_MouseWheel\r\n        ImGuiInputEventMouseButton  MouseButton;    // if Type == ImGuiInputEventType_MouseButton\r\n        ImGuiInputEventKey          Key;            // if Type == ImGuiInputEventType_Key\r\n        ImGuiInputEventText         Text;           // if Type == ImGuiInputEventType_Text\r\n        ImGuiInputEventAppFocused   AppFocused;     // if Type == ImGuiInputEventType_Focus\r\n    };\r\n    bool                            AddedByTestEngine;\r\n\r\n    ImGuiInputEvent() { memset(this, 0, sizeof(*this)); }\r\n};\r\n\r\n// FIXME-NAV: Clarify/expose various repeat delay/rate\r\nenum ImGuiInputReadMode\r\n{\r\n    ImGuiInputReadMode_Down,\r\n    ImGuiInputReadMode_Pressed,\r\n    ImGuiInputReadMode_Released,\r\n    ImGuiInputReadMode_Repeat,\r\n    ImGuiInputReadMode_RepeatSlow,\r\n    ImGuiInputReadMode_RepeatFast\r\n};\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Clipper support\r\n//-----------------------------------------------------------------------------\r\n\r\nstruct ImGuiListClipperRange\r\n{\r\n    int     Min;\r\n    int     Max;\r\n    bool    PosToIndexConvert;      // Begin/End are absolute position (will be converted to indices later)\r\n    ImS8    PosToIndexOffsetMin;    // Add to Min after converting to indices\r\n    ImS8    PosToIndexOffsetMax;    // Add to Min after converting to indices\r\n\r\n    static ImGuiListClipperRange    FromIndices(int min, int max)                               { ImGuiListClipperRange r = { min, max, false, 0, 0 }; return r; }\r\n    static ImGuiListClipperRange    FromPositions(float y1, float y2, int off_min, int off_max) { ImGuiListClipperRange r = { (int)y1, (int)y2, true, (ImS8)off_min, (ImS8)off_max }; return r; }\r\n};\r\n\r\n// Temporary clipper data, buffers shared/reused between instances\r\nstruct ImGuiListClipperData\r\n{\r\n    ImGuiListClipper*               ListClipper;\r\n    float                           LossynessOffset;\r\n    int                             StepNo;\r\n    int                             ItemsFrozen;\r\n    ImVector<ImGuiListClipperRange> Ranges;\r\n\r\n    ImGuiListClipperData()          { memset(this, 0, sizeof(*this)); }\r\n    void                            Reset(ImGuiListClipper* clipper) { ListClipper = clipper; StepNo = ItemsFrozen = 0; Ranges.resize(0); }\r\n};\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Navigation support\r\n//-----------------------------------------------------------------------------\r\n\r\nenum ImGuiActivateFlags_\r\n{\r\n    ImGuiActivateFlags_None                 = 0,\r\n    ImGuiActivateFlags_PreferInput          = 1 << 0,       // Favor activation that requires keyboard text input (e.g. for Slider/Drag). Default if keyboard is available.\r\n    ImGuiActivateFlags_PreferTweak          = 1 << 1,       // Favor activation for tweaking with arrows or gamepad (e.g. for Slider/Drag). Default if keyboard is not available.\r\n    ImGuiActivateFlags_TryToPreserveState   = 1 << 2        // Request widget to preserve state if it can (e.g. InputText will try to preserve cursor/selection)\r\n};\r\n\r\n// Early work-in-progress API for ScrollToItem()\r\nenum ImGuiScrollFlags_\r\n{\r\n    ImGuiScrollFlags_None                   = 0,\r\n    ImGuiScrollFlags_KeepVisibleEdgeX       = 1 << 0,       // If item is not visible: scroll as little as possible on X axis to bring item back into view [default for X axis]\r\n    ImGuiScrollFlags_KeepVisibleEdgeY       = 1 << 1,       // If item is not visible: scroll as little as possible on Y axis to bring item back into view [default for Y axis for windows that are already visible]\r\n    ImGuiScrollFlags_KeepVisibleCenterX     = 1 << 2,       // If item is not visible: scroll to make the item centered on X axis [rarely used]\r\n    ImGuiScrollFlags_KeepVisibleCenterY     = 1 << 3,       // If item is not visible: scroll to make the item centered on Y axis\r\n    ImGuiScrollFlags_AlwaysCenterX          = 1 << 4,       // Always center the result item on X axis [rarely used]\r\n    ImGuiScrollFlags_AlwaysCenterY          = 1 << 5,       // Always center the result item on Y axis [default for Y axis for appearing window)\r\n    ImGuiScrollFlags_NoScrollParent         = 1 << 6,       // Disable forwarding scrolling to parent window if required to keep item/rect visible (only scroll window the function was applied to).\r\n    ImGuiScrollFlags_MaskX_                 = ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleCenterX | ImGuiScrollFlags_AlwaysCenterX,\r\n    ImGuiScrollFlags_MaskY_                 = ImGuiScrollFlags_KeepVisibleEdgeY | ImGuiScrollFlags_KeepVisibleCenterY | ImGuiScrollFlags_AlwaysCenterY\r\n};\r\n\r\nenum ImGuiNavHighlightFlags_\r\n{\r\n    ImGuiNavHighlightFlags_None             = 0,\r\n    ImGuiNavHighlightFlags_TypeDefault      = 1 << 0,\r\n    ImGuiNavHighlightFlags_TypeThin         = 1 << 1,\r\n    ImGuiNavHighlightFlags_AlwaysDraw       = 1 << 2,       // Draw rectangular highlight if (g.NavId == id) _even_ when using the mouse.\r\n    ImGuiNavHighlightFlags_NoRounding       = 1 << 3\r\n};\r\n\r\nenum ImGuiNavDirSourceFlags_\r\n{\r\n    ImGuiNavDirSourceFlags_None             = 0,\r\n    ImGuiNavDirSourceFlags_RawKeyboard      = 1 << 0,   // Raw keyboard (not pulled from nav), faciliate use of some functions before we can unify nav and keys\r\n    ImGuiNavDirSourceFlags_Keyboard         = 1 << 1,\r\n    ImGuiNavDirSourceFlags_PadDPad          = 1 << 2,\r\n    ImGuiNavDirSourceFlags_PadLStick        = 1 << 3\r\n};\r\n\r\nenum ImGuiNavMoveFlags_\r\n{\r\n    ImGuiNavMoveFlags_None                  = 0,\r\n    ImGuiNavMoveFlags_LoopX                 = 1 << 0,   // On failed request, restart from opposite side\r\n    ImGuiNavMoveFlags_LoopY                 = 1 << 1,\r\n    ImGuiNavMoveFlags_WrapX                 = 1 << 2,   // On failed request, request from opposite side one line down (when NavDir==right) or one line up (when NavDir==left)\r\n    ImGuiNavMoveFlags_WrapY                 = 1 << 3,   // This is not super useful but provided for completeness\r\n    ImGuiNavMoveFlags_AllowCurrentNavId     = 1 << 4,   // Allow scoring and considering the current NavId as a move target candidate. This is used when the move source is offset (e.g. pressing PageDown actually needs to send a Up move request, if we are pressing PageDown from the bottom-most item we need to stay in place)\r\n    ImGuiNavMoveFlags_AlsoScoreVisibleSet   = 1 << 5,   // Store alternate result in NavMoveResultLocalVisible that only comprise elements that are already fully visible (used by PageUp/PageDown)\r\n    ImGuiNavMoveFlags_ScrollToEdgeY         = 1 << 6,   // Force scrolling to min/max (used by Home/End) // FIXME-NAV: Aim to remove or reword, probably unnecessary\r\n    ImGuiNavMoveFlags_Forwarded             = 1 << 7,\r\n    ImGuiNavMoveFlags_DebugNoResult         = 1 << 8,   // Dummy scoring for debug purpose, don't apply result\r\n    ImGuiNavMoveFlags_FocusApi              = 1 << 9,\r\n    ImGuiNavMoveFlags_Tabbing               = 1 << 10,  // == Focus + Activate if item is Inputable + DontChangeNavHighlight\r\n    ImGuiNavMoveFlags_Activate              = 1 << 11,\r\n    ImGuiNavMoveFlags_DontSetNavHighlight   = 1 << 12   // Do not alter the visible state of keyboard vs mouse nav highlight\r\n};\r\n\r\nenum ImGuiNavLayer\r\n{\r\n    ImGuiNavLayer_Main  = 0,    // Main scrolling layer\r\n    ImGuiNavLayer_Menu  = 1,    // Menu layer (access with Alt/ImGuiNavInput_Menu)\r\n    ImGuiNavLayer_COUNT\r\n};\r\n\r\nstruct ImGuiNavItemData\r\n{\r\n    ImGuiWindow*        Window;         // Init,Move    // Best candidate window (result->ItemWindow->RootWindowForNav == request->Window)\r\n    ImGuiID             ID;             // Init,Move    // Best candidate item ID\r\n    ImGuiID             FocusScopeId;   // Init,Move    // Best candidate focus scope ID\r\n    ImRect              RectRel;        // Init,Move    // Best candidate bounding box in window relative space\r\n    ImGuiItemFlags      InFlags;        // ????,Move    // Best candidate item flags\r\n    float               DistBox;        //      Move    // Best candidate box distance to current NavId\r\n    float               DistCenter;     //      Move    // Best candidate center distance to current NavId\r\n    float               DistAxial;      //      Move    // Best candidate axial distance to current NavId\r\n\r\n    ImGuiNavItemData()  { Clear(); }\r\n    void Clear()        { Window = NULL; ID = FocusScopeId = 0; InFlags = 0; DistBox = DistCenter = DistAxial = FLT_MAX; }\r\n};\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Columns support\r\n//-----------------------------------------------------------------------------\r\n\r\n// Flags for internal's BeginColumns(). Prefix using BeginTable() nowadays!\r\nenum ImGuiOldColumnFlags_\r\n{\r\n    ImGuiOldColumnFlags_None                    = 0,\r\n    ImGuiOldColumnFlags_NoBorder                = 1 << 0,   // Disable column dividers\r\n    ImGuiOldColumnFlags_NoResize                = 1 << 1,   // Disable resizing columns when clicking on the dividers\r\n    ImGuiOldColumnFlags_NoPreserveWidths        = 1 << 2,   // Disable column width preservation when adjusting columns\r\n    ImGuiOldColumnFlags_NoForceWithinWindow     = 1 << 3,   // Disable forcing columns to fit within window\r\n    ImGuiOldColumnFlags_GrowParentContentsSize  = 1 << 4    // (WIP) Restore pre-1.51 behavior of extending the parent window contents size but _without affecting the columns width at all_. Will eventually remove.\r\n\r\n    // Obsolete names (will be removed)\r\n#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS\r\n    , ImGuiColumnsFlags_None                    = ImGuiOldColumnFlags_None,\r\n    ImGuiColumnsFlags_NoBorder                  = ImGuiOldColumnFlags_NoBorder,\r\n    ImGuiColumnsFlags_NoResize                  = ImGuiOldColumnFlags_NoResize,\r\n    ImGuiColumnsFlags_NoPreserveWidths          = ImGuiOldColumnFlags_NoPreserveWidths,\r\n    ImGuiColumnsFlags_NoForceWithinWindow       = ImGuiOldColumnFlags_NoForceWithinWindow,\r\n    ImGuiColumnsFlags_GrowParentContentsSize    = ImGuiOldColumnFlags_GrowParentContentsSize\r\n#endif\r\n};\r\n\r\nstruct ImGuiOldColumnData\r\n{\r\n    float               OffsetNorm;         // Column start offset, normalized 0.0 (far left) -> 1.0 (far right)\r\n    float               OffsetNormBeforeResize;\r\n    ImGuiOldColumnFlags Flags;              // Not exposed\r\n    ImRect              ClipRect;\r\n\r\n    ImGuiOldColumnData() { memset(this, 0, sizeof(*this)); }\r\n};\r\n\r\nstruct ImGuiOldColumns\r\n{\r\n    ImGuiID             ID;\r\n    ImGuiOldColumnFlags Flags;\r\n    bool                IsFirstFrame;\r\n    bool                IsBeingResized;\r\n    int                 Current;\r\n    int                 Count;\r\n    float               OffMinX, OffMaxX;       // Offsets from HostWorkRect.Min.x\r\n    float               LineMinY, LineMaxY;\r\n    float               HostCursorPosY;         // Backup of CursorPos at the time of BeginColumns()\r\n    float               HostCursorMaxPosX;      // Backup of CursorMaxPos at the time of BeginColumns()\r\n    ImRect              HostInitialClipRect;    // Backup of ClipRect at the time of BeginColumns()\r\n    ImRect              HostBackupClipRect;     // Backup of ClipRect during PushColumnsBackground()/PopColumnsBackground()\r\n    ImRect              HostBackupParentWorkRect;//Backup of WorkRect at the time of BeginColumns()\r\n    ImVector<ImGuiOldColumnData> Columns;\r\n    ImDrawListSplitter  Splitter;\r\n\r\n    ImGuiOldColumns()   { memset(this, 0, sizeof(*this)); }\r\n};\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Multi-select support\r\n//-----------------------------------------------------------------------------\r\n\r\n#ifdef IMGUI_HAS_MULTI_SELECT\r\n// <this is filled in 'range_select' branch>\r\n#endif // #ifdef IMGUI_HAS_MULTI_SELECT\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Docking support\r\n//-----------------------------------------------------------------------------\r\n\r\n#ifdef IMGUI_HAS_DOCK\r\n// <this is filled in 'docking' branch>\r\n#endif // #ifdef IMGUI_HAS_DOCK\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Viewport support\r\n//-----------------------------------------------------------------------------\r\n\r\n// ImGuiViewport Private/Internals fields (cardinal sin: we are using inheritance!)\r\n// Every instance of ImGuiViewport is in fact a ImGuiViewportP.\r\nstruct ImGuiViewportP : public ImGuiViewport\r\n{\r\n    int                 DrawListsLastFrame[2];  // Last frame number the background (0) and foreground (1) draw lists were used\r\n    ImDrawList*         DrawLists[2];           // Convenience background (0) and foreground (1) draw lists. We use them to draw software mouser cursor when io.MouseDrawCursor is set and to draw most debug overlays.\r\n    ImDrawData          DrawDataP;\r\n    ImDrawDataBuilder   DrawDataBuilder;\r\n\r\n    ImVec2              WorkOffsetMin;          // Work Area: Offset from Pos to top-left corner of Work Area. Generally (0,0) or (0,+main_menu_bar_height). Work Area is Full Area but without menu-bars/status-bars (so WorkArea always fit inside Pos/Size!)\r\n    ImVec2              WorkOffsetMax;          // Work Area: Offset from Pos+Size to bottom-right corner of Work Area. Generally (0,0) or (0,-status_bar_height).\r\n    ImVec2              BuildWorkOffsetMin;     // Work Area: Offset being built during current frame. Generally >= 0.0f.\r\n    ImVec2              BuildWorkOffsetMax;     // Work Area: Offset being built during current frame. Generally <= 0.0f.\r\n\r\n    ImGuiViewportP()    { DrawListsLastFrame[0] = DrawListsLastFrame[1] = -1; DrawLists[0] = DrawLists[1] = NULL; }\r\n    ~ImGuiViewportP()   { if (DrawLists[0]) IM_DELETE(DrawLists[0]); if (DrawLists[1]) IM_DELETE(DrawLists[1]); }\r\n\r\n    // Calculate work rect pos/size given a set of offset (we have 1 pair of offset for rect locked from last frame data, and 1 pair for currently building rect)\r\n    ImVec2  CalcWorkRectPos(const ImVec2& off_min) const                            { return ImVec2(Pos.x + off_min.x, Pos.y + off_min.y); }\r\n    ImVec2  CalcWorkRectSize(const ImVec2& off_min, const ImVec2& off_max) const    { return ImVec2(ImMax(0.0f, Size.x - off_min.x + off_max.x), ImMax(0.0f, Size.y - off_min.y + off_max.y)); }\r\n    void    UpdateWorkRect()            { WorkPos = CalcWorkRectPos(WorkOffsetMin); WorkSize = CalcWorkRectSize(WorkOffsetMin, WorkOffsetMax); } // Update public fields\r\n\r\n    // Helpers to retrieve ImRect (we don't need to store BuildWorkRect as every access tend to change it, hence the code asymmetry)\r\n    ImRect  GetMainRect() const         { return ImRect(Pos.x, Pos.y, Pos.x + Size.x, Pos.y + Size.y); }\r\n    ImRect  GetWorkRect() const         { return ImRect(WorkPos.x, WorkPos.y, WorkPos.x + WorkSize.x, WorkPos.y + WorkSize.y); }\r\n    ImRect  GetBuildWorkRect() const    { ImVec2 pos = CalcWorkRectPos(BuildWorkOffsetMin); ImVec2 size = CalcWorkRectSize(BuildWorkOffsetMin, BuildWorkOffsetMax); return ImRect(pos.x, pos.y, pos.x + size.x, pos.y + size.y); }\r\n};\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Settings support\r\n//-----------------------------------------------------------------------------\r\n\r\n// Windows data saved in imgui.ini file\r\n// Because we never destroy or rename ImGuiWindowSettings, we can store the names in a separate buffer easily.\r\n// (this is designed to be stored in a ImChunkStream buffer, with the variable-length Name following our structure)\r\nstruct ImGuiWindowSettings\r\n{\r\n    ImGuiID     ID;\r\n    ImVec2ih    Pos;\r\n    ImVec2ih    Size;\r\n    bool        Collapsed;\r\n    bool        WantApply;      // Set when loaded from .ini data (to enable merging/loading .ini data into an already running context)\r\n\r\n    ImGuiWindowSettings()       { memset(this, 0, sizeof(*this)); }\r\n    char* GetName()             { return (char*)(this + 1); }\r\n};\r\n\r\nstruct ImGuiSettingsHandler\r\n{\r\n    const char* TypeName;       // Short description stored in .ini file. Disallowed characters: '[' ']'\r\n    ImGuiID     TypeHash;       // == ImHashStr(TypeName)\r\n    void        (*ClearAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler);                                // Clear all settings data\r\n    void        (*ReadInitFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler);                                // Read: Called before reading (in registration order)\r\n    void*       (*ReadOpenFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, const char* name);              // Read: Called when entering into a new ini entry e.g. \"[Window][Name]\"\r\n    void        (*ReadLineFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, void* entry, const char* line); // Read: Called for every line of text within an ini entry\r\n    void        (*ApplyAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler);                                // Read: Called after reading (in registration order)\r\n    void        (*WriteAllFn)(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* out_buf);      // Write: Output every entries into 'out_buf'\r\n    void*       UserData;\r\n\r\n    ImGuiSettingsHandler() { memset(this, 0, sizeof(*this)); }\r\n};\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Metrics, Debug Tools\r\n//-----------------------------------------------------------------------------\r\n\r\nstruct ImGuiMetricsConfig\r\n{\r\n    bool        ShowStackTool;\r\n    bool        ShowWindowsRects;\r\n    bool        ShowWindowsBeginOrder;\r\n    bool        ShowTablesRects;\r\n    bool        ShowDrawCmdMesh;\r\n    bool        ShowDrawCmdBoundingBoxes;\r\n    int         ShowWindowsRectsType;\r\n    int         ShowTablesRectsType;\r\n\r\n    ImGuiMetricsConfig()\r\n    {\r\n        ShowStackTool = false;\r\n        ShowWindowsRects = false;\r\n        ShowWindowsBeginOrder = false;\r\n        ShowTablesRects = false;\r\n        ShowDrawCmdMesh = true;\r\n        ShowDrawCmdBoundingBoxes = true;\r\n        ShowWindowsRectsType = -1;\r\n        ShowTablesRectsType = -1;\r\n    }\r\n};\r\n\r\nstruct ImGuiStackLevelInfo\r\n{\r\n    ImGuiID                 ID;\r\n    ImS8                    QueryFrameCount;            // >= 1: Query in progress\r\n    bool                    QuerySuccess;               // Obtained result from DebugHookIdInfo()\r\n    char                    Desc[58];                   // Arbitrarily sized buffer to hold a result (FIXME: could replace Results[] with a chunk stream?)\r\n\r\n    ImGuiStackLevelInfo()   { memset(this, 0, sizeof(*this)); }\r\n};\r\n\r\n// State for Stack tool queries\r\nstruct ImGuiStackTool\r\n{\r\n    int                     LastActiveFrame;\r\n    int                     StackLevel;                 // -1: query stack and resize Results, >= 0: individual stack level\r\n    ImGuiID                 QueryId;                    // ID to query details for\r\n    ImVector<ImGuiStackLevelInfo> Results;\r\n\r\n    ImGuiStackTool()        { memset(this, 0, sizeof(*this)); }\r\n};\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Generic context hooks\r\n//-----------------------------------------------------------------------------\r\n\r\ntypedef void (*ImGuiContextHookCallback)(ImGuiContext* ctx, ImGuiContextHook* hook);\r\nenum ImGuiContextHookType { ImGuiContextHookType_NewFramePre, ImGuiContextHookType_NewFramePost, ImGuiContextHookType_EndFramePre, ImGuiContextHookType_EndFramePost, ImGuiContextHookType_RenderPre, ImGuiContextHookType_RenderPost, ImGuiContextHookType_Shutdown, ImGuiContextHookType_PendingRemoval_ };\r\n\r\nstruct ImGuiContextHook\r\n{\r\n    ImGuiID                     HookId;     // A unique ID assigned by AddContextHook()\r\n    ImGuiContextHookType        Type;\r\n    ImGuiID                     Owner;\r\n    ImGuiContextHookCallback    Callback;\r\n    void*                       UserData;\r\n\r\n    ImGuiContextHook()          { memset(this, 0, sizeof(*this)); }\r\n};\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] ImGuiContext (main imgui context)\r\n//-----------------------------------------------------------------------------\r\n\r\nstruct ImGuiContext\r\n{\r\n    bool                    Initialized;\r\n    bool                    FontAtlasOwnedByContext;            // IO.Fonts-> is owned by the ImGuiContext and will be destructed along with it.\r\n    ImGuiIO                 IO;\r\n    ImVector<ImGuiInputEvent> InputEventsQueue;                 // Input events which will be tricked/written into IO structure.\r\n    ImVector<ImGuiInputEvent> InputEventsTrail;                 // Past input events processed in NewFrame(). This is to allow domain-specific application to access e.g mouse/pen trail.\r\n    ImGuiStyle              Style;\r\n    ImFont*                 Font;                               // (Shortcut) == FontStack.empty() ? IO.Font : FontStack.back()\r\n    float                   FontSize;                           // (Shortcut) == FontBaseSize * g.CurrentWindow->FontWindowScale == window->FontSize(). Text height for current window.\r\n    float                   FontBaseSize;                       // (Shortcut) == IO.FontGlobalScale * Font->Scale * Font->FontSize. Base text height.\r\n    ImDrawListSharedData    DrawListSharedData;\r\n    double                  Time;\r\n    int                     FrameCount;\r\n    int                     FrameCountEnded;\r\n    int                     FrameCountRendered;\r\n    bool                    WithinFrameScope;                   // Set by NewFrame(), cleared by EndFrame()\r\n    bool                    WithinFrameScopeWithImplicitWindow; // Set by NewFrame(), cleared by EndFrame() when the implicit debug window has been pushed\r\n    bool                    WithinEndChild;                     // Set within EndChild()\r\n    bool                    GcCompactAll;                       // Request full GC\r\n    bool                    TestEngineHookItems;                // Will call test engine hooks: ImGuiTestEngineHook_ItemAdd(), ImGuiTestEngineHook_ItemInfo(), ImGuiTestEngineHook_Log()\r\n    void*                   TestEngine;                         // Test engine user data\r\n\r\n    // Windows state\r\n    ImVector<ImGuiWindow*>  Windows;                            // Windows, sorted in display order, back to front\r\n    ImVector<ImGuiWindow*>  WindowsFocusOrder;                  // Root windows, sorted in focus order, back to front.\r\n    ImVector<ImGuiWindow*>  WindowsTempSortBuffer;              // Temporary buffer used in EndFrame() to reorder windows so parents are kept before their child\r\n    ImVector<ImGuiWindowStackData> CurrentWindowStack;\r\n    ImGuiStorage            WindowsById;                        // Map window's ImGuiID to ImGuiWindow*\r\n    int                     WindowsActiveCount;                 // Number of unique windows submitted by frame\r\n    ImVec2                  WindowsHoverPadding;                // Padding around resizable windows for which hovering on counts as hovering the window == ImMax(style.TouchExtraPadding, WINDOWS_HOVER_PADDING)\r\n    ImGuiWindow*            CurrentWindow;                      // Window being drawn into\r\n    ImGuiWindow*            HoveredWindow;                      // Window the mouse is hovering. Will typically catch mouse inputs.\r\n    ImGuiWindow*            HoveredWindowUnderMovingWindow;     // Hovered window ignoring MovingWindow. Only set if MovingWindow is set.\r\n    ImGuiWindow*            MovingWindow;                       // Track the window we clicked on (in order to preserve focus). The actual window that is moved is generally MovingWindow->RootWindow.\r\n    ImGuiWindow*            WheelingWindow;                     // Track the window we started mouse-wheeling on. Until a timer elapse or mouse has moved, generally keep scrolling the same window even if during the course of scrolling the mouse ends up hovering a child window.\r\n    ImVec2                  WheelingWindowRefMousePos;\r\n    float                   WheelingWindowTimer;\r\n\r\n    // Item/widgets state and tracking information\r\n    ImGuiID                 DebugHookIdInfo;                    // Will call core hooks: DebugHookIdInfo() from GetID functions, used by Stack Tool [next HoveredId/ActiveId to not pull in an extra cache-line]\r\n    ImGuiID                 HoveredId;                          // Hovered widget, filled during the frame\r\n    ImGuiID                 HoveredIdPreviousFrame;\r\n    bool                    HoveredIdAllowOverlap;\r\n    bool                    HoveredIdUsingMouseWheel;           // Hovered widget will use mouse wheel. Blocks scrolling the underlying window.\r\n    bool                    HoveredIdPreviousFrameUsingMouseWheel;\r\n    bool                    HoveredIdDisabled;                  // At least one widget passed the rect test, but has been discarded by disabled flag or popup inhibit. May be true even if HoveredId == 0.\r\n    float                   HoveredIdTimer;                     // Measure contiguous hovering time\r\n    float                   HoveredIdNotActiveTimer;            // Measure contiguous hovering time where the item has not been active\r\n    ImGuiID                 ActiveId;                           // Active widget\r\n    ImGuiID                 ActiveIdIsAlive;                    // Active widget has been seen this frame (we can't use a bool as the ActiveId may change within the frame)\r\n    float                   ActiveIdTimer;\r\n    bool                    ActiveIdIsJustActivated;            // Set at the time of activation for one frame\r\n    bool                    ActiveIdAllowOverlap;               // Active widget allows another widget to steal active id (generally for overlapping widgets, but not always)\r\n    bool                    ActiveIdNoClearOnFocusLoss;         // Disable losing active id if the active id window gets unfocused.\r\n    bool                    ActiveIdHasBeenPressedBefore;       // Track whether the active id led to a press (this is to allow changing between PressOnClick and PressOnRelease without pressing twice). Used by range_select branch.\r\n    bool                    ActiveIdHasBeenEditedBefore;        // Was the value associated to the widget Edited over the course of the Active state.\r\n    bool                    ActiveIdHasBeenEditedThisFrame;\r\n    bool                    ActiveIdUsingMouseWheel;            // Active widget will want to read mouse wheel. Blocks scrolling the underlying window.\r\n    ImU32                   ActiveIdUsingNavDirMask;            // Active widget will want to read those nav move requests (e.g. can activate a button and move away from it)\r\n    ImU32                   ActiveIdUsingNavInputMask;          // Active widget will want to read those nav inputs.\r\n    ImBitArrayForNamedKeys  ActiveIdUsingKeyInputMask;          // Active widget will want to read those key inputs. When we grow the ImGuiKey enum we'll need to either to order the enum to make useful keys come first, either redesign this into e.g. a small array.\r\n    ImVec2                  ActiveIdClickOffset;                // Clicked offset from upper-left corner, if applicable (currently only set by ButtonBehavior)\r\n    ImGuiWindow*            ActiveIdWindow;\r\n    ImGuiInputSource        ActiveIdSource;                     // Activating with mouse or nav (gamepad/keyboard)\r\n    int                     ActiveIdMouseButton;\r\n    ImGuiID                 ActiveIdPreviousFrame;\r\n    bool                    ActiveIdPreviousFrameIsAlive;\r\n    bool                    ActiveIdPreviousFrameHasBeenEditedBefore;\r\n    ImGuiWindow*            ActiveIdPreviousFrameWindow;\r\n    ImGuiID                 LastActiveId;                       // Store the last non-zero ActiveId, useful for animation.\r\n    float                   LastActiveIdTimer;                  // Store the last non-zero ActiveId timer since the beginning of activation, useful for animation.\r\n\r\n    // Next window/item data\r\n    ImGuiItemFlags          CurrentItemFlags;                      // == g.ItemFlagsStack.back()\r\n    ImGuiNextItemData       NextItemData;                       // Storage for SetNextItem** functions\r\n    ImGuiLastItemData       LastItemData;                       // Storage for last submitted item (setup by ItemAdd)\r\n    ImGuiNextWindowData     NextWindowData;                     // Storage for SetNextWindow** functions\r\n\r\n    // Shared stacks\r\n    ImVector<ImGuiColorMod> ColorStack;                         // Stack for PushStyleColor()/PopStyleColor() - inherited by Begin()\r\n    ImVector<ImGuiStyleMod> StyleVarStack;                      // Stack for PushStyleVar()/PopStyleVar() - inherited by Begin()\r\n    ImVector<ImFont*>       FontStack;                          // Stack for PushFont()/PopFont() - inherited by Begin()\r\n    ImVector<ImGuiID>       FocusScopeStack;                    // Stack for PushFocusScope()/PopFocusScope() - not inherited by Begin(), unless child window\r\n    ImVector<ImGuiItemFlags>ItemFlagsStack;                     // Stack for PushItemFlag()/PopItemFlag() - inherited by Begin()\r\n    ImVector<ImGuiGroupData>GroupStack;                         // Stack for BeginGroup()/EndGroup() - not inherited by Begin()\r\n    ImVector<ImGuiPopupData>OpenPopupStack;                     // Which popups are open (persistent)\r\n    ImVector<ImGuiPopupData>BeginPopupStack;                    // Which level of BeginPopup() we are in (reset every frame)\r\n    int                     BeginMenuCount;\r\n\r\n    // Viewports\r\n    ImVector<ImGuiViewportP*> Viewports;                        // Active viewports (Size==1 in 'master' branch). Each viewports hold their copy of ImDrawData.\r\n\r\n    // Gamepad/keyboard Navigation\r\n    ImGuiWindow*            NavWindow;                          // Focused window for navigation. Could be called 'FocusWindow'\r\n    ImGuiID                 NavId;                              // Focused item for navigation\r\n    ImGuiID                 NavFocusScopeId;                    // Identify a selection scope (selection code often wants to \"clear other items\" when landing on an item of the selection set)\r\n    ImGuiID                 NavActivateId;                      // ~~ (g.ActiveId == 0) && IsNavInputPressed(ImGuiNavInput_Activate) ? NavId : 0, also set when calling ActivateItem()\r\n    ImGuiID                 NavActivateDownId;                  // ~~ IsNavInputDown(ImGuiNavInput_Activate) ? NavId : 0\r\n    ImGuiID                 NavActivatePressedId;               // ~~ IsNavInputPressed(ImGuiNavInput_Activate) ? NavId : 0\r\n    ImGuiID                 NavActivateInputId;                 // ~~ IsNavInputPressed(ImGuiNavInput_Input) ? NavId : 0; ImGuiActivateFlags_PreferInput will be set and NavActivateId will be 0.\r\n    ImGuiActivateFlags      NavActivateFlags;\r\n    ImGuiID                 NavJustMovedToId;                   // Just navigated to this id (result of a successfully MoveRequest).\r\n    ImGuiID                 NavJustMovedToFocusScopeId;         // Just navigated to this focus scope id (result of a successfully MoveRequest).\r\n    ImGuiKeyModFlags        NavJustMovedToKeyMods;\r\n    ImGuiID                 NavNextActivateId;                  // Set by ActivateItem(), queued until next frame.\r\n    ImGuiActivateFlags      NavNextActivateFlags;\r\n    ImGuiInputSource        NavInputSource;                     // Keyboard or Gamepad mode? THIS WILL ONLY BE None or NavGamepad or NavKeyboard.\r\n    ImGuiNavLayer           NavLayer;                           // Layer we are navigating on. For now the system is hard-coded for 0=main contents and 1=menu/title bar, may expose layers later.\r\n    bool                    NavIdIsAlive;                       // Nav widget has been seen this frame ~~ NavRectRel is valid\r\n    bool                    NavMousePosDirty;                   // When set we will update mouse position if (io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) if set (NB: this not enabled by default)\r\n    bool                    NavDisableHighlight;                // When user starts using mouse, we hide gamepad/keyboard highlight (NB: but they are still available, which is why NavDisableHighlight isn't always != NavDisableMouseHover)\r\n    bool                    NavDisableMouseHover;               // When user starts using gamepad/keyboard, we hide mouse hovering highlight until mouse is touched again.\r\n\r\n    // Navigation: Init & Move Requests\r\n    bool                    NavAnyRequest;                      // ~~ NavMoveRequest || NavInitRequest this is to perform early out in ItemAdd()\r\n    bool                    NavInitRequest;                     // Init request for appearing window to select first item\r\n    bool                    NavInitRequestFromMove;\r\n    ImGuiID                 NavInitResultId;                    // Init request result (first item of the window, or one for which SetItemDefaultFocus() was called)\r\n    ImRect                  NavInitResultRectRel;               // Init request result rectangle (relative to parent window)\r\n    bool                    NavMoveSubmitted;                   // Move request submitted, will process result on next NewFrame()\r\n    bool                    NavMoveScoringItems;                // Move request submitted, still scoring incoming items\r\n    bool                    NavMoveForwardToNextFrame;\r\n    ImGuiNavMoveFlags       NavMoveFlags;\r\n    ImGuiScrollFlags        NavMoveScrollFlags;\r\n    ImGuiKeyModFlags        NavMoveKeyMods;\r\n    ImGuiDir                NavMoveDir;                         // Direction of the move request (left/right/up/down)\r\n    ImGuiDir                NavMoveDirForDebug;\r\n    ImGuiDir                NavMoveClipDir;                     // FIXME-NAV: Describe the purpose of this better. Might want to rename?\r\n    ImRect                  NavScoringRect;                     // Rectangle used for scoring, in screen space. Based of window->NavRectRel[], modified for directional navigation scoring.\r\n    ImRect                  NavScoringNoClipRect;               // Some nav operations (such as PageUp/PageDown) enforce a region which clipper will attempt to always keep submitted\r\n    int                     NavScoringDebugCount;               // Metrics for debugging\r\n    int                     NavTabbingDir;                      // Generally -1 or +1, 0 when tabbing without a nav id\r\n    int                     NavTabbingCounter;                  // >0 when counting items for tabbing\r\n    ImGuiNavItemData        NavMoveResultLocal;                 // Best move request candidate within NavWindow\r\n    ImGuiNavItemData        NavMoveResultLocalVisible;          // Best move request candidate within NavWindow that are mostly visible (when using ImGuiNavMoveFlags_AlsoScoreVisibleSet flag)\r\n    ImGuiNavItemData        NavMoveResultOther;                 // Best move request candidate within NavWindow's flattened hierarchy (when using ImGuiWindowFlags_NavFlattened flag)\r\n    ImGuiNavItemData        NavTabbingResultFirst;              // First tabbing request candidate within NavWindow and flattened hierarchy\r\n\r\n    // Navigation: Windowing (CTRL+TAB for list, or Menu button + keys or directional pads to move/resize)\r\n    ImGuiWindow*            NavWindowingTarget;                 // Target window when doing CTRL+Tab (or Pad Menu + FocusPrev/Next), this window is temporarily displayed top-most!\r\n    ImGuiWindow*            NavWindowingTargetAnim;             // Record of last valid NavWindowingTarget until DimBgRatio and NavWindowingHighlightAlpha becomes 0.0f, so the fade-out can stay on it.\r\n    ImGuiWindow*            NavWindowingListWindow;             // Internal window actually listing the CTRL+Tab contents\r\n    float                   NavWindowingTimer;\r\n    float                   NavWindowingHighlightAlpha;\r\n    bool                    NavWindowingToggleLayer;\r\n\r\n    // Render\r\n    float                   DimBgRatio;                         // 0.0..1.0 animation when fading in a dimming background (for modal window and CTRL+TAB list)\r\n    ImGuiMouseCursor        MouseCursor;\r\n\r\n    // Drag and Drop\r\n    bool                    DragDropActive;\r\n    bool                    DragDropWithinSource;               // Set when within a BeginDragDropXXX/EndDragDropXXX block for a drag source.\r\n    bool                    DragDropWithinTarget;               // Set when within a BeginDragDropXXX/EndDragDropXXX block for a drag target.\r\n    ImGuiDragDropFlags      DragDropSourceFlags;\r\n    int                     DragDropSourceFrameCount;\r\n    int                     DragDropMouseButton;\r\n    ImGuiPayload            DragDropPayload;\r\n    ImRect                  DragDropTargetRect;                 // Store rectangle of current target candidate (we favor small targets when overlapping)\r\n    ImGuiID                 DragDropTargetId;\r\n    ImGuiDragDropFlags      DragDropAcceptFlags;\r\n    float                   DragDropAcceptIdCurrRectSurface;    // Target item surface (we resolve overlapping targets by prioritizing the smaller surface)\r\n    ImGuiID                 DragDropAcceptIdCurr;               // Target item id (set at the time of accepting the payload)\r\n    ImGuiID                 DragDropAcceptIdPrev;               // Target item id from previous frame (we need to store this to allow for overlapping drag and drop targets)\r\n    int                     DragDropAcceptFrameCount;           // Last time a target expressed a desire to accept the source\r\n    ImGuiID                 DragDropHoldJustPressedId;          // Set when holding a payload just made ButtonBehavior() return a press.\r\n    ImVector<unsigned char> DragDropPayloadBufHeap;             // We don't expose the ImVector<> directly, ImGuiPayload only holds pointer+size\r\n    unsigned char           DragDropPayloadBufLocal[16];        // Local buffer for small payloads\r\n\r\n    // Clipper\r\n    int                             ClipperTempDataStacked;\r\n    ImVector<ImGuiListClipperData>  ClipperTempData;\r\n\r\n    // Table\r\n    ImGuiTable*                     CurrentTable;\r\n    int                             TablesTempDataStacked;      // Temporary table data size (because we leave previous instances undestructed, we generally don't use TablesTempData.Size)\r\n    ImVector<ImGuiTableTempData>    TablesTempData;             // Temporary table data (buffers reused/shared across instances, support nesting)\r\n    ImPool<ImGuiTable>              Tables;                     // Persistent table data\r\n    ImVector<float>                 TablesLastTimeActive;       // Last used timestamp of each tables (SOA, for efficient GC)\r\n    ImVector<ImDrawChannel>         DrawChannelsTempMergeBuffer;\r\n\r\n    // Tab bars\r\n    ImGuiTabBar*                    CurrentTabBar;\r\n    ImPool<ImGuiTabBar>             TabBars;\r\n    ImVector<ImGuiPtrOrIndex>       CurrentTabBarStack;\r\n    ImVector<ImGuiShrinkWidthItem>  ShrinkWidthBuffer;\r\n\r\n    // Widget state\r\n    ImVec2                  MouseLastValidPos;\r\n    ImGuiInputTextState     InputTextState;\r\n    ImFont                  InputTextPasswordFont;\r\n    ImGuiID                 TempInputId;                        // Temporary text input when CTRL+clicking on a slider, etc.\r\n    ImGuiColorEditFlags     ColorEditOptions;                   // Store user options for color edit widgets\r\n    float                   ColorEditLastHue;                   // Backup of last Hue associated to LastColor, so we can restore Hue in lossy RGB<>HSV round trips\r\n    float                   ColorEditLastSat;                   // Backup of last Saturation associated to LastColor, so we can restore Saturation in lossy RGB<>HSV round trips\r\n    ImU32                   ColorEditLastColor;                 // RGB value with alpha set to 0.\r\n    ImVec4                  ColorPickerRef;                     // Initial/reference color at the time of opening the color picker.\r\n    ImGuiComboPreviewData   ComboPreviewData;\r\n    float                   SliderCurrentAccum;                 // Accumulated slider delta when using navigation controls.\r\n    bool                    SliderCurrentAccumDirty;            // Has the accumulated slider delta changed since last time we tried to apply it?\r\n    bool                    DragCurrentAccumDirty;\r\n    float                   DragCurrentAccum;                   // Accumulator for dragging modification. Always high-precision, not rounded by end-user precision settings\r\n    float                   DragSpeedDefaultRatio;              // If speed == 0.0f, uses (max-min) * DragSpeedDefaultRatio\r\n    float                   ScrollbarClickDeltaToGrabCenter;    // Distance between mouse and center of grab box, normalized in parent space. Use storage?\r\n    float                   DisabledAlphaBackup;                // Backup for style.Alpha for BeginDisabled()\r\n    short                   DisabledStackSize;\r\n    short                   TooltipOverrideCount;\r\n    float                   TooltipSlowDelay;                   // Time before slow tooltips appears (FIXME: This is temporary until we merge in tooltip timer+priority work)\r\n    ImVector<char>          ClipboardHandlerData;               // If no custom clipboard handler is defined\r\n    ImVector<ImGuiID>       MenusIdSubmittedThisFrame;          // A list of menu IDs that were rendered at least once\r\n\r\n    // Platform support\r\n    ImGuiPlatformImeData    PlatformImeData;                    // Data updated by current frame\r\n    ImGuiPlatformImeData    PlatformImeDataPrev;                // Previous frame data (when changing we will call io.SetPlatformImeDataFn\r\n    char                    PlatformLocaleDecimalPoint;         // '.' or *localeconv()->decimal_point\r\n\r\n    // Settings\r\n    bool                    SettingsLoaded;\r\n    float                   SettingsDirtyTimer;                 // Save .ini Settings to memory when time reaches zero\r\n    ImGuiTextBuffer         SettingsIniData;                    // In memory .ini settings\r\n    ImVector<ImGuiSettingsHandler>      SettingsHandlers;       // List of .ini settings handlers\r\n    ImChunkStream<ImGuiWindowSettings>  SettingsWindows;        // ImGuiWindow .ini settings entries\r\n    ImChunkStream<ImGuiTableSettings>   SettingsTables;         // ImGuiTable .ini settings entries\r\n    ImVector<ImGuiContextHook>          Hooks;                  // Hooks for extensions (e.g. test engine)\r\n    ImGuiID                             HookIdNext;             // Next available HookId\r\n\r\n    // Capture/Logging\r\n    bool                    LogEnabled;                         // Currently capturing\r\n    ImGuiLogType            LogType;                            // Capture target\r\n    ImFileHandle            LogFile;                            // If != NULL log to stdout/ file\r\n    ImGuiTextBuffer         LogBuffer;                          // Accumulation buffer when log to clipboard. This is pointer so our GImGui static constructor doesn't call heap allocators.\r\n    const char*             LogNextPrefix;\r\n    const char*             LogNextSuffix;\r\n    float                   LogLinePosY;\r\n    bool                    LogLineFirstItem;\r\n    int                     LogDepthRef;\r\n    int                     LogDepthToExpand;\r\n    int                     LogDepthToExpandDefault;            // Default/stored value for LogDepthMaxExpand if not specified in the LogXXX function call.\r\n\r\n    // Debug Tools\r\n    bool                    DebugItemPickerActive;              // Item picker is active (started with DebugStartItemPicker())\r\n    ImGuiID                 DebugItemPickerBreakId;             // Will call IM_DEBUG_BREAK() when encountering this ID\r\n    ImGuiMetricsConfig      DebugMetricsConfig;\r\n    ImGuiStackTool          DebugStackTool;\r\n\r\n    // Misc\r\n    float                   FramerateSecPerFrame[120];          // Calculate estimate of framerate for user over the last 2 seconds.\r\n    int                     FramerateSecPerFrameIdx;\r\n    int                     FramerateSecPerFrameCount;\r\n    float                   FramerateSecPerFrameAccum;\r\n    int                     WantCaptureMouseNextFrame;          // Explicit capture via CaptureKeyboardFromApp()/CaptureMouseFromApp() sets those flags\r\n    int                     WantCaptureKeyboardNextFrame;\r\n    int                     WantTextInputNextFrame;\r\n    char                    TempBuffer[1024 * 3 + 1];           // Temporary text buffer\r\n\r\n    ImGuiContext(ImFontAtlas* shared_font_atlas)\r\n    {\r\n        Initialized = false;\r\n        FontAtlasOwnedByContext = shared_font_atlas ? false : true;\r\n        Font = NULL;\r\n        FontSize = FontBaseSize = 0.0f;\r\n        IO.Fonts = shared_font_atlas ? shared_font_atlas : IM_NEW(ImFontAtlas)();\r\n        Time = 0.0f;\r\n        FrameCount = 0;\r\n        FrameCountEnded = FrameCountRendered = -1;\r\n        WithinFrameScope = WithinFrameScopeWithImplicitWindow = WithinEndChild = false;\r\n        GcCompactAll = false;\r\n        TestEngineHookItems = false;\r\n        TestEngine = NULL;\r\n\r\n        WindowsActiveCount = 0;\r\n        CurrentWindow = NULL;\r\n        HoveredWindow = NULL;\r\n        HoveredWindowUnderMovingWindow = NULL;\r\n        MovingWindow = NULL;\r\n        WheelingWindow = NULL;\r\n        WheelingWindowTimer = 0.0f;\r\n\r\n        DebugHookIdInfo = 0;\r\n        HoveredId = HoveredIdPreviousFrame = 0;\r\n        HoveredIdAllowOverlap = false;\r\n        HoveredIdUsingMouseWheel = HoveredIdPreviousFrameUsingMouseWheel = false;\r\n        HoveredIdDisabled = false;\r\n        HoveredIdTimer = HoveredIdNotActiveTimer = 0.0f;\r\n        ActiveId = 0;\r\n        ActiveIdIsAlive = 0;\r\n        ActiveIdTimer = 0.0f;\r\n        ActiveIdIsJustActivated = false;\r\n        ActiveIdAllowOverlap = false;\r\n        ActiveIdNoClearOnFocusLoss = false;\r\n        ActiveIdHasBeenPressedBefore = false;\r\n        ActiveIdHasBeenEditedBefore = false;\r\n        ActiveIdHasBeenEditedThisFrame = false;\r\n        ActiveIdUsingMouseWheel = false;\r\n        ActiveIdUsingNavDirMask = 0x00;\r\n        ActiveIdUsingNavInputMask = 0x00;\r\n        ActiveIdUsingKeyInputMask.ClearAllBits();\r\n        ActiveIdClickOffset = ImVec2(-1, -1);\r\n        ActiveIdWindow = NULL;\r\n        ActiveIdSource = ImGuiInputSource_None;\r\n        ActiveIdMouseButton = -1;\r\n        ActiveIdPreviousFrame = 0;\r\n        ActiveIdPreviousFrameIsAlive = false;\r\n        ActiveIdPreviousFrameHasBeenEditedBefore = false;\r\n        ActiveIdPreviousFrameWindow = NULL;\r\n        LastActiveId = 0;\r\n        LastActiveIdTimer = 0.0f;\r\n\r\n        CurrentItemFlags = ImGuiItemFlags_None;\r\n        BeginMenuCount = 0;\r\n\r\n        NavWindow = NULL;\r\n        NavId = NavFocusScopeId = NavActivateId = NavActivateDownId = NavActivatePressedId = NavActivateInputId = 0;\r\n        NavJustMovedToId = NavJustMovedToFocusScopeId = NavNextActivateId = 0;\r\n        NavActivateFlags = NavNextActivateFlags = ImGuiActivateFlags_None;\r\n        NavJustMovedToKeyMods = ImGuiKeyModFlags_None;\r\n        NavInputSource = ImGuiInputSource_None;\r\n        NavLayer = ImGuiNavLayer_Main;\r\n        NavIdIsAlive = false;\r\n        NavMousePosDirty = false;\r\n        NavDisableHighlight = true;\r\n        NavDisableMouseHover = false;\r\n        NavAnyRequest = false;\r\n        NavInitRequest = false;\r\n        NavInitRequestFromMove = false;\r\n        NavInitResultId = 0;\r\n        NavMoveSubmitted = false;\r\n        NavMoveScoringItems = false;\r\n        NavMoveForwardToNextFrame = false;\r\n        NavMoveFlags = ImGuiNavMoveFlags_None;\r\n        NavMoveScrollFlags = ImGuiScrollFlags_None;\r\n        NavMoveKeyMods = ImGuiKeyModFlags_None;\r\n        NavMoveDir = NavMoveDirForDebug = NavMoveClipDir = ImGuiDir_None;\r\n        NavScoringDebugCount = 0;\r\n        NavTabbingDir = 0;\r\n        NavTabbingCounter = 0;\r\n\r\n        NavWindowingTarget = NavWindowingTargetAnim = NavWindowingListWindow = NULL;\r\n        NavWindowingTimer = NavWindowingHighlightAlpha = 0.0f;\r\n        NavWindowingToggleLayer = false;\r\n\r\n        DimBgRatio = 0.0f;\r\n        MouseCursor = ImGuiMouseCursor_Arrow;\r\n\r\n        DragDropActive = DragDropWithinSource = DragDropWithinTarget = false;\r\n        DragDropSourceFlags = ImGuiDragDropFlags_None;\r\n        DragDropSourceFrameCount = -1;\r\n        DragDropMouseButton = -1;\r\n        DragDropTargetId = 0;\r\n        DragDropAcceptFlags = ImGuiDragDropFlags_None;\r\n        DragDropAcceptIdCurrRectSurface = 0.0f;\r\n        DragDropAcceptIdPrev = DragDropAcceptIdCurr = 0;\r\n        DragDropAcceptFrameCount = -1;\r\n        DragDropHoldJustPressedId = 0;\r\n        memset(DragDropPayloadBufLocal, 0, sizeof(DragDropPayloadBufLocal));\r\n\r\n        ClipperTempDataStacked = 0;\r\n\r\n        CurrentTable = NULL;\r\n        TablesTempDataStacked = 0;\r\n        CurrentTabBar = NULL;\r\n\r\n        TempInputId = 0;\r\n        ColorEditOptions = ImGuiColorEditFlags_DefaultOptions_;\r\n        ColorEditLastHue = ColorEditLastSat = 0.0f;\r\n        ColorEditLastColor = 0;\r\n        SliderCurrentAccum = 0.0f;\r\n        SliderCurrentAccumDirty = false;\r\n        DragCurrentAccumDirty = false;\r\n        DragCurrentAccum = 0.0f;\r\n        DragSpeedDefaultRatio = 1.0f / 100.0f;\r\n        DisabledAlphaBackup = 0.0f;\r\n        DisabledStackSize = 0;\r\n        ScrollbarClickDeltaToGrabCenter = 0.0f;\r\n        TooltipOverrideCount = 0;\r\n        TooltipSlowDelay = 0.50f;\r\n\r\n        PlatformImeData.InputPos = ImVec2(0.0f, 0.0f);\r\n        PlatformImeDataPrev.InputPos = ImVec2(-1.0f, -1.0f); // Different to ensure initial submission\r\n        PlatformLocaleDecimalPoint = '.';\r\n\r\n        SettingsLoaded = false;\r\n        SettingsDirtyTimer = 0.0f;\r\n        HookIdNext = 0;\r\n\r\n        LogEnabled = false;\r\n        LogType = ImGuiLogType_None;\r\n        LogNextPrefix = LogNextSuffix = NULL;\r\n        LogFile = NULL;\r\n        LogLinePosY = FLT_MAX;\r\n        LogLineFirstItem = false;\r\n        LogDepthRef = 0;\r\n        LogDepthToExpand = LogDepthToExpandDefault = 2;\r\n\r\n        DebugItemPickerActive = false;\r\n        DebugItemPickerBreakId = 0;\r\n\r\n        memset(FramerateSecPerFrame, 0, sizeof(FramerateSecPerFrame));\r\n        FramerateSecPerFrameIdx = FramerateSecPerFrameCount = 0;\r\n        FramerateSecPerFrameAccum = 0.0f;\r\n        WantCaptureMouseNextFrame = WantCaptureKeyboardNextFrame = WantTextInputNextFrame = -1;\r\n        memset(TempBuffer, 0, sizeof(TempBuffer));\r\n    }\r\n};\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] ImGuiWindowTempData, ImGuiWindow\r\n//-----------------------------------------------------------------------------\r\n\r\n// Transient per-window data, reset at the beginning of the frame. This used to be called ImGuiDrawContext, hence the DC variable name in ImGuiWindow.\r\n// (That's theory, in practice the delimitation between ImGuiWindow and ImGuiWindowTempData is quite tenuous and could be reconsidered..)\r\n// (This doesn't need a constructor because we zero-clear it as part of ImGuiWindow and all frame-temporary data are setup on Begin)\r\nstruct IMGUI_API ImGuiWindowTempData\r\n{\r\n    // Layout\r\n    ImVec2                  CursorPos;              // Current emitting position, in absolute coordinates.\r\n    ImVec2                  CursorPosPrevLine;\r\n    ImVec2                  CursorStartPos;         // Initial position after Begin(), generally ~ window position + WindowPadding.\r\n    ImVec2                  CursorMaxPos;           // Used to implicitly calculate ContentSize at the beginning of next frame, for scrolling range and auto-resize. Always growing during the frame.\r\n    ImVec2                  IdealMaxPos;            // Used to implicitly calculate ContentSizeIdeal at the beginning of next frame, for auto-resize only. Always growing during the frame.\r\n    ImVec2                  CurrLineSize;\r\n    ImVec2                  PrevLineSize;\r\n    float                   CurrLineTextBaseOffset; // Baseline offset (0.0f by default on a new line, generally == style.FramePadding.y when a framed item has been added).\r\n    float                   PrevLineTextBaseOffset;\r\n    ImVec1                  Indent;                 // Indentation / start position from left of window (increased by TreePush/TreePop, etc.)\r\n    ImVec1                  ColumnsOffset;          // Offset to the current column (if ColumnsCurrent > 0). FIXME: This and the above should be a stack to allow use cases like Tree->Column->Tree. Need revamp columns API.\r\n    ImVec1                  GroupOffset;\r\n    ImVec2                  CursorStartPosLossyness;// Record the loss of precision of CursorStartPos due to really large scrolling amount. This is used by clipper to compensentate and fix the most common use case of large scroll area.\r\n\r\n    // Keyboard/Gamepad navigation\r\n    ImGuiNavLayer           NavLayerCurrent;        // Current layer, 0..31 (we currently only use 0..1)\r\n    short                   NavLayersActiveMask;    // Which layers have been written to (result from previous frame)\r\n    short                   NavLayersActiveMaskNext;// Which layers have been written to (accumulator for current frame)\r\n    ImGuiID                 NavFocusScopeIdCurrent; // Current focus scope ID while appending\r\n    bool                    NavHideHighlightOneFrame;\r\n    bool                    NavHasScroll;           // Set when scrolling can be used (ScrollMax > 0.0f)\r\n\r\n    // Miscellaneous\r\n    bool                    MenuBarAppending;       // FIXME: Remove this\r\n    ImVec2                  MenuBarOffset;          // MenuBarOffset.x is sort of equivalent of a per-layer CursorPos.x, saved/restored as we switch to the menu bar. The only situation when MenuBarOffset.y is > 0 if when (SafeAreaPadding.y > FramePadding.y), often used on TVs.\r\n    ImGuiMenuColumns        MenuColumns;            // Simplified columns storage for menu items measurement\r\n    int                     TreeDepth;              // Current tree depth.\r\n    ImU32                   TreeJumpToParentOnPopMask; // Store a copy of !g.NavIdIsAlive for TreeDepth 0..31.. Could be turned into a ImU64 if necessary.\r\n    ImVector<ImGuiWindow*>  ChildWindows;\r\n    ImGuiStorage*           StateStorage;           // Current persistent per-window storage (store e.g. tree node open/close state)\r\n    ImGuiOldColumns*        CurrentColumns;         // Current columns set\r\n    int                     CurrentTableIdx;        // Current table index (into g.Tables)\r\n    ImGuiLayoutType         LayoutType;\r\n    ImGuiLayoutType         ParentLayoutType;       // Layout type of parent window at the time of Begin()\r\n\r\n    // Local parameters stacks\r\n    // We store the current settings outside of the vectors to increase memory locality (reduce cache misses). The vectors are rarely modified. Also it allows us to not heap allocate for short-lived windows which are not using those settings.\r\n    float                   ItemWidth;              // Current item width (>0.0: width in pixels, <0.0: align xx pixels to the right of window).\r\n    float                   TextWrapPos;            // Current text wrap pos.\r\n    ImVector<float>         ItemWidthStack;         // Store item widths to restore (attention: .back() is not == ItemWidth)\r\n    ImVector<float>         TextWrapPosStack;       // Store text wrap pos to restore (attention: .back() is not == TextWrapPos)\r\n};\r\n\r\n// Storage for one window\r\nstruct IMGUI_API ImGuiWindow\r\n{\r\n    char*                   Name;                               // Window name, owned by the window.\r\n    ImGuiID                 ID;                                 // == ImHashStr(Name)\r\n    ImGuiWindowFlags        Flags;                              // See enum ImGuiWindowFlags_\r\n    ImVec2                  Pos;                                // Position (always rounded-up to nearest pixel)\r\n    ImVec2                  Size;                               // Current size (==SizeFull or collapsed title bar size)\r\n    ImVec2                  SizeFull;                           // Size when non collapsed\r\n    ImVec2                  ContentSize;                        // Size of contents/scrollable client area (calculated from the extents reach of the cursor) from previous frame. Does not include window decoration or window padding.\r\n    ImVec2                  ContentSizeIdeal;\r\n    ImVec2                  ContentSizeExplicit;                // Size of contents/scrollable client area explicitly request by the user via SetNextWindowContentSize().\r\n    ImVec2                  WindowPadding;                      // Window padding at the time of Begin().\r\n    float                   WindowRounding;                     // Window rounding at the time of Begin(). May be clamped lower to avoid rendering artifacts with title bar, menu bar etc.\r\n    float                   WindowBorderSize;                   // Window border size at the time of Begin().\r\n    int                     NameBufLen;                         // Size of buffer storing Name. May be larger than strlen(Name)!\r\n    ImGuiID                 MoveId;                             // == window->GetID(\"#MOVE\")\r\n    ImGuiID                 ChildId;                            // ID of corresponding item in parent window (for navigation to return from child window to parent window)\r\n    ImVec2                  Scroll;\r\n    ImVec2                  ScrollMax;\r\n    ImVec2                  ScrollTarget;                       // target scroll position. stored as cursor position with scrolling canceled out, so the highest point is always 0.0f. (FLT_MAX for no change)\r\n    ImVec2                  ScrollTargetCenterRatio;            // 0.0f = scroll so that target position is at top, 0.5f = scroll so that target position is centered\r\n    ImVec2                  ScrollTargetEdgeSnapDist;           // 0.0f = no snapping, >0.0f snapping threshold\r\n    ImVec2                  ScrollbarSizes;                     // Size taken by each scrollbars on their smaller axis. Pay attention! ScrollbarSizes.x == width of the vertical scrollbar, ScrollbarSizes.y = height of the horizontal scrollbar.\r\n    bool                    ScrollbarX, ScrollbarY;             // Are scrollbars visible?\r\n    bool                    Active;                             // Set to true on Begin(), unless Collapsed\r\n    bool                    WasActive;\r\n    bool                    WriteAccessed;                      // Set to true when any widget access the current window\r\n    bool                    Collapsed;                          // Set when collapsing window to become only title-bar\r\n    bool                    WantCollapseToggle;\r\n    bool                    SkipItems;                          // Set when items can safely be all clipped (e.g. window not visible or collapsed)\r\n    bool                    Appearing;                          // Set during the frame where the window is appearing (or re-appearing)\r\n    bool                    Hidden;                             // Do not display (== HiddenFrames*** > 0)\r\n    bool                    IsFallbackWindow;                   // Set on the \"Debug##Default\" window.\r\n    bool                    IsExplicitChild;                    // Set when passed _ChildWindow, left to false by BeginDocked()\r\n    bool                    HasCloseButton;                     // Set when the window has a close button (p_open != NULL)\r\n    signed char             ResizeBorderHeld;                   // Current border being held for resize (-1: none, otherwise 0-3)\r\n    short                   BeginCount;                         // Number of Begin() during the current frame (generally 0 or 1, 1+ if appending via multiple Begin/End pairs)\r\n    short                   BeginOrderWithinParent;             // Begin() order within immediate parent window, if we are a child window. Otherwise 0.\r\n    short                   BeginOrderWithinContext;            // Begin() order within entire imgui context. This is mostly used for debugging submission order related issues.\r\n    short                   FocusOrder;                         // Order within WindowsFocusOrder[], altered when windows are focused.\r\n    ImGuiID                 PopupId;                            // ID in the popup stack when this window is used as a popup/menu (because we use generic Name/ID for recycling)\r\n    ImS8                    AutoFitFramesX, AutoFitFramesY;\r\n    ImS8                    AutoFitChildAxises;\r\n    bool                    AutoFitOnlyGrows;\r\n    ImGuiDir                AutoPosLastDirection;\r\n    ImS8                    HiddenFramesCanSkipItems;           // Hide the window for N frames\r\n    ImS8                    HiddenFramesCannotSkipItems;        // Hide the window for N frames while allowing items to be submitted so we can measure their size\r\n    ImS8                    HiddenFramesForRenderOnly;          // Hide the window until frame N at Render() time only\r\n    ImS8                    DisableInputsFrames;                // Disable window interactions for N frames\r\n    ImGuiCond               SetWindowPosAllowFlags : 8;         // store acceptable condition flags for SetNextWindowPos() use.\r\n    ImGuiCond               SetWindowSizeAllowFlags : 8;        // store acceptable condition flags for SetNextWindowSize() use.\r\n    ImGuiCond               SetWindowCollapsedAllowFlags : 8;   // store acceptable condition flags for SetNextWindowCollapsed() use.\r\n    ImVec2                  SetWindowPosVal;                    // store window position when using a non-zero Pivot (position set needs to be processed when we know the window size)\r\n    ImVec2                  SetWindowPosPivot;                  // store window pivot for positioning. ImVec2(0, 0) when positioning from top-left corner; ImVec2(0.5f, 0.5f) for centering; ImVec2(1, 1) for bottom right.\r\n\r\n    ImVector<ImGuiID>       IDStack;                            // ID stack. ID are hashes seeded with the value at the top of the stack. (In theory this should be in the TempData structure)\r\n    ImGuiWindowTempData     DC;                                 // Temporary per-window data, reset at the beginning of the frame. This used to be called ImGuiDrawContext, hence the \"DC\" variable name.\r\n\r\n    // The best way to understand what those rectangles are is to use the 'Metrics->Tools->Show Windows Rectangles' viewer.\r\n    // The main 'OuterRect', omitted as a field, is window->Rect().\r\n    ImRect                  OuterRectClipped;                   // == Window->Rect() just after setup in Begin(). == window->Rect() for root window.\r\n    ImRect                  InnerRect;                          // Inner rectangle (omit title bar, menu bar, scroll bar)\r\n    ImRect                  InnerClipRect;                      // == InnerRect shrunk by WindowPadding*0.5f on each side, clipped within viewport or parent clip rect.\r\n    ImRect                  WorkRect;                           // Initially covers the whole scrolling region. Reduced by containers e.g columns/tables when active. Shrunk by WindowPadding*1.0f on each side. This is meant to replace ContentRegionRect over time (from 1.71+ onward).\r\n    ImRect                  ParentWorkRect;                     // Backup of WorkRect before entering a container such as columns/tables. Used by e.g. SpanAllColumns functions to easily access. Stacked containers are responsible for maintaining this. // FIXME-WORKRECT: Could be a stack?\r\n    ImRect                  ClipRect;                           // Current clipping/scissoring rectangle, evolve as we are using PushClipRect(), etc. == DrawList->clip_rect_stack.back().\r\n    ImRect                  ContentRegionRect;                  // FIXME: This is currently confusing/misleading. It is essentially WorkRect but not handling of scrolling. We currently rely on it as right/bottom aligned sizing operation need some size to rely on.\r\n    ImVec2ih                HitTestHoleSize;                    // Define an optional rectangular hole where mouse will pass-through the window.\r\n    ImVec2ih                HitTestHoleOffset;\r\n\r\n    int                     LastFrameActive;                    // Last frame number the window was Active.\r\n    float                   LastTimeActive;                     // Last timestamp the window was Active (using float as we don't need high precision there)\r\n    float                   ItemWidthDefault;\r\n    ImGuiStorage            StateStorage;\r\n    ImVector<ImGuiOldColumns> ColumnsStorage;\r\n    float                   FontWindowScale;                    // User scale multiplier per-window, via SetWindowFontScale()\r\n    int                     SettingsOffset;                     // Offset into SettingsWindows[] (offsets are always valid as we only grow the array from the back)\r\n\r\n    ImDrawList*             DrawList;                           // == &DrawListInst (for backward compatibility reason with code using imgui_internal.h we keep this a pointer)\r\n    ImDrawList              DrawListInst;\r\n    ImGuiWindow*            ParentWindow;                       // If we are a child _or_ popup _or_ docked window, this is pointing to our parent. Otherwise NULL.\r\n    ImGuiWindow*            ParentWindowInBeginStack;\r\n    ImGuiWindow*            RootWindow;                         // Point to ourself or first ancestor that is not a child window. Doesn't cross through popups/dock nodes.\r\n    ImGuiWindow*            RootWindowPopupTree;                // Point to ourself or first ancestor that is not a child window. Cross through popups parent<>child.\r\n    ImGuiWindow*            RootWindowForTitleBarHighlight;     // Point to ourself or first ancestor which will display TitleBgActive color when this window is active.\r\n    ImGuiWindow*            RootWindowForNav;                   // Point to ourself or first ancestor which doesn't have the NavFlattened flag.\r\n\r\n    ImGuiWindow*            NavLastChildNavWindow;              // When going to the menu bar, we remember the child window we came from. (This could probably be made implicit if we kept g.Windows sorted by last focused including child window.)\r\n    ImGuiID                 NavLastIds[ImGuiNavLayer_COUNT];    // Last known NavId for this window, per layer (0/1)\r\n    ImRect                  NavRectRel[ImGuiNavLayer_COUNT];    // Reference rectangle, in window relative space\r\n\r\n    int                     MemoryDrawListIdxCapacity;          // Backup of last idx/vtx count, so when waking up the window we can preallocate and avoid iterative alloc/copy\r\n    int                     MemoryDrawListVtxCapacity;\r\n    bool                    MemoryCompacted;                    // Set when window extraneous data have been garbage collected\r\n\r\npublic:\r\n    ImGuiWindow(ImGuiContext* context, const char* name);\r\n    ~ImGuiWindow();\r\n\r\n    ImGuiID     GetID(const char* str, const char* str_end = NULL);\r\n    ImGuiID     GetID(const void* ptr);\r\n    ImGuiID     GetID(int n);\r\n    ImGuiID     GetIDNoKeepAlive(const char* str, const char* str_end = NULL);\r\n    ImGuiID     GetIDNoKeepAlive(const void* ptr);\r\n    ImGuiID     GetIDNoKeepAlive(int n);\r\n    ImGuiID     GetIDFromRectangle(const ImRect& r_abs);\r\n\r\n    // We don't use g.FontSize because the window may be != g.CurrentWidow.\r\n    ImRect      Rect() const            { return ImRect(Pos.x, Pos.y, Pos.x + Size.x, Pos.y + Size.y); }\r\n    float       CalcFontSize() const    { ImGuiContext& g = *GImGui; float scale = g.FontBaseSize * FontWindowScale; if (ParentWindow) scale *= ParentWindow->FontWindowScale; return scale; }\r\n    float       TitleBarHeight() const  { ImGuiContext& g = *GImGui; return (Flags & ImGuiWindowFlags_NoTitleBar) ? 0.0f : CalcFontSize() + g.Style.FramePadding.y * 2.0f; }\r\n    ImRect      TitleBarRect() const    { return ImRect(Pos, ImVec2(Pos.x + SizeFull.x, Pos.y + TitleBarHeight())); }\r\n    float       MenuBarHeight() const   { ImGuiContext& g = *GImGui; return (Flags & ImGuiWindowFlags_MenuBar) ? DC.MenuBarOffset.y + CalcFontSize() + g.Style.FramePadding.y * 2.0f : 0.0f; }\r\n    ImRect      MenuBarRect() const     { float y1 = Pos.y + TitleBarHeight(); return ImRect(Pos.x, y1, Pos.x + SizeFull.x, y1 + MenuBarHeight()); }\r\n};\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Tab bar, Tab item support\r\n//-----------------------------------------------------------------------------\r\n\r\n// Extend ImGuiTabBarFlags_\r\nenum ImGuiTabBarFlagsPrivate_\r\n{\r\n    ImGuiTabBarFlags_DockNode                   = 1 << 20,  // Part of a dock node [we don't use this in the master branch but it facilitate branch syncing to keep this around]\r\n    ImGuiTabBarFlags_IsFocused                  = 1 << 21,\r\n    ImGuiTabBarFlags_SaveSettings               = 1 << 22   // FIXME: Settings are handled by the docking system, this only request the tab bar to mark settings dirty when reordering tabs\r\n};\r\n\r\n// Extend ImGuiTabItemFlags_\r\nenum ImGuiTabItemFlagsPrivate_\r\n{\r\n    ImGuiTabItemFlags_SectionMask_              = ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_Trailing,\r\n    ImGuiTabItemFlags_NoCloseButton             = 1 << 20,  // Track whether p_open was set or not (we'll need this info on the next frame to recompute ContentWidth during layout)\r\n    ImGuiTabItemFlags_Button                    = 1 << 21   // Used by TabItemButton, change the tab item behavior to mimic a button\r\n};\r\n\r\n// Storage for one active tab item (sizeof() 40 bytes)\r\nstruct ImGuiTabItem\r\n{\r\n    ImGuiID             ID;\r\n    ImGuiTabItemFlags   Flags;\r\n    int                 LastFrameVisible;\r\n    int                 LastFrameSelected;      // This allows us to infer an ordered list of the last activated tabs with little maintenance\r\n    float               Offset;                 // Position relative to beginning of tab\r\n    float               Width;                  // Width currently displayed\r\n    float               ContentWidth;           // Width of label, stored during BeginTabItem() call\r\n    ImS32               NameOffset;             // When Window==NULL, offset to name within parent ImGuiTabBar::TabsNames\r\n    ImS16               BeginOrder;             // BeginTabItem() order, used to re-order tabs after toggling ImGuiTabBarFlags_Reorderable\r\n    ImS16               IndexDuringLayout;      // Index only used during TabBarLayout()\r\n    bool                WantClose;              // Marked as closed by SetTabItemClosed()\r\n\r\n    ImGuiTabItem()      { memset(this, 0, sizeof(*this)); LastFrameVisible = LastFrameSelected = -1; NameOffset = -1; BeginOrder = IndexDuringLayout = -1; }\r\n};\r\n\r\n// Storage for a tab bar (sizeof() 152 bytes)\r\nstruct IMGUI_API ImGuiTabBar\r\n{\r\n    ImVector<ImGuiTabItem> Tabs;\r\n    ImGuiTabBarFlags    Flags;\r\n    ImGuiID             ID;                     // Zero for tab-bars used by docking\r\n    ImGuiID             SelectedTabId;          // Selected tab/window\r\n    ImGuiID             NextSelectedTabId;      // Next selected tab/window. Will also trigger a scrolling animation\r\n    ImGuiID             VisibleTabId;           // Can occasionally be != SelectedTabId (e.g. when previewing contents for CTRL+TAB preview)\r\n    int                 CurrFrameVisible;\r\n    int                 PrevFrameVisible;\r\n    ImRect              BarRect;\r\n    float               CurrTabsContentsHeight;\r\n    float               PrevTabsContentsHeight; // Record the height of contents submitted below the tab bar\r\n    float               WidthAllTabs;           // Actual width of all tabs (locked during layout)\r\n    float               WidthAllTabsIdeal;      // Ideal width if all tabs were visible and not clipped\r\n    float               ScrollingAnim;\r\n    float               ScrollingTarget;\r\n    float               ScrollingTargetDistToVisibility;\r\n    float               ScrollingSpeed;\r\n    float               ScrollingRectMinX;\r\n    float               ScrollingRectMaxX;\r\n    ImGuiID             ReorderRequestTabId;\r\n    ImS16               ReorderRequestOffset;\r\n    ImS8                BeginCount;\r\n    bool                WantLayout;\r\n    bool                VisibleTabWasSubmitted;\r\n    bool                TabsAddedNew;           // Set to true when a new tab item or button has been added to the tab bar during last frame\r\n    ImS16               TabsActiveCount;        // Number of tabs submitted this frame.\r\n    ImS16               LastTabItemIdx;         // Index of last BeginTabItem() tab for use by EndTabItem()\r\n    float               ItemSpacingY;\r\n    ImVec2              FramePadding;           // style.FramePadding locked at the time of BeginTabBar()\r\n    ImVec2              BackupCursorPos;\r\n    ImGuiTextBuffer     TabsNames;              // For non-docking tab bar we re-append names in a contiguous buffer.\r\n\r\n    ImGuiTabBar();\r\n    int                 GetTabOrder(const ImGuiTabItem* tab) const  { return Tabs.index_from_ptr(tab); }\r\n    const char*         GetTabName(const ImGuiTabItem* tab) const\r\n    {\r\n        IM_ASSERT(tab->NameOffset != -1 && tab->NameOffset < TabsNames.Buf.Size);\r\n        return TabsNames.Buf.Data + tab->NameOffset;\r\n    }\r\n};\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Table support\r\n//-----------------------------------------------------------------------------\r\n\r\n#define IM_COL32_DISABLE                IM_COL32(0,0,0,1)   // Special sentinel code which cannot be used as a regular color.\r\n#define IMGUI_TABLE_MAX_COLUMNS         64                  // sizeof(ImU64) * 8. This is solely because we frequently encode columns set in a ImU64.\r\n#define IMGUI_TABLE_MAX_DRAW_CHANNELS   (4 + 64 * 2)        // See TableSetupDrawChannels()\r\n\r\n// Our current column maximum is 64 but we may raise that in the future.\r\ntypedef ImS8 ImGuiTableColumnIdx;\r\ntypedef ImU8 ImGuiTableDrawChannelIdx;\r\n\r\n// [Internal] sizeof() ~ 104\r\n// We use the terminology \"Enabled\" to refer to a column that is not Hidden by user/api.\r\n// We use the terminology \"Clipped\" to refer to a column that is out of sight because of scrolling/clipping.\r\n// This is in contrast with some user-facing api such as IsItemVisible() / IsRectVisible() which use \"Visible\" to mean \"not clipped\".\r\nstruct ImGuiTableColumn\r\n{\r\n    ImGuiTableColumnFlags   Flags;                          // Flags after some patching (not directly same as provided by user). See ImGuiTableColumnFlags_\r\n    float                   WidthGiven;                     // Final/actual width visible == (MaxX - MinX), locked in TableUpdateLayout(). May be > WidthRequest to honor minimum width, may be < WidthRequest to honor shrinking columns down in tight space.\r\n    float                   MinX;                           // Absolute positions\r\n    float                   MaxX;\r\n    float                   WidthRequest;                   // Master width absolute value when !(Flags & _WidthStretch). When Stretch this is derived every frame from StretchWeight in TableUpdateLayout()\r\n    float                   WidthAuto;                      // Automatic width\r\n    float                   StretchWeight;                  // Master width weight when (Flags & _WidthStretch). Often around ~1.0f initially.\r\n    float                   InitStretchWeightOrWidth;       // Value passed to TableSetupColumn(). For Width it is a content width (_without padding_).\r\n    ImRect                  ClipRect;                       // Clipping rectangle for the column\r\n    ImGuiID                 UserID;                         // Optional, value passed to TableSetupColumn()\r\n    float                   WorkMinX;                       // Contents region min ~(MinX + CellPaddingX + CellSpacingX1) == cursor start position when entering column\r\n    float                   WorkMaxX;                       // Contents region max ~(MaxX - CellPaddingX - CellSpacingX2)\r\n    float                   ItemWidth;                      // Current item width for the column, preserved across rows\r\n    float                   ContentMaxXFrozen;              // Contents maximum position for frozen rows (apart from headers), from which we can infer content width.\r\n    float                   ContentMaxXUnfrozen;\r\n    float                   ContentMaxXHeadersUsed;         // Contents maximum position for headers rows (regardless of freezing). TableHeader() automatically softclip itself + report ideal desired size, to avoid creating extraneous draw calls\r\n    float                   ContentMaxXHeadersIdeal;\r\n    ImS16                   NameOffset;                     // Offset into parent ColumnsNames[]\r\n    ImGuiTableColumnIdx     DisplayOrder;                   // Index within Table's IndexToDisplayOrder[] (column may be reordered by users)\r\n    ImGuiTableColumnIdx     IndexWithinEnabledSet;          // Index within enabled/visible set (<= IndexToDisplayOrder)\r\n    ImGuiTableColumnIdx     PrevEnabledColumn;              // Index of prev enabled/visible column within Columns[], -1 if first enabled/visible column\r\n    ImGuiTableColumnIdx     NextEnabledColumn;              // Index of next enabled/visible column within Columns[], -1 if last enabled/visible column\r\n    ImGuiTableColumnIdx     SortOrder;                      // Index of this column within sort specs, -1 if not sorting on this column, 0 for single-sort, may be >0 on multi-sort\r\n    ImGuiTableDrawChannelIdx DrawChannelCurrent;            // Index within DrawSplitter.Channels[]\r\n    ImGuiTableDrawChannelIdx DrawChannelFrozen;             // Draw channels for frozen rows (often headers)\r\n    ImGuiTableDrawChannelIdx DrawChannelUnfrozen;           // Draw channels for unfrozen rows\r\n    bool                    IsEnabled;                      // IsUserEnabled && (Flags & ImGuiTableColumnFlags_Disabled) == 0\r\n    bool                    IsUserEnabled;                  // Is the column not marked Hidden by the user? (unrelated to being off view, e.g. clipped by scrolling).\r\n    bool                    IsUserEnabledNextFrame;\r\n    bool                    IsVisibleX;                     // Is actually in view (e.g. overlapping the host window clipping rectangle, not scrolled).\r\n    bool                    IsVisibleY;\r\n    bool                    IsRequestOutput;                // Return value for TableSetColumnIndex() / TableNextColumn(): whether we request user to output contents or not.\r\n    bool                    IsSkipItems;                    // Do we want item submissions to this column to be completely ignored (no layout will happen).\r\n    bool                    IsPreserveWidthAuto;\r\n    ImS8                    NavLayerCurrent;                // ImGuiNavLayer in 1 byte\r\n    ImU8                    AutoFitQueue;                   // Queue of 8 values for the next 8 frames to request auto-fit\r\n    ImU8                    CannotSkipItemsQueue;           // Queue of 8 values for the next 8 frames to disable Clipped/SkipItem\r\n    ImU8                    SortDirection : 2;              // ImGuiSortDirection_Ascending or ImGuiSortDirection_Descending\r\n    ImU8                    SortDirectionsAvailCount : 2;   // Number of available sort directions (0 to 3)\r\n    ImU8                    SortDirectionsAvailMask : 4;    // Mask of available sort directions (1-bit each)\r\n    ImU8                    SortDirectionsAvailList;        // Ordered of available sort directions (2-bits each)\r\n\r\n    ImGuiTableColumn()\r\n    {\r\n        memset(this, 0, sizeof(*this));\r\n        StretchWeight = WidthRequest = -1.0f;\r\n        NameOffset = -1;\r\n        DisplayOrder = IndexWithinEnabledSet = -1;\r\n        PrevEnabledColumn = NextEnabledColumn = -1;\r\n        SortOrder = -1;\r\n        SortDirection = ImGuiSortDirection_None;\r\n        DrawChannelCurrent = DrawChannelFrozen = DrawChannelUnfrozen = (ImU8)-1;\r\n    }\r\n};\r\n\r\n// Transient cell data stored per row.\r\n// sizeof() ~ 6\r\nstruct ImGuiTableCellData\r\n{\r\n    ImU32                       BgColor;    // Actual color\r\n    ImGuiTableColumnIdx         Column;     // Column number\r\n};\r\n\r\n// FIXME-TABLE: more transient data could be stored in a per-stacked table structure: DrawSplitter, SortSpecs, incoming RowData\r\nstruct IMGUI_API ImGuiTable\r\n{\r\n    ImGuiID                     ID;\r\n    ImGuiTableFlags             Flags;\r\n    void*                       RawData;                    // Single allocation to hold Columns[], DisplayOrderToIndex[] and RowCellData[]\r\n    ImGuiTableTempData*         TempData;                   // Transient data while table is active. Point within g.CurrentTableStack[]\r\n    ImSpan<ImGuiTableColumn>    Columns;                    // Point within RawData[]\r\n    ImSpan<ImGuiTableColumnIdx> DisplayOrderToIndex;        // Point within RawData[]. Store display order of columns (when not reordered, the values are 0...Count-1)\r\n    ImSpan<ImGuiTableCellData>  RowCellData;                // Point within RawData[]. Store cells background requests for current row.\r\n    ImU64                       EnabledMaskByDisplayOrder;  // Column DisplayOrder -> IsEnabled map\r\n    ImU64                       EnabledMaskByIndex;         // Column Index -> IsEnabled map (== not hidden by user/api) in a format adequate for iterating column without touching cold data\r\n    ImU64                       VisibleMaskByIndex;         // Column Index -> IsVisibleX|IsVisibleY map (== not hidden by user/api && not hidden by scrolling/cliprect)\r\n    ImU64                       RequestOutputMaskByIndex;   // Column Index -> IsVisible || AutoFit (== expect user to submit items)\r\n    ImGuiTableFlags             SettingsLoadedFlags;        // Which data were loaded from the .ini file (e.g. when order is not altered we won't save order)\r\n    int                         SettingsOffset;             // Offset in g.SettingsTables\r\n    int                         LastFrameActive;\r\n    int                         ColumnsCount;               // Number of columns declared in BeginTable()\r\n    int                         CurrentRow;\r\n    int                         CurrentColumn;\r\n    ImS16                       InstanceCurrent;            // Count of BeginTable() calls with same ID in the same frame (generally 0). This is a little bit similar to BeginCount for a window, but multiple table with same ID look are multiple tables, they are just synched.\r\n    ImS16                       InstanceInteracted;         // Mark which instance (generally 0) of the same ID is being interacted with\r\n    float                       RowPosY1;\r\n    float                       RowPosY2;\r\n    float                       RowMinHeight;               // Height submitted to TableNextRow()\r\n    float                       RowTextBaseline;\r\n    float                       RowIndentOffsetX;\r\n    ImGuiTableRowFlags          RowFlags : 16;              // Current row flags, see ImGuiTableRowFlags_\r\n    ImGuiTableRowFlags          LastRowFlags : 16;\r\n    int                         RowBgColorCounter;          // Counter for alternating background colors (can be fast-forwarded by e.g clipper), not same as CurrentRow because header rows typically don't increase this.\r\n    ImU32                       RowBgColor[2];              // Background color override for current row.\r\n    ImU32                       BorderColorStrong;\r\n    ImU32                       BorderColorLight;\r\n    float                       BorderX1;\r\n    float                       BorderX2;\r\n    float                       HostIndentX;\r\n    float                       MinColumnWidth;\r\n    float                       OuterPaddingX;\r\n    float                       CellPaddingX;               // Padding from each borders\r\n    float                       CellPaddingY;\r\n    float                       CellSpacingX1;              // Spacing between non-bordered cells\r\n    float                       CellSpacingX2;\r\n    float                       LastOuterHeight;            // Outer height from last frame\r\n    float                       LastFirstRowHeight;         // Height of first row from last frame\r\n    float                       InnerWidth;                 // User value passed to BeginTable(), see comments at the top of BeginTable() for details.\r\n    float                       ColumnsGivenWidth;          // Sum of current column width\r\n    float                       ColumnsAutoFitWidth;        // Sum of ideal column width in order nothing to be clipped, used for auto-fitting and content width submission in outer window\r\n    float                       ResizedColumnNextWidth;\r\n    float                       ResizeLockMinContentsX2;    // Lock minimum contents width while resizing down in order to not create feedback loops. But we allow growing the table.\r\n    float                       RefScale;                   // Reference scale to be able to rescale columns on font/dpi changes.\r\n    ImRect                      OuterRect;                  // Note: for non-scrolling table, OuterRect.Max.y is often FLT_MAX until EndTable(), unless a height has been specified in BeginTable().\r\n    ImRect                      InnerRect;                  // InnerRect but without decoration. As with OuterRect, for non-scrolling tables, InnerRect.Max.y is\r\n    ImRect                      WorkRect;\r\n    ImRect                      InnerClipRect;\r\n    ImRect                      BgClipRect;                 // We use this to cpu-clip cell background color fill, evolve during the frame as we cross frozen rows boundaries\r\n    ImRect                      Bg0ClipRectForDrawCmd;      // Actual ImDrawCmd clip rect for BG0/1 channel. This tends to be == OuterWindow->ClipRect at BeginTable() because output in BG0/BG1 is cpu-clipped\r\n    ImRect                      Bg2ClipRectForDrawCmd;      // Actual ImDrawCmd clip rect for BG2 channel. This tends to be a correct, tight-fit, because output to BG2 are done by widgets relying on regular ClipRect.\r\n    ImRect                      HostClipRect;               // This is used to check if we can eventually merge our columns draw calls into the current draw call of the current window.\r\n    ImRect                      HostBackupInnerClipRect;    // Backup of InnerWindow->ClipRect during PushTableBackground()/PopTableBackground()\r\n    ImGuiWindow*                OuterWindow;                // Parent window for the table\r\n    ImGuiWindow*                InnerWindow;                // Window holding the table data (== OuterWindow or a child window)\r\n    ImGuiTextBuffer             ColumnsNames;               // Contiguous buffer holding columns names\r\n    ImDrawListSplitter*         DrawSplitter;               // Shortcut to TempData->DrawSplitter while in table. Isolate draw commands per columns to avoid switching clip rect constantly\r\n    ImGuiTableColumnSortSpecs   SortSpecsSingle;\r\n    ImVector<ImGuiTableColumnSortSpecs> SortSpecsMulti;     // FIXME-OPT: Using a small-vector pattern would be good.\r\n    ImGuiTableSortSpecs         SortSpecs;                  // Public facing sorts specs, this is what we return in TableGetSortSpecs()\r\n    ImGuiTableColumnIdx         SortSpecsCount;\r\n    ImGuiTableColumnIdx         ColumnsEnabledCount;        // Number of enabled columns (<= ColumnsCount)\r\n    ImGuiTableColumnIdx         ColumnsEnabledFixedCount;   // Number of enabled columns (<= ColumnsCount)\r\n    ImGuiTableColumnIdx         DeclColumnsCount;           // Count calls to TableSetupColumn()\r\n    ImGuiTableColumnIdx         HoveredColumnBody;          // Index of column whose visible region is being hovered. Important: == ColumnsCount when hovering empty region after the right-most column!\r\n    ImGuiTableColumnIdx         HoveredColumnBorder;        // Index of column whose right-border is being hovered (for resizing).\r\n    ImGuiTableColumnIdx         AutoFitSingleColumn;        // Index of single column requesting auto-fit.\r\n    ImGuiTableColumnIdx         ResizedColumn;              // Index of column being resized. Reset when InstanceCurrent==0.\r\n    ImGuiTableColumnIdx         LastResizedColumn;          // Index of column being resized from previous frame.\r\n    ImGuiTableColumnIdx         HeldHeaderColumn;           // Index of column header being held.\r\n    ImGuiTableColumnIdx         ReorderColumn;              // Index of column being reordered. (not cleared)\r\n    ImGuiTableColumnIdx         ReorderColumnDir;           // -1 or +1\r\n    ImGuiTableColumnIdx         LeftMostEnabledColumn;      // Index of left-most non-hidden column.\r\n    ImGuiTableColumnIdx         RightMostEnabledColumn;     // Index of right-most non-hidden column.\r\n    ImGuiTableColumnIdx         LeftMostStretchedColumn;    // Index of left-most stretched column.\r\n    ImGuiTableColumnIdx         RightMostStretchedColumn;   // Index of right-most stretched column.\r\n    ImGuiTableColumnIdx         ContextPopupColumn;         // Column right-clicked on, of -1 if opening context menu from a neutral/empty spot\r\n    ImGuiTableColumnIdx         FreezeRowsRequest;          // Requested frozen rows count\r\n    ImGuiTableColumnIdx         FreezeRowsCount;            // Actual frozen row count (== FreezeRowsRequest, or == 0 when no scrolling offset)\r\n    ImGuiTableColumnIdx         FreezeColumnsRequest;       // Requested frozen columns count\r\n    ImGuiTableColumnIdx         FreezeColumnsCount;         // Actual frozen columns count (== FreezeColumnsRequest, or == 0 when no scrolling offset)\r\n    ImGuiTableColumnIdx         RowCellDataCurrent;         // Index of current RowCellData[] entry in current row\r\n    ImGuiTableDrawChannelIdx    DummyDrawChannel;           // Redirect non-visible columns here.\r\n    ImGuiTableDrawChannelIdx    Bg2DrawChannelCurrent;      // For Selectable() and other widgets drawing across columns after the freezing line. Index within DrawSplitter.Channels[]\r\n    ImGuiTableDrawChannelIdx    Bg2DrawChannelUnfrozen;\r\n    bool                        IsLayoutLocked;             // Set by TableUpdateLayout() which is called when beginning the first row.\r\n    bool                        IsInsideRow;                // Set when inside TableBeginRow()/TableEndRow().\r\n    bool                        IsInitializing;\r\n    bool                        IsSortSpecsDirty;\r\n    bool                        IsUsingHeaders;             // Set when the first row had the ImGuiTableRowFlags_Headers flag.\r\n    bool                        IsContextPopupOpen;         // Set when default context menu is open (also see: ContextPopupColumn, InstanceInteracted).\r\n    bool                        IsSettingsRequestLoad;\r\n    bool                        IsSettingsDirty;            // Set when table settings have changed and needs to be reported into ImGuiTableSetttings data.\r\n    bool                        IsDefaultDisplayOrder;      // Set when display order is unchanged from default (DisplayOrder contains 0...Count-1)\r\n    bool                        IsResetAllRequest;\r\n    bool                        IsResetDisplayOrderRequest;\r\n    bool                        IsUnfrozenRows;             // Set when we got past the frozen row.\r\n    bool                        IsDefaultSizingPolicy;      // Set if user didn't explicitly set a sizing policy in BeginTable()\r\n    bool                        MemoryCompacted;\r\n    bool                        HostSkipItems;              // Backup of InnerWindow->SkipItem at the end of BeginTable(), because we will overwrite InnerWindow->SkipItem on a per-column basis\r\n\r\n    ImGuiTable()                { memset(this, 0, sizeof(*this)); LastFrameActive = -1; }\r\n    ~ImGuiTable()               { IM_FREE(RawData); }\r\n};\r\n\r\n// Transient data that are only needed between BeginTable() and EndTable(), those buffers are shared (1 per level of stacked table).\r\n// - Accessing those requires chasing an extra pointer so for very frequently used data we leave them in the main table structure.\r\n// - We also leave out of this structure data that tend to be particularly useful for debugging/metrics.\r\nstruct IMGUI_API ImGuiTableTempData\r\n{\r\n    int                         TableIndex;                 // Index in g.Tables.Buf[] pool\r\n    float                       LastTimeActive;             // Last timestamp this structure was used\r\n\r\n    ImVec2                      UserOuterSize;              // outer_size.x passed to BeginTable()\r\n    ImDrawListSplitter          DrawSplitter;\r\n\r\n    ImRect                      HostBackupWorkRect;         // Backup of InnerWindow->WorkRect at the end of BeginTable()\r\n    ImRect                      HostBackupParentWorkRect;   // Backup of InnerWindow->ParentWorkRect at the end of BeginTable()\r\n    ImVec2                      HostBackupPrevLineSize;     // Backup of InnerWindow->DC.PrevLineSize at the end of BeginTable()\r\n    ImVec2                      HostBackupCurrLineSize;     // Backup of InnerWindow->DC.CurrLineSize at the end of BeginTable()\r\n    ImVec2                      HostBackupCursorMaxPos;     // Backup of InnerWindow->DC.CursorMaxPos at the end of BeginTable()\r\n    ImVec1                      HostBackupColumnsOffset;    // Backup of OuterWindow->DC.ColumnsOffset at the end of BeginTable()\r\n    float                       HostBackupItemWidth;        // Backup of OuterWindow->DC.ItemWidth at the end of BeginTable()\r\n    int                         HostBackupItemWidthStackSize;//Backup of OuterWindow->DC.ItemWidthStack.Size at the end of BeginTable()\r\n\r\n    ImGuiTableTempData()        { memset(this, 0, sizeof(*this)); LastTimeActive = -1.0f; }\r\n};\r\n\r\n// sizeof() ~ 12\r\nstruct ImGuiTableColumnSettings\r\n{\r\n    float                   WidthOrWeight;\r\n    ImGuiID                 UserID;\r\n    ImGuiTableColumnIdx     Index;\r\n    ImGuiTableColumnIdx     DisplayOrder;\r\n    ImGuiTableColumnIdx     SortOrder;\r\n    ImU8                    SortDirection : 2;\r\n    ImU8                    IsEnabled : 1; // \"Visible\" in ini file\r\n    ImU8                    IsStretch : 1;\r\n\r\n    ImGuiTableColumnSettings()\r\n    {\r\n        WidthOrWeight = 0.0f;\r\n        UserID = 0;\r\n        Index = -1;\r\n        DisplayOrder = SortOrder = -1;\r\n        SortDirection = ImGuiSortDirection_None;\r\n        IsEnabled = 1;\r\n        IsStretch = 0;\r\n    }\r\n};\r\n\r\n// This is designed to be stored in a single ImChunkStream (1 header followed by N ImGuiTableColumnSettings, etc.)\r\nstruct ImGuiTableSettings\r\n{\r\n    ImGuiID                     ID;                     // Set to 0 to invalidate/delete the setting\r\n    ImGuiTableFlags             SaveFlags;              // Indicate data we want to save using the Resizable/Reorderable/Sortable/Hideable flags (could be using its own flags..)\r\n    float                       RefScale;               // Reference scale to be able to rescale columns on font/dpi changes.\r\n    ImGuiTableColumnIdx         ColumnsCount;\r\n    ImGuiTableColumnIdx         ColumnsCountMax;        // Maximum number of columns this settings instance can store, we can recycle a settings instance with lower number of columns but not higher\r\n    bool                        WantApply;              // Set when loaded from .ini data (to enable merging/loading .ini data into an already running context)\r\n\r\n    ImGuiTableSettings()        { memset(this, 0, sizeof(*this)); }\r\n    ImGuiTableColumnSettings*   GetColumnSettings()     { return (ImGuiTableColumnSettings*)(this + 1); }\r\n};\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] ImGui internal API\r\n// No guarantee of forward compatibility here!\r\n//-----------------------------------------------------------------------------\r\n\r\nnamespace ImGui\r\n{\r\n    // Windows\r\n    // We should always have a CurrentWindow in the stack (there is an implicit \"Debug\" window)\r\n    // If this ever crash because g.CurrentWindow is NULL it means that either\r\n    // - ImGui::NewFrame() has never been called, which is illegal.\r\n    // - You are calling ImGui functions after ImGui::EndFrame()/ImGui::Render() and before the next ImGui::NewFrame(), which is also illegal.\r\n    inline    ImGuiWindow*  GetCurrentWindowRead()      { ImGuiContext& g = *GImGui; return g.CurrentWindow; }\r\n    inline    ImGuiWindow*  GetCurrentWindow()          { ImGuiContext& g = *GImGui; g.CurrentWindow->WriteAccessed = true; return g.CurrentWindow; }\r\n    IMGUI_API ImGuiWindow*  FindWindowByID(ImGuiID id);\r\n    IMGUI_API ImGuiWindow*  FindWindowByName(const char* name);\r\n    IMGUI_API void          UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window);\r\n    IMGUI_API ImVec2        CalcWindowNextAutoFitSize(ImGuiWindow* window);\r\n    IMGUI_API bool          IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent, bool popup_hierarchy);\r\n    IMGUI_API bool          IsWindowWithinBeginStackOf(ImGuiWindow* window, ImGuiWindow* potential_parent);\r\n    IMGUI_API bool          IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below);\r\n    IMGUI_API bool          IsWindowNavFocusable(ImGuiWindow* window);\r\n    IMGUI_API void          SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond = 0);\r\n    IMGUI_API void          SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond = 0);\r\n    IMGUI_API void          SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond = 0);\r\n    IMGUI_API void          SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size);\r\n    inline ImRect           WindowRectAbsToRel(ImGuiWindow* window, const ImRect& r) { ImVec2 off = window->DC.CursorStartPos; return ImRect(r.Min.x - off.x, r.Min.y - off.y, r.Max.x - off.x, r.Max.y - off.y); }\r\n    inline ImRect           WindowRectRelToAbs(ImGuiWindow* window, const ImRect& r) { ImVec2 off = window->DC.CursorStartPos; return ImRect(r.Min.x + off.x, r.Min.y + off.y, r.Max.x + off.x, r.Max.y + off.y); }\r\n\r\n    // Windows: Display Order and Focus Order\r\n    IMGUI_API void          FocusWindow(ImGuiWindow* window);\r\n    IMGUI_API void          FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window);\r\n    IMGUI_API void          BringWindowToFocusFront(ImGuiWindow* window);\r\n    IMGUI_API void          BringWindowToDisplayFront(ImGuiWindow* window);\r\n    IMGUI_API void          BringWindowToDisplayBack(ImGuiWindow* window);\r\n    IMGUI_API void          BringWindowToDisplayBehind(ImGuiWindow* window, ImGuiWindow* above_window);\r\n    IMGUI_API int           FindWindowDisplayIndex(ImGuiWindow* window);\r\n    IMGUI_API ImGuiWindow*  FindBottomMostVisibleWindowWithinBeginStack(ImGuiWindow* window);\r\n\r\n    // Fonts, drawing\r\n    IMGUI_API void          SetCurrentFont(ImFont* font);\r\n    inline ImFont*          GetDefaultFont() { ImGuiContext& g = *GImGui; return g.IO.FontDefault ? g.IO.FontDefault : g.IO.Fonts->Fonts[0]; }\r\n    inline ImDrawList*      GetForegroundDrawList(ImGuiWindow* window) { IM_UNUSED(window); return GetForegroundDrawList(); } // This seemingly unnecessary wrapper simplifies compatibility between the 'master' and 'docking' branches.\r\n    IMGUI_API ImDrawList*   GetBackgroundDrawList(ImGuiViewport* viewport);                     // get background draw list for the given viewport. this draw list will be the first rendering one. Useful to quickly draw shapes/text behind dear imgui contents.\r\n    IMGUI_API ImDrawList*   GetForegroundDrawList(ImGuiViewport* viewport);                     // get foreground draw list for the given viewport. this draw list will be the last rendered one. Useful to quickly draw shapes/text over dear imgui contents.\r\n\r\n    // Init\r\n    IMGUI_API void          Initialize(ImGuiContext* context);\r\n    IMGUI_API void          Shutdown(ImGuiContext* context);    // Since 1.60 this is a _private_ function. You can call DestroyContext() to destroy the context created by CreateContext().\r\n\r\n    // NewFrame\r\n    IMGUI_API void          UpdateInputEvents(bool trickle_fast_inputs);\r\n    IMGUI_API void          UpdateHoveredWindowAndCaptureFlags();\r\n    IMGUI_API void          StartMouseMovingWindow(ImGuiWindow* window);\r\n    IMGUI_API void          UpdateMouseMovingWindowNewFrame();\r\n    IMGUI_API void          UpdateMouseMovingWindowEndFrame();\r\n\r\n    // Generic context hooks\r\n    IMGUI_API ImGuiID       AddContextHook(ImGuiContext* context, const ImGuiContextHook* hook);\r\n    IMGUI_API void          RemoveContextHook(ImGuiContext* context, ImGuiID hook_to_remove);\r\n    IMGUI_API void          CallContextHooks(ImGuiContext* context, ImGuiContextHookType type);\r\n\r\n    // Settings\r\n    IMGUI_API void                  MarkIniSettingsDirty();\r\n    IMGUI_API void                  MarkIniSettingsDirty(ImGuiWindow* window);\r\n    IMGUI_API void                  ClearIniSettings();\r\n    IMGUI_API ImGuiWindowSettings*  CreateNewWindowSettings(const char* name);\r\n    IMGUI_API ImGuiWindowSettings*  FindWindowSettings(ImGuiID id);\r\n    IMGUI_API ImGuiWindowSettings*  FindOrCreateWindowSettings(const char* name);\r\n    IMGUI_API ImGuiSettingsHandler* FindSettingsHandler(const char* type_name);\r\n\r\n    // Scrolling\r\n    IMGUI_API void          SetNextWindowScroll(const ImVec2& scroll); // Use -1.0f on one axis to leave as-is\r\n    IMGUI_API void          SetScrollX(ImGuiWindow* window, float scroll_x);\r\n    IMGUI_API void          SetScrollY(ImGuiWindow* window, float scroll_y);\r\n    IMGUI_API void          SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio);\r\n    IMGUI_API void          SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio);\r\n\r\n    // Early work-in-progress API (ScrollToItem() will become public)\r\n    IMGUI_API void          ScrollToItem(ImGuiScrollFlags flags = 0);\r\n    IMGUI_API void          ScrollToRect(ImGuiWindow* window, const ImRect& rect, ImGuiScrollFlags flags = 0);\r\n    IMGUI_API ImVec2        ScrollToRectEx(ImGuiWindow* window, const ImRect& rect, ImGuiScrollFlags flags = 0);\r\n//#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS\r\n    inline void             ScrollToBringRectIntoView(ImGuiWindow* window, const ImRect& rect) { ScrollToRect(window, rect, ImGuiScrollFlags_KeepVisibleEdgeY); }\r\n//#endif\r\n\r\n    // Basic Accessors\r\n    inline ImGuiID          GetItemID()     { ImGuiContext& g = *GImGui; return g.LastItemData.ID; }   // Get ID of last item (~~ often same ImGui::GetID(label) beforehand)\r\n    inline ImGuiItemStatusFlags GetItemStatusFlags(){ ImGuiContext& g = *GImGui; return g.LastItemData.StatusFlags; }\r\n    inline ImGuiItemFlags   GetItemFlags()  { ImGuiContext& g = *GImGui; return g.LastItemData.InFlags; }\r\n    inline ImGuiID          GetActiveID()   { ImGuiContext& g = *GImGui; return g.ActiveId; }\r\n    inline ImGuiID          GetFocusID()    { ImGuiContext& g = *GImGui; return g.NavId; }\r\n    IMGUI_API void          SetActiveID(ImGuiID id, ImGuiWindow* window);\r\n    IMGUI_API void          SetFocusID(ImGuiID id, ImGuiWindow* window);\r\n    IMGUI_API void          ClearActiveID();\r\n    IMGUI_API ImGuiID       GetHoveredID();\r\n    IMGUI_API void          SetHoveredID(ImGuiID id);\r\n    IMGUI_API void          KeepAliveID(ImGuiID id);\r\n    IMGUI_API void          MarkItemEdited(ImGuiID id);     // Mark data associated to given item as \"edited\", used by IsItemDeactivatedAfterEdit() function.\r\n    IMGUI_API void          PushOverrideID(ImGuiID id);     // Push given value as-is at the top of the ID stack (whereas PushID combines old and new hashes)\r\n    IMGUI_API ImGuiID       GetIDWithSeed(const char* str_id_begin, const char* str_id_end, ImGuiID seed);\r\n\r\n    // Basic Helpers for widget code\r\n    IMGUI_API void          ItemSize(const ImVec2& size, float text_baseline_y = -1.0f);\r\n    IMGUI_API void          ItemSize(const ImRect& bb, float text_baseline_y = -1.0f);\r\n    IMGUI_API bool          ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb = NULL, ImGuiItemFlags extra_flags = 0);\r\n    IMGUI_API bool          ItemHoverable(const ImRect& bb, ImGuiID id);\r\n    IMGUI_API bool          IsClippedEx(const ImRect& bb, ImGuiID id);\r\n    IMGUI_API void          SetLastItemData(ImGuiID item_id, ImGuiItemFlags in_flags, ImGuiItemStatusFlags status_flags, const ImRect& item_rect);\r\n    IMGUI_API ImVec2        CalcItemSize(ImVec2 size, float default_w, float default_h);\r\n    IMGUI_API float         CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x);\r\n    IMGUI_API void          PushMultiItemsWidths(int components, float width_full);\r\n    IMGUI_API bool          IsItemToggledSelection();                                   // Was the last item selection toggled? (after Selectable(), TreeNode() etc. We only returns toggle _event_ in order to handle clipping correctly)\r\n    IMGUI_API ImVec2        GetContentRegionMaxAbs();\r\n    IMGUI_API void          ShrinkWidths(ImGuiShrinkWidthItem* items, int count, float width_excess);\r\n\r\n    // Parameter stacks\r\n    IMGUI_API void          PushItemFlag(ImGuiItemFlags option, bool enabled);\r\n    IMGUI_API void          PopItemFlag();\r\n\r\n#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS\r\n    // Currently refactoring focus/nav/tabbing system\r\n    // If you have old/custom copy-and-pasted widgets that used FocusableItemRegister():\r\n    //  (Old) IMGUI_VERSION_NUM  < 18209: using 'ItemAdd(....)'                              and 'bool tab_focused = FocusableItemRegister(...)'\r\n    //  (Old) IMGUI_VERSION_NUM >= 18209: using 'ItemAdd(..., ImGuiItemAddFlags_Focusable)'  and 'bool tab_focused = (GetItemStatusFlags() & ImGuiItemStatusFlags_Focused) != 0'\r\n    //  (New) IMGUI_VERSION_NUM >= 18413: using 'ItemAdd(..., ImGuiItemFlags_Inputable)'     and 'bool tab_focused = (GetItemStatusFlags() & ImGuiItemStatusFlags_FocusedTabbing) != 0 || g.NavActivateInputId == id' (WIP)\r\n    // Widget code are simplified as there's no need to call FocusableItemUnregister() while managing the transition from regular widget to TempInputText()\r\n    inline bool FocusableItemRegister(ImGuiWindow* window, ImGuiID id)  { IM_ASSERT(0); IM_UNUSED(window); IM_UNUSED(id); return false; } // -> pass ImGuiItemAddFlags_Inputable flag to ItemAdd()\r\n    inline void FocusableItemUnregister(ImGuiWindow* window)            { IM_ASSERT(0); IM_UNUSED(window); }                              // -> unnecessary: TempInputText() uses ImGuiInputTextFlags_MergedItem\r\n#endif\r\n\r\n    // Logging/Capture\r\n    IMGUI_API void          LogBegin(ImGuiLogType type, int auto_open_depth);           // -> BeginCapture() when we design v2 api, for now stay under the radar by using the old name.\r\n    IMGUI_API void          LogToBuffer(int auto_open_depth = -1);                      // Start logging/capturing to internal buffer\r\n    IMGUI_API void          LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end = NULL);\r\n    IMGUI_API void          LogSetNextTextDecoration(const char* prefix, const char* suffix);\r\n\r\n    // Popups, Modals, Tooltips\r\n    IMGUI_API bool          BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags);\r\n    IMGUI_API void          OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags = ImGuiPopupFlags_None);\r\n    IMGUI_API void          ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup);\r\n    IMGUI_API void          ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup);\r\n    IMGUI_API void          ClosePopupsExceptModals();\r\n    IMGUI_API bool          IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags);\r\n    IMGUI_API bool          BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_flags);\r\n    IMGUI_API void          BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags extra_window_flags);\r\n    IMGUI_API ImRect        GetPopupAllowedExtentRect(ImGuiWindow* window);\r\n    IMGUI_API ImGuiWindow*  GetTopMostPopupModal();\r\n    IMGUI_API ImGuiWindow*  GetTopMostAndVisiblePopupModal();\r\n    IMGUI_API ImVec2        FindBestWindowPosForPopup(ImGuiWindow* window);\r\n    IMGUI_API ImVec2        FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy);\r\n\r\n    // Menus\r\n    IMGUI_API bool          BeginViewportSideBar(const char* name, ImGuiViewport* viewport, ImGuiDir dir, float size, ImGuiWindowFlags window_flags);\r\n    IMGUI_API bool          BeginMenuEx(const char* label, const char* icon, bool enabled = true);\r\n    IMGUI_API bool          MenuItemEx(const char* label, const char* icon, const char* shortcut = NULL, bool selected = false, bool enabled = true);\r\n\r\n    // Combos\r\n    IMGUI_API bool          BeginComboPopup(ImGuiID popup_id, const ImRect& bb, ImGuiComboFlags flags);\r\n    IMGUI_API bool          BeginComboPreview();\r\n    IMGUI_API void          EndComboPreview();\r\n\r\n    // Gamepad/Keyboard Navigation\r\n    IMGUI_API void          NavInitWindow(ImGuiWindow* window, bool force_reinit);\r\n    IMGUI_API void          NavInitRequestApplyResult();\r\n    IMGUI_API bool          NavMoveRequestButNoResultYet();\r\n    IMGUI_API void          NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags);\r\n    IMGUI_API void          NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags);\r\n    IMGUI_API void          NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result);\r\n    IMGUI_API void          NavMoveRequestCancel();\r\n    IMGUI_API void          NavMoveRequestApplyResult();\r\n    IMGUI_API void          NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags move_flags);\r\n    IMGUI_API const char*   GetNavInputName(ImGuiNavInput n);\r\n    IMGUI_API float         GetNavInputAmount(ImGuiNavInput n, ImGuiInputReadMode mode);\r\n    IMGUI_API ImVec2        GetNavInputAmount2d(ImGuiNavDirSourceFlags dir_sources, ImGuiInputReadMode mode, float slow_factor = 0.0f, float fast_factor = 0.0f);\r\n    IMGUI_API int           CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate);\r\n    IMGUI_API void          ActivateItem(ImGuiID id);   // Remotely activate a button, checkbox, tree node etc. given its unique ID. activation is queued and processed on the next frame when the item is encountered again.\r\n    IMGUI_API void          SetNavID(ImGuiID id, ImGuiNavLayer nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel);\r\n\r\n    // Focus Scope (WIP)\r\n    // This is generally used to identify a selection set (multiple of which may be in the same window), as selection\r\n    // patterns generally need to react (e.g. clear selection) when landing on an item of the set.\r\n    IMGUI_API void          PushFocusScope(ImGuiID id);\r\n    IMGUI_API void          PopFocusScope();\r\n    inline ImGuiID          GetFocusedFocusScope()          { ImGuiContext& g = *GImGui; return g.NavFocusScopeId; }                            // Focus scope which is actually active\r\n    inline ImGuiID          GetFocusScope()                 { ImGuiContext& g = *GImGui; return g.CurrentWindow->DC.NavFocusScopeIdCurrent; }   // Focus scope we are outputting into, set by PushFocusScope()\r\n\r\n    // Inputs\r\n    // FIXME: Eventually we should aim to move e.g. IsActiveIdUsingKey() into IsKeyXXX functions.\r\n    inline bool             IsNamedKey(ImGuiKey key)                                    { return key >= ImGuiKey_NamedKey_BEGIN && key < ImGuiKey_NamedKey_END; }\r\n    inline bool             IsLegacyKey(ImGuiKey key)                                   { return key >= ImGuiKey_LegacyNativeKey_BEGIN && key < ImGuiKey_LegacyNativeKey_END; }\r\n    inline bool             IsGamepadKey(ImGuiKey key)                                  { return key >= ImGuiKey_Gamepad_BEGIN && key < ImGuiKey_Gamepad_END; }\r\n    IMGUI_API ImGuiKeyData* GetKeyData(ImGuiKey key);\r\n    IMGUI_API void          SetItemUsingMouseWheel();\r\n    IMGUI_API void          SetActiveIdUsingNavAndKeys();\r\n    inline bool             IsActiveIdUsingNavDir(ImGuiDir dir)                         { ImGuiContext& g = *GImGui; return (g.ActiveIdUsingNavDirMask & (1 << dir)) != 0; }\r\n    inline bool             IsActiveIdUsingNavInput(ImGuiNavInput input)                { ImGuiContext& g = *GImGui; return (g.ActiveIdUsingNavInputMask & (1 << input)) != 0; }\r\n    inline bool             IsActiveIdUsingKey(ImGuiKey key)                            { ImGuiContext& g = *GImGui; return g.ActiveIdUsingKeyInputMask[key]; }\r\n    inline void             SetActiveIdUsingKey(ImGuiKey key)                           { ImGuiContext& g = *GImGui; g.ActiveIdUsingKeyInputMask.SetBit(key); }\r\n    IMGUI_API bool          IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold = -1.0f);\r\n    inline bool             IsNavInputDown(ImGuiNavInput n)                             { ImGuiContext& g = *GImGui; return g.IO.NavInputs[n] > 0.0f; }\r\n    inline bool             IsNavInputTest(ImGuiNavInput n, ImGuiInputReadMode rm)      { return (GetNavInputAmount(n, rm) > 0.0f); }\r\n    IMGUI_API ImGuiKeyModFlags GetMergedKeyModFlags();\r\n#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO\r\n    inline bool             IsKeyPressedMap(ImGuiKey key, bool repeat = true)           { IM_ASSERT(IsNamedKey(key)); return IsKeyPressed(key, repeat); }\r\n#endif\r\n\r\n    // Drag and Drop\r\n    IMGUI_API bool          BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id);\r\n    IMGUI_API void          ClearDragDrop();\r\n    IMGUI_API bool          IsDragDropPayloadBeingAccepted();\r\n\r\n    // Internal Columns API (this is not exposed because we will encourage transitioning to the Tables API)\r\n    IMGUI_API void          SetWindowClipRectBeforeSetChannel(ImGuiWindow* window, const ImRect& clip_rect);\r\n    IMGUI_API void          BeginColumns(const char* str_id, int count, ImGuiOldColumnFlags flags = 0); // setup number of columns. use an identifier to distinguish multiple column sets. close with EndColumns().\r\n    IMGUI_API void          EndColumns();                                                               // close columns\r\n    IMGUI_API void          PushColumnClipRect(int column_index);\r\n    IMGUI_API void          PushColumnsBackground();\r\n    IMGUI_API void          PopColumnsBackground();\r\n    IMGUI_API ImGuiID       GetColumnsID(const char* str_id, int count);\r\n    IMGUI_API ImGuiOldColumns* FindOrCreateColumns(ImGuiWindow* window, ImGuiID id);\r\n    IMGUI_API float         GetColumnOffsetFromNorm(const ImGuiOldColumns* columns, float offset_norm);\r\n    IMGUI_API float         GetColumnNormFromOffset(const ImGuiOldColumns* columns, float offset);\r\n\r\n    // Tables: Candidates for public API\r\n    IMGUI_API void          TableOpenContextMenu(int column_n = -1);\r\n    IMGUI_API void          TableSetColumnWidth(int column_n, float width);\r\n    IMGUI_API void          TableSetColumnSortDirection(int column_n, ImGuiSortDirection sort_direction, bool append_to_sort_specs);\r\n    IMGUI_API int           TableGetHoveredColumn(); // May use (TableGetColumnFlags() & ImGuiTableColumnFlags_IsHovered) instead. Return hovered column. return -1 when table is not hovered. return columns_count if the unused space at the right of visible columns is hovered.\r\n    IMGUI_API float         TableGetHeaderRowHeight();\r\n    IMGUI_API void          TablePushBackgroundChannel();\r\n    IMGUI_API void          TablePopBackgroundChannel();\r\n\r\n    // Tables: Internals\r\n    inline    ImGuiTable*   GetCurrentTable() { ImGuiContext& g = *GImGui; return g.CurrentTable; }\r\n    IMGUI_API ImGuiTable*   TableFindByID(ImGuiID id);\r\n    IMGUI_API bool          BeginTableEx(const char* name, ImGuiID id, int columns_count, ImGuiTableFlags flags = 0, const ImVec2& outer_size = ImVec2(0, 0), float inner_width = 0.0f);\r\n    IMGUI_API void          TableBeginInitMemory(ImGuiTable* table, int columns_count);\r\n    IMGUI_API void          TableBeginApplyRequests(ImGuiTable* table);\r\n    IMGUI_API void          TableSetupDrawChannels(ImGuiTable* table);\r\n    IMGUI_API void          TableUpdateLayout(ImGuiTable* table);\r\n    IMGUI_API void          TableUpdateBorders(ImGuiTable* table);\r\n    IMGUI_API void          TableUpdateColumnsWeightFromWidth(ImGuiTable* table);\r\n    IMGUI_API void          TableDrawBorders(ImGuiTable* table);\r\n    IMGUI_API void          TableDrawContextMenu(ImGuiTable* table);\r\n    IMGUI_API void          TableMergeDrawChannels(ImGuiTable* table);\r\n    IMGUI_API void          TableSortSpecsSanitize(ImGuiTable* table);\r\n    IMGUI_API void          TableSortSpecsBuild(ImGuiTable* table);\r\n    IMGUI_API ImGuiSortDirection TableGetColumnNextSortDirection(ImGuiTableColumn* column);\r\n    IMGUI_API void          TableFixColumnSortDirection(ImGuiTable* table, ImGuiTableColumn* column);\r\n    IMGUI_API float         TableGetColumnWidthAuto(ImGuiTable* table, ImGuiTableColumn* column);\r\n    IMGUI_API void          TableBeginRow(ImGuiTable* table);\r\n    IMGUI_API void          TableEndRow(ImGuiTable* table);\r\n    IMGUI_API void          TableBeginCell(ImGuiTable* table, int column_n);\r\n    IMGUI_API void          TableEndCell(ImGuiTable* table);\r\n    IMGUI_API ImRect        TableGetCellBgRect(const ImGuiTable* table, int column_n);\r\n    IMGUI_API const char*   TableGetColumnName(const ImGuiTable* table, int column_n);\r\n    IMGUI_API ImGuiID       TableGetColumnResizeID(const ImGuiTable* table, int column_n, int instance_no = 0);\r\n    IMGUI_API float         TableGetMaxColumnWidth(const ImGuiTable* table, int column_n);\r\n    IMGUI_API void          TableSetColumnWidthAutoSingle(ImGuiTable* table, int column_n);\r\n    IMGUI_API void          TableSetColumnWidthAutoAll(ImGuiTable* table);\r\n    IMGUI_API void          TableRemove(ImGuiTable* table);\r\n    IMGUI_API void          TableGcCompactTransientBuffers(ImGuiTable* table);\r\n    IMGUI_API void          TableGcCompactTransientBuffers(ImGuiTableTempData* table);\r\n    IMGUI_API void          TableGcCompactSettings();\r\n\r\n    // Tables: Settings\r\n    IMGUI_API void                  TableLoadSettings(ImGuiTable* table);\r\n    IMGUI_API void                  TableSaveSettings(ImGuiTable* table);\r\n    IMGUI_API void                  TableResetSettings(ImGuiTable* table);\r\n    IMGUI_API ImGuiTableSettings*   TableGetBoundSettings(ImGuiTable* table);\r\n    IMGUI_API void                  TableSettingsInstallHandler(ImGuiContext* context);\r\n    IMGUI_API ImGuiTableSettings*   TableSettingsCreate(ImGuiID id, int columns_count);\r\n    IMGUI_API ImGuiTableSettings*   TableSettingsFindByID(ImGuiID id);\r\n\r\n    // Tab Bars\r\n    IMGUI_API bool          BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& bb, ImGuiTabBarFlags flags);\r\n    IMGUI_API ImGuiTabItem* TabBarFindTabByID(ImGuiTabBar* tab_bar, ImGuiID tab_id);\r\n    IMGUI_API void          TabBarRemoveTab(ImGuiTabBar* tab_bar, ImGuiID tab_id);\r\n    IMGUI_API void          TabBarCloseTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab);\r\n    IMGUI_API void          TabBarQueueReorder(ImGuiTabBar* tab_bar, const ImGuiTabItem* tab, int offset);\r\n    IMGUI_API void          TabBarQueueReorderFromMousePos(ImGuiTabBar* tab_bar, const ImGuiTabItem* tab, ImVec2 mouse_pos);\r\n    IMGUI_API bool          TabBarProcessReorder(ImGuiTabBar* tab_bar);\r\n    IMGUI_API bool          TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, ImGuiTabItemFlags flags);\r\n    IMGUI_API ImVec2        TabItemCalcSize(const char* label, bool has_close_button);\r\n    IMGUI_API void          TabItemBackground(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImU32 col);\r\n    IMGUI_API void          TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImVec2 frame_padding, const char* label, ImGuiID tab_id, ImGuiID close_button_id, bool is_contents_visible, bool* out_just_closed, bool* out_text_clipped);\r\n\r\n    // Render helpers\r\n    // AVOID USING OUTSIDE OF IMGUI.CPP! NOT FOR PUBLIC CONSUMPTION. THOSE FUNCTIONS ARE A MESS. THEIR SIGNATURE AND BEHAVIOR WILL CHANGE, THEY NEED TO BE REFACTORED INTO SOMETHING DECENT.\r\n    // NB: All position are in absolute pixels coordinates (we are never using window coordinates internally)\r\n    IMGUI_API void          RenderText(ImVec2 pos, const char* text, const char* text_end = NULL, bool hide_text_after_hash = true);\r\n    IMGUI_API void          RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width);\r\n    IMGUI_API void          RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align = ImVec2(0, 0), const ImRect* clip_rect = NULL);\r\n    IMGUI_API void          RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align = ImVec2(0, 0), const ImRect* clip_rect = NULL);\r\n    IMGUI_API void          RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end, const ImVec2* text_size_if_known);\r\n    IMGUI_API void          RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border = true, float rounding = 0.0f);\r\n    IMGUI_API void          RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding = 0.0f);\r\n    IMGUI_API void          RenderColorRectWithAlphaCheckerboard(ImDrawList* draw_list, ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, float grid_step, ImVec2 grid_off, float rounding = 0.0f, ImDrawFlags flags = 0);\r\n    IMGUI_API void          RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags = ImGuiNavHighlightFlags_TypeDefault); // Navigation highlight\r\n    IMGUI_API const char*   FindRenderedTextEnd(const char* text, const char* text_end = NULL); // Find the optional ## from which we stop displaying text.\r\n\r\n    // Render helpers (those functions don't access any ImGui state!)\r\n    IMGUI_API void          RenderArrow(ImDrawList* draw_list, ImVec2 pos, ImU32 col, ImGuiDir dir, float scale = 1.0f);\r\n    IMGUI_API void          RenderBullet(ImDrawList* draw_list, ImVec2 pos, ImU32 col);\r\n    IMGUI_API void          RenderCheckMark(ImDrawList* draw_list, ImVec2 pos, ImU32 col, float sz);\r\n    IMGUI_API void          RenderMouseCursor(ImDrawList* draw_list, ImVec2 pos, float scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow);\r\n    IMGUI_API void          RenderArrowPointingAt(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, ImGuiDir direction, ImU32 col);\r\n    IMGUI_API void          RenderRectFilledRangeH(ImDrawList* draw_list, const ImRect& rect, ImU32 col, float x_start_norm, float x_end_norm, float rounding);\r\n    IMGUI_API void          RenderRectFilledWithHole(ImDrawList* draw_list, ImRect outer, ImRect inner, ImU32 col, float rounding);\r\n\r\n#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS\r\n    // [1.71: 2019/06/07: Updating prototypes of some of the internal functions. Leaving those for reference for a short while]\r\n    inline void RenderArrow(ImVec2 pos, ImGuiDir dir, float scale=1.0f) { ImGuiWindow* window = GetCurrentWindow(); RenderArrow(window->DrawList, pos, GetColorU32(ImGuiCol_Text), dir, scale); }\r\n    inline void RenderBullet(ImVec2 pos)                                { ImGuiWindow* window = GetCurrentWindow(); RenderBullet(window->DrawList, pos, GetColorU32(ImGuiCol_Text)); }\r\n#endif\r\n\r\n    // Widgets\r\n    IMGUI_API void          TextEx(const char* text, const char* text_end = NULL, ImGuiTextFlags flags = 0);\r\n    IMGUI_API bool          ButtonEx(const char* label, const ImVec2& size_arg = ImVec2(0, 0), ImGuiButtonFlags flags = 0);\r\n    IMGUI_API bool          CloseButton(ImGuiID id, const ImVec2& pos);\r\n    IMGUI_API bool          CollapseButton(ImGuiID id, const ImVec2& pos);\r\n    IMGUI_API bool          ArrowButtonEx(const char* str_id, ImGuiDir dir, ImVec2 size_arg, ImGuiButtonFlags flags = 0);\r\n    IMGUI_API void          Scrollbar(ImGuiAxis axis);\r\n    IMGUI_API bool          ScrollbarEx(const ImRect& bb, ImGuiID id, ImGuiAxis axis, ImS64* p_scroll_v, ImS64 avail_v, ImS64 contents_v, ImDrawFlags flags);\r\n    IMGUI_API bool          ImageButtonEx(ImGuiID id, ImTextureID texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec2& padding, const ImVec4& bg_col, const ImVec4& tint_col);\r\n    IMGUI_API ImRect        GetWindowScrollbarRect(ImGuiWindow* window, ImGuiAxis axis);\r\n    IMGUI_API ImGuiID       GetWindowScrollbarID(ImGuiWindow* window, ImGuiAxis axis);\r\n    IMGUI_API ImGuiID       GetWindowResizeCornerID(ImGuiWindow* window, int n); // 0..3: corners\r\n    IMGUI_API ImGuiID       GetWindowResizeBorderID(ImGuiWindow* window, ImGuiDir dir);\r\n    IMGUI_API void          SeparatorEx(ImGuiSeparatorFlags flags);\r\n    IMGUI_API bool          CheckboxFlags(const char* label, ImS64* flags, ImS64 flags_value);\r\n    IMGUI_API bool          CheckboxFlags(const char* label, ImU64* flags, ImU64 flags_value);\r\n\r\n    // Widgets low-level behaviors\r\n    IMGUI_API bool          ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags = 0);\r\n    IMGUI_API bool          DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags);\r\n    IMGUI_API bool          SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* p_v, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags, ImRect* out_grab_bb);\r\n    IMGUI_API bool          SplitterBehavior(const ImRect& bb, ImGuiID id, ImGuiAxis axis, float* size1, float* size2, float min_size1, float min_size2, float hover_extend = 0.0f, float hover_visibility_delay = 0.0f);\r\n    IMGUI_API bool          TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end = NULL);\r\n    IMGUI_API bool          TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags = 0);                     // Consume previous SetNextItemOpen() data, if any. May return true when logging\r\n    IMGUI_API void          TreePushOverrideID(ImGuiID id);\r\n\r\n    // Template functions are instantiated in imgui_widgets.cpp for a finite number of types.\r\n    // To use them externally (for custom widget) you may need an \"extern template\" statement in your code in order to link to existing instances and silence Clang warnings (see #2036).\r\n    // e.g. \" extern template IMGUI_API float RoundScalarWithFormatT<float, float>(const char* format, ImGuiDataType data_type, float v); \"\r\n    template<typename T, typename SIGNED_T, typename FLOAT_T>   IMGUI_API float ScaleRatioFromValueT(ImGuiDataType data_type, T v, T v_min, T v_max, bool is_logarithmic, float logarithmic_zero_epsilon, float zero_deadzone_size);\r\n    template<typename T, typename SIGNED_T, typename FLOAT_T>   IMGUI_API T     ScaleValueFromRatioT(ImGuiDataType data_type, float t, T v_min, T v_max, bool is_logarithmic, float logarithmic_zero_epsilon, float zero_deadzone_size);\r\n    template<typename T, typename SIGNED_T, typename FLOAT_T>   IMGUI_API bool  DragBehaviorT(ImGuiDataType data_type, T* v, float v_speed, T v_min, T v_max, const char* format, ImGuiSliderFlags flags);\r\n    template<typename T, typename SIGNED_T, typename FLOAT_T>   IMGUI_API bool  SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, T* v, T v_min, T v_max, const char* format, ImGuiSliderFlags flags, ImRect* out_grab_bb);\r\n    template<typename T, typename SIGNED_T>                     IMGUI_API T     RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, T v);\r\n    template<typename T>                                        IMGUI_API bool  CheckboxFlagsT(const char* label, T* flags, T flags_value);\r\n\r\n    // Data type helpers\r\n    IMGUI_API const ImGuiDataTypeInfo*  DataTypeGetInfo(ImGuiDataType data_type);\r\n    IMGUI_API int           DataTypeFormatString(char* buf, int buf_size, ImGuiDataType data_type, const void* p_data, const char* format);\r\n    IMGUI_API void          DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, const void* arg_1, const void* arg_2);\r\n    IMGUI_API bool          DataTypeApplyFromText(const char* buf, ImGuiDataType data_type, void* p_data, const char* format);\r\n    IMGUI_API int           DataTypeCompare(ImGuiDataType data_type, const void* arg_1, const void* arg_2);\r\n    IMGUI_API bool          DataTypeClamp(ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max);\r\n\r\n    // InputText\r\n    IMGUI_API bool          InputTextEx(const char* label, const char* hint, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback = NULL, void* user_data = NULL);\r\n    IMGUI_API bool          TempInputText(const ImRect& bb, ImGuiID id, const char* label, char* buf, int buf_size, ImGuiInputTextFlags flags);\r\n    IMGUI_API bool          TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* p_data, const char* format, const void* p_clamp_min = NULL, const void* p_clamp_max = NULL);\r\n    inline bool             TempInputIsActive(ImGuiID id)       { ImGuiContext& g = *GImGui; return (g.ActiveId == id && g.TempInputId == id); }\r\n    inline ImGuiInputTextState* GetInputTextState(ImGuiID id)   { ImGuiContext& g = *GImGui; return (g.InputTextState.ID == id) ? &g.InputTextState : NULL; } // Get input text state if active\r\n\r\n    // Color\r\n    IMGUI_API void          ColorTooltip(const char* text, const float* col, ImGuiColorEditFlags flags);\r\n    IMGUI_API void          ColorEditOptionsPopup(const float* col, ImGuiColorEditFlags flags);\r\n    IMGUI_API void          ColorPickerOptionsPopup(const float* ref_col, ImGuiColorEditFlags flags);\r\n\r\n    // Plot\r\n    IMGUI_API int           PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 frame_size);\r\n\r\n    // Shade functions (write over already created vertices)\r\n    IMGUI_API void          ShadeVertsLinearColorGradientKeepAlpha(ImDrawList* draw_list, int vert_start_idx, int vert_end_idx, ImVec2 gradient_p0, ImVec2 gradient_p1, ImU32 col0, ImU32 col1);\r\n    IMGUI_API void          ShadeVertsLinearUV(ImDrawList* draw_list, int vert_start_idx, int vert_end_idx, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, bool clamp);\r\n\r\n    // Garbage collection\r\n    IMGUI_API void          GcCompactTransientMiscBuffers();\r\n    IMGUI_API void          GcCompactTransientWindowBuffers(ImGuiWindow* window);\r\n    IMGUI_API void          GcAwakeTransientWindowBuffers(ImGuiWindow* window);\r\n\r\n    // Debug Tools\r\n    IMGUI_API void          ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void* user_data = NULL);\r\n    IMGUI_API void          ErrorCheckEndWindowRecover(ImGuiErrorLogCallback log_callback, void* user_data = NULL);\r\n    inline void             DebugDrawItemRect(ImU32 col = IM_COL32(255,0,0,255))    { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; GetForegroundDrawList(window)->AddRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, col); }\r\n    inline void             DebugStartItemPicker()                                  { ImGuiContext& g = *GImGui; g.DebugItemPickerActive = true; }\r\n\r\n    IMGUI_API void          ShowFontAtlas(ImFontAtlas* atlas);\r\n    IMGUI_API void          DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* data_id, const void* data_id_end);\r\n    IMGUI_API void          DebugNodeColumns(ImGuiOldColumns* columns);\r\n    IMGUI_API void          DebugNodeDrawList(ImGuiWindow* window, const ImDrawList* draw_list, const char* label);\r\n    IMGUI_API void          DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb);\r\n    IMGUI_API void          DebugNodeFont(ImFont* font);\r\n    IMGUI_API void          DebugNodeStorage(ImGuiStorage* storage, const char* label);\r\n    IMGUI_API void          DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label);\r\n    IMGUI_API void          DebugNodeTable(ImGuiTable* table);\r\n    IMGUI_API void          DebugNodeTableSettings(ImGuiTableSettings* settings);\r\n    IMGUI_API void          DebugNodeWindow(ImGuiWindow* window, const char* label);\r\n    IMGUI_API void          DebugNodeWindowSettings(ImGuiWindowSettings* settings);\r\n    IMGUI_API void          DebugNodeWindowsList(ImVector<ImGuiWindow*>* windows, const char* label);\r\n    IMGUI_API void          DebugNodeWindowsListByBeginStackParent(ImGuiWindow** windows, int windows_size, ImGuiWindow* parent_in_begin_stack);\r\n    IMGUI_API void          DebugNodeViewport(ImGuiViewportP* viewport);\r\n    IMGUI_API void          DebugRenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb);\r\n\r\n} // namespace ImGui\r\n\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] ImFontAtlas internal API\r\n//-----------------------------------------------------------------------------\r\n\r\n// This structure is likely to evolve as we add support for incremental atlas updates\r\nstruct ImFontBuilderIO\r\n{\r\n    bool    (*FontBuilder_Build)(ImFontAtlas* atlas);\r\n};\r\n\r\n// Helper for font builder\r\n#ifdef IMGUI_ENABLE_STB_TRUETYPE\r\nIMGUI_API const ImFontBuilderIO* ImFontAtlasGetBuilderForStbTruetype();\r\n#endif\r\nIMGUI_API void      ImFontAtlasBuildInit(ImFontAtlas* atlas);\r\nIMGUI_API void      ImFontAtlasBuildSetupFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* font_config, float ascent, float descent);\r\nIMGUI_API void      ImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas, void* stbrp_context_opaque);\r\nIMGUI_API void      ImFontAtlasBuildFinish(ImFontAtlas* atlas);\r\nIMGUI_API void      ImFontAtlasBuildRender8bppRectFromString(ImFontAtlas* atlas, int x, int y, int w, int h, const char* in_str, char in_marker_char, unsigned char in_marker_pixel_value);\r\nIMGUI_API void      ImFontAtlasBuildRender32bppRectFromString(ImFontAtlas* atlas, int x, int y, int w, int h, const char* in_str, char in_marker_char, unsigned int in_marker_pixel_value);\r\nIMGUI_API void      ImFontAtlasBuildMultiplyCalcLookupTable(unsigned char out_table[256], float in_multiply_factor);\r\nIMGUI_API void      ImFontAtlasBuildMultiplyRectAlpha8(const unsigned char table[256], unsigned char* pixels, int x, int y, int w, int h, int stride);\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Test Engine specific hooks (imgui_test_engine)\r\n//-----------------------------------------------------------------------------\r\n\r\n#ifdef IMGUI_ENABLE_TEST_ENGINE\r\nextern void         ImGuiTestEngineHook_ItemAdd(ImGuiContext* ctx, const ImRect& bb, ImGuiID id);\r\nextern void         ImGuiTestEngineHook_ItemInfo(ImGuiContext* ctx, ImGuiID id, const char* label, ImGuiItemStatusFlags flags);\r\nextern void         ImGuiTestEngineHook_Log(ImGuiContext* ctx, const char* fmt, ...);\r\nextern const char*  ImGuiTestEngine_FindItemDebugLabel(ImGuiContext* ctx, ImGuiID id);\r\n\r\n#define IMGUI_TEST_ENGINE_ITEM_ADD(_BB,_ID)                 if (g.TestEngineHookItems) ImGuiTestEngineHook_ItemAdd(&g, _BB, _ID)               // Register item bounding box\r\n#define IMGUI_TEST_ENGINE_ITEM_INFO(_ID,_LABEL,_FLAGS)      if (g.TestEngineHookItems) ImGuiTestEngineHook_ItemInfo(&g, _ID, _LABEL, _FLAGS)   // Register item label and status flags (optional)\r\n#define IMGUI_TEST_ENGINE_LOG(_FMT,...)                     if (g.TestEngineHookItems) ImGuiTestEngineHook_Log(&g, _FMT, __VA_ARGS__)          // Custom log entry from user land into test log\r\n#else\r\n#define IMGUI_TEST_ENGINE_ITEM_ADD(_BB,_ID)                 ((void)0)\r\n#define IMGUI_TEST_ENGINE_ITEM_INFO(_ID,_LABEL,_FLAGS)      ((void)g)\r\n#endif\r\n\r\n//-----------------------------------------------------------------------------\r\n\r\n#if defined(__clang__)\r\n#pragma clang diagnostic pop\r\n#elif defined(__GNUC__)\r\n#pragma GCC diagnostic pop\r\n#endif\r\n\r\n#ifdef _MSC_VER\r\n#pragma warning (pop)\r\n#endif\r\n\r\n#endif // #ifndef IMGUI_DISABLE\r\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/imgui/imgui_tables.cpp",
    "content": "// dear imgui, v1.87 WIP\r\n// (tables and columns code)\r\n\r\n/*\r\n\r\nIndex of this file:\r\n\r\n// [SECTION] Commentary\r\n// [SECTION] Header mess\r\n// [SECTION] Tables: Main code\r\n// [SECTION] Tables: Simple accessors\r\n// [SECTION] Tables: Row changes\r\n// [SECTION] Tables: Columns changes\r\n// [SECTION] Tables: Columns width management\r\n// [SECTION] Tables: Drawing\r\n// [SECTION] Tables: Sorting\r\n// [SECTION] Tables: Headers\r\n// [SECTION] Tables: Context Menu\r\n// [SECTION] Tables: Settings (.ini data)\r\n// [SECTION] Tables: Garbage Collection\r\n// [SECTION] Tables: Debugging\r\n// [SECTION] Columns, BeginColumns, EndColumns, etc.\r\n\r\n*/\r\n\r\n// Navigating this file:\r\n// - In Visual Studio IDE: CTRL+comma (\"Edit.NavigateTo\") can follow symbols in comments, whereas CTRL+F12 (\"Edit.GoToImplementation\") cannot.\r\n// - With Visual Assist installed: ALT+G (\"VAssistX.GoToImplementation\") can also follow symbols in comments.\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Commentary\r\n//-----------------------------------------------------------------------------\r\n\r\n//-----------------------------------------------------------------------------\r\n// Typical tables call flow: (root level is generally public API):\r\n//-----------------------------------------------------------------------------\r\n// - BeginTable()                               user begin into a table\r\n//    | BeginChild()                            - (if ScrollX/ScrollY is set)\r\n//    | TableBeginInitMemory()                  - first time table is used\r\n//    | TableResetSettings()                    - on settings reset\r\n//    | TableLoadSettings()                     - on settings load\r\n//    | TableBeginApplyRequests()               - apply queued resizing/reordering/hiding requests\r\n//    | - TableSetColumnWidth()                 - apply resizing width (for mouse resize, often requested by previous frame)\r\n//    |    - TableUpdateColumnsWeightFromWidth()- recompute columns weights (of stretch columns) from their respective width\r\n// - TableSetupColumn()                         user submit columns details (optional)\r\n// - TableSetupScrollFreeze()                   user submit scroll freeze information (optional)\r\n//-----------------------------------------------------------------------------\r\n// - TableUpdateLayout() [Internal]             followup to BeginTable(): setup everything: widths, columns positions, clipping rectangles. Automatically called by the FIRST call to TableNextRow() or TableHeadersRow().\r\n//    | TableSetupDrawChannels()                - setup ImDrawList channels\r\n//    | TableUpdateBorders()                    - detect hovering columns for resize, ahead of contents submission\r\n//    | TableDrawContextMenu()                  - draw right-click context menu\r\n//-----------------------------------------------------------------------------\r\n// - TableHeadersRow() or TableHeader()         user submit a headers row (optional)\r\n//    | TableSortSpecsClickColumn()             - when left-clicked: alter sort order and sort direction\r\n//    | TableOpenContextMenu()                  - when right-clicked: trigger opening of the default context menu\r\n// - TableGetSortSpecs()                        user queries updated sort specs (optional, generally after submitting headers)\r\n// - TableNextRow()                             user begin into a new row (also automatically called by TableHeadersRow())\r\n//    | TableEndRow()                           - finish existing row\r\n//    | TableBeginRow()                         - add a new row\r\n// - TableSetColumnIndex() / TableNextColumn()  user begin into a cell\r\n//    | TableEndCell()                          - close existing column/cell\r\n//    | TableBeginCell()                        - enter into current column/cell\r\n// - [...]                                      user emit contents\r\n//-----------------------------------------------------------------------------\r\n// - EndTable()                                 user ends the table\r\n//    | TableDrawBorders()                      - draw outer borders, inner vertical borders\r\n//    | TableMergeDrawChannels()                - merge draw channels if clipping isn't required\r\n//    | EndChild()                              - (if ScrollX/ScrollY is set)\r\n//-----------------------------------------------------------------------------\r\n\r\n//-----------------------------------------------------------------------------\r\n// TABLE SIZING\r\n//-----------------------------------------------------------------------------\r\n// (Read carefully because this is subtle but it does make sense!)\r\n//-----------------------------------------------------------------------------\r\n// About 'outer_size':\r\n// Its meaning needs to differ slightly depending on if we are using ScrollX/ScrollY flags.\r\n// Default value is ImVec2(0.0f, 0.0f).\r\n//   X\r\n//   - outer_size.x <= 0.0f  ->  Right-align from window/work-rect right-most edge. With -FLT_MIN or 0.0f will align exactly on right-most edge.\r\n//   - outer_size.x  > 0.0f  ->  Set Fixed width.\r\n//   Y with ScrollX/ScrollY disabled: we output table directly in current window\r\n//   - outer_size.y  < 0.0f  ->  Bottom-align (but will auto extend, unless _NoHostExtendY is set). Not meaningful is parent window can vertically scroll.\r\n//   - outer_size.y  = 0.0f  ->  No minimum height (but will auto extend, unless _NoHostExtendY is set)\r\n//   - outer_size.y  > 0.0f  ->  Set Minimum height (but will auto extend, unless _NoHostExtenY is set)\r\n//   Y with ScrollX/ScrollY enabled: using a child window for scrolling\r\n//   - outer_size.y  < 0.0f  ->  Bottom-align. Not meaningful is parent window can vertically scroll.\r\n//   - outer_size.y  = 0.0f  ->  Bottom-align, consistent with BeginChild(). Not recommended unless table is last item in parent window.\r\n//   - outer_size.y  > 0.0f  ->  Set Exact height. Recommended when using Scrolling on any axis.\r\n//-----------------------------------------------------------------------------\r\n// Outer size is also affected by the NoHostExtendX/NoHostExtendY flags.\r\n// Important to that note how the two flags have slightly different behaviors!\r\n//   - ImGuiTableFlags_NoHostExtendX -> Make outer width auto-fit to columns (overriding outer_size.x value). Only available when ScrollX/ScrollY are disabled and Stretch columns are not used.\r\n//   - ImGuiTableFlags_NoHostExtendY -> Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit). Only available when ScrollX/ScrollY is disabled. Data below the limit will be clipped and not visible.\r\n// In theory ImGuiTableFlags_NoHostExtendY could be the default and any non-scrolling tables with outer_size.y != 0.0f would use exact height.\r\n// This would be consistent but perhaps less useful and more confusing (as vertically clipped items are not easily noticeable)\r\n//-----------------------------------------------------------------------------\r\n// About 'inner_width':\r\n//   With ScrollX disabled:\r\n//   - inner_width          ->  *ignored*\r\n//   With ScrollX enabled:\r\n//   - inner_width  < 0.0f  ->  *illegal* fit in known width (right align from outer_size.x) <-- weird\r\n//   - inner_width  = 0.0f  ->  fit in outer_width: Fixed size columns will take space they need (if avail, otherwise shrink down), Stretch columns becomes Fixed columns.\r\n//   - inner_width  > 0.0f  ->  override scrolling width, generally to be larger than outer_size.x. Fixed column take space they need (if avail, otherwise shrink down), Stretch columns share remaining space!\r\n//-----------------------------------------------------------------------------\r\n// Details:\r\n// - If you want to use Stretch columns with ScrollX, you generally need to specify 'inner_width' otherwise the concept\r\n//   of \"available space\" doesn't make sense.\r\n// - Even if not really useful, we allow 'inner_width < outer_size.x' for consistency and to facilitate understanding\r\n//   of what the value does.\r\n//-----------------------------------------------------------------------------\r\n\r\n//-----------------------------------------------------------------------------\r\n// COLUMNS SIZING POLICIES\r\n//-----------------------------------------------------------------------------\r\n// About overriding column sizing policy and width/weight with TableSetupColumn():\r\n// We use a default parameter of 'init_width_or_weight == -1'.\r\n//   - with ImGuiTableColumnFlags_WidthFixed,    init_width  <= 0 (default)  --> width is automatic\r\n//   - with ImGuiTableColumnFlags_WidthFixed,    init_width  >  0 (explicit) --> width is custom\r\n//   - with ImGuiTableColumnFlags_WidthStretch,  init_weight <= 0 (default)  --> weight is 1.0f\r\n//   - with ImGuiTableColumnFlags_WidthStretch,  init_weight >  0 (explicit) --> weight is custom\r\n// Widths are specified _without_ CellPadding. If you specify a width of 100.0f, the column will be cover (100.0f + Padding * 2.0f)\r\n// and you can fit a 100.0f wide item in it without clipping and with full padding.\r\n//-----------------------------------------------------------------------------\r\n// About default sizing policy (if you don't specify a ImGuiTableColumnFlags_WidthXXXX flag)\r\n//   - with Table policy ImGuiTableFlags_SizingFixedFit      --> default Column policy is ImGuiTableColumnFlags_WidthFixed, default Width is equal to contents width\r\n//   - with Table policy ImGuiTableFlags_SizingFixedSame     --> default Column policy is ImGuiTableColumnFlags_WidthFixed, default Width is max of all contents width\r\n//   - with Table policy ImGuiTableFlags_SizingStretchSame   --> default Column policy is ImGuiTableColumnFlags_WidthStretch, default Weight is 1.0f\r\n//   - with Table policy ImGuiTableFlags_SizingStretchWeight --> default Column policy is ImGuiTableColumnFlags_WidthStretch, default Weight is proportional to contents\r\n// Default Width and default Weight can be overridden when calling TableSetupColumn().\r\n//-----------------------------------------------------------------------------\r\n// About mixing Fixed/Auto and Stretch columns together:\r\n//   - the typical use of mixing sizing policies is: any number of LEADING Fixed columns, followed by one or two TRAILING Stretch columns.\r\n//   - using mixed policies with ScrollX does not make much sense, as using Stretch columns with ScrollX does not make much sense in the first place!\r\n//     that is, unless 'inner_width' is passed to BeginTable() to explicitly provide a total width to layout columns in.\r\n//   - when using ImGuiTableFlags_SizingFixedSame with mixed columns, only the Fixed/Auto columns will match their widths to the width of the maximum contents.\r\n//   - when using ImGuiTableFlags_SizingStretchSame with mixed columns, only the Stretch columns will match their weight/widths.\r\n//-----------------------------------------------------------------------------\r\n// About using column width:\r\n// If a column is manual resizable or has a width specified with TableSetupColumn():\r\n//   - you may use GetContentRegionAvail().x to query the width available in a given column.\r\n//   - right-side alignment features such as SetNextItemWidth(-x) or PushItemWidth(-x) will rely on this width.\r\n// If the column is not resizable and has no width specified with TableSetupColumn():\r\n//   - its width will be automatic and be set to the max of items submitted.\r\n//   - therefore you generally cannot have ALL items of the columns use e.g. SetNextItemWidth(-FLT_MIN).\r\n//   - but if the column has one or more items of known/fixed size, this will become the reference width used by SetNextItemWidth(-FLT_MIN).\r\n//-----------------------------------------------------------------------------\r\n\r\n\r\n//-----------------------------------------------------------------------------\r\n// TABLES CLIPPING/CULLING\r\n//-----------------------------------------------------------------------------\r\n// About clipping/culling of Rows in Tables:\r\n// - For large numbers of rows, it is recommended you use ImGuiListClipper to only submit visible rows.\r\n//   ImGuiListClipper is reliant on the fact that rows are of equal height.\r\n//   See 'Demo->Tables->Vertical Scrolling' or 'Demo->Tables->Advanced' for a demo of using the clipper.\r\n// - Note that auto-resizing columns don't play well with using the clipper.\r\n//   By default a table with _ScrollX but without _Resizable will have column auto-resize.\r\n//   So, if you want to use the clipper, make sure to either enable _Resizable, either setup columns width explicitly with _WidthFixed.\r\n//-----------------------------------------------------------------------------\r\n// About clipping/culling of Columns in Tables:\r\n// - Both TableSetColumnIndex() and TableNextColumn() return true when the column is visible or performing\r\n//   width measurements. Otherwise, you may skip submitting the contents of a cell/column, BUT ONLY if you know\r\n//   it is not going to contribute to row height.\r\n//   In many situations, you may skip submitting contents for every column but one (e.g. the first one).\r\n// - Case A: column is not hidden by user, and at least partially in sight (most common case).\r\n// - Case B: column is clipped / out of sight (because of scrolling or parent ClipRect): TableNextColumn() return false as a hint but we still allow layout output.\r\n// - Case C: column is hidden explicitly by the user (e.g. via the context menu, or _DefaultHide column flag, etc.).\r\n//\r\n//                        [A]         [B]          [C]\r\n//  TableNextColumn():    true        false        false       -> [userland] when TableNextColumn() / TableSetColumnIndex() return false, user can skip submitting items but only if the column doesn't contribute to row height.\r\n//          SkipItems:    false       false        true        -> [internal] when SkipItems is true, most widgets will early out if submitted, resulting is no layout output.\r\n//           ClipRect:    normal      zero-width   zero-width  -> [internal] when ClipRect is zero, ItemAdd() will return false and most widgets will early out mid-way.\r\n//  ImDrawList output:    normal      dummy        dummy       -> [internal] when using the dummy channel, ImDrawList submissions (if any) will be wasted (because cliprect is zero-width anyway).\r\n//\r\n// - We need to distinguish those cases because non-hidden columns that are clipped outside of scrolling bounds should still contribute their height to the row.\r\n//   However, in the majority of cases, the contribution to row height is the same for all columns, or the tallest cells are known by the programmer.\r\n//-----------------------------------------------------------------------------\r\n// About clipping/culling of whole Tables:\r\n// - Scrolling tables with a known outer size can be clipped earlier as BeginTable() will return false.\r\n//-----------------------------------------------------------------------------\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Header mess\r\n//-----------------------------------------------------------------------------\r\n\r\n#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)\r\n#define _CRT_SECURE_NO_WARNINGS\r\n#endif\r\n\r\n#include \"imgui.h\"\r\n#ifndef IMGUI_DISABLE\r\n\r\n#ifndef IMGUI_DEFINE_MATH_OPERATORS\r\n#define IMGUI_DEFINE_MATH_OPERATORS\r\n#endif\r\n#include \"imgui_internal.h\"\r\n\r\n// System includes\r\n#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier\r\n#include <stddef.h>     // intptr_t\r\n#else\r\n#include <stdint.h>     // intptr_t\r\n#endif\r\n\r\n// Visual Studio warnings\r\n#ifdef _MSC_VER\r\n#pragma warning (disable: 4127)     // condition expression is constant\r\n#pragma warning (disable: 4996)     // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen\r\n#if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later\r\n#pragma warning (disable: 5054)     // operator '|': deprecated between enumerations of different types\r\n#endif\r\n#pragma warning (disable: 26451)    // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to a 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2).\r\n#pragma warning (disable: 26812)    // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).\r\n#endif\r\n\r\n// Clang/GCC warnings with -Weverything\r\n#if defined(__clang__)\r\n#if __has_warning(\"-Wunknown-warning-option\")\r\n#pragma clang diagnostic ignored \"-Wunknown-warning-option\"         // warning: unknown warning group 'xxx'                      // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great!\r\n#endif\r\n#pragma clang diagnostic ignored \"-Wunknown-pragmas\"                // warning: unknown warning group 'xxx'\r\n#pragma clang diagnostic ignored \"-Wold-style-cast\"                 // warning: use of old-style cast                            // yes, they are more terse.\r\n#pragma clang diagnostic ignored \"-Wfloat-equal\"                    // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok.\r\n#pragma clang diagnostic ignored \"-Wformat-nonliteral\"              // warning: format string is not a string literal            // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code.\r\n#pragma clang diagnostic ignored \"-Wsign-conversion\"                // warning: implicit conversion changes signedness\r\n#pragma clang diagnostic ignored \"-Wzero-as-null-pointer-constant\"  // warning: zero as null pointer constant                    // some standard header variations use #define NULL 0\r\n#pragma clang diagnostic ignored \"-Wdouble-promotion\"               // warning: implicit conversion from 'float' to 'double' when passing argument to function  // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.\r\n#pragma clang diagnostic ignored \"-Wenum-enum-conversion\"           // warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_')\r\n#pragma clang diagnostic ignored \"-Wdeprecated-enum-enum-conversion\"// warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated\r\n#pragma clang diagnostic ignored \"-Wimplicit-int-float-conversion\"  // warning: implicit conversion from 'xxx' to 'float' may lose precision\r\n#elif defined(__GNUC__)\r\n#pragma GCC diagnostic ignored \"-Wpragmas\"                          // warning: unknown option after '#pragma GCC diagnostic' kind\r\n#pragma GCC diagnostic ignored \"-Wformat-nonliteral\"                // warning: format not a string literal, format string not checked\r\n#pragma GCC diagnostic ignored \"-Wclass-memaccess\"                  // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead\r\n#endif\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Tables: Main code\r\n//-----------------------------------------------------------------------------\r\n// - TableFixFlags() [Internal]\r\n// - TableFindByID() [Internal]\r\n// - BeginTable()\r\n// - BeginTableEx() [Internal]\r\n// - TableBeginInitMemory() [Internal]\r\n// - TableBeginApplyRequests() [Internal]\r\n// - TableSetupColumnFlags() [Internal]\r\n// - TableUpdateLayout() [Internal]\r\n// - TableUpdateBorders() [Internal]\r\n// - EndTable()\r\n// - TableSetupColumn()\r\n// - TableSetupScrollFreeze()\r\n//-----------------------------------------------------------------------------\r\n\r\n// Configuration\r\nstatic const int TABLE_DRAW_CHANNEL_BG0 = 0;\r\nstatic const int TABLE_DRAW_CHANNEL_BG2_FROZEN = 1;\r\nstatic const int TABLE_DRAW_CHANNEL_NOCLIP = 2;                     // When using ImGuiTableFlags_NoClip (this becomes the last visible channel)\r\nstatic const float TABLE_BORDER_SIZE                     = 1.0f;    // FIXME-TABLE: Currently hard-coded because of clipping assumptions with outer borders rendering.\r\nstatic const float TABLE_RESIZE_SEPARATOR_HALF_THICKNESS = 4.0f;    // Extend outside inner borders.\r\nstatic const float TABLE_RESIZE_SEPARATOR_FEEDBACK_TIMER = 0.06f;   // Delay/timer before making the hover feedback (color+cursor) visible because tables/columns tends to be more cramped.\r\n\r\n// Helper\r\ninline ImGuiTableFlags TableFixFlags(ImGuiTableFlags flags, ImGuiWindow* outer_window)\r\n{\r\n    // Adjust flags: set default sizing policy\r\n    if ((flags & ImGuiTableFlags_SizingMask_) == 0)\r\n        flags |= ((flags & ImGuiTableFlags_ScrollX) || (outer_window->Flags & ImGuiWindowFlags_AlwaysAutoResize)) ? ImGuiTableFlags_SizingFixedFit : ImGuiTableFlags_SizingStretchSame;\r\n\r\n    // Adjust flags: enable NoKeepColumnsVisible when using ImGuiTableFlags_SizingFixedSame\r\n    if ((flags & ImGuiTableFlags_SizingMask_) == ImGuiTableFlags_SizingFixedSame)\r\n        flags |= ImGuiTableFlags_NoKeepColumnsVisible;\r\n\r\n    // Adjust flags: enforce borders when resizable\r\n    if (flags & ImGuiTableFlags_Resizable)\r\n        flags |= ImGuiTableFlags_BordersInnerV;\r\n\r\n    // Adjust flags: disable NoHostExtendX/NoHostExtendY if we have any scrolling going on\r\n    if (flags & (ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY))\r\n        flags &= ~(ImGuiTableFlags_NoHostExtendX | ImGuiTableFlags_NoHostExtendY);\r\n\r\n    // Adjust flags: NoBordersInBodyUntilResize takes priority over NoBordersInBody\r\n    if (flags & ImGuiTableFlags_NoBordersInBodyUntilResize)\r\n        flags &= ~ImGuiTableFlags_NoBordersInBody;\r\n\r\n    // Adjust flags: disable saved settings if there's nothing to save\r\n    if ((flags & (ImGuiTableFlags_Resizable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Sortable)) == 0)\r\n        flags |= ImGuiTableFlags_NoSavedSettings;\r\n\r\n    // Inherit _NoSavedSettings from top-level window (child windows always have _NoSavedSettings set)\r\n    if (outer_window->RootWindow->Flags & ImGuiWindowFlags_NoSavedSettings)\r\n        flags |= ImGuiTableFlags_NoSavedSettings;\r\n\r\n    return flags;\r\n}\r\n\r\nImGuiTable* ImGui::TableFindByID(ImGuiID id)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    return g.Tables.GetByKey(id);\r\n}\r\n\r\n// Read about \"TABLE SIZING\" at the top of this file.\r\nbool    ImGui::BeginTable(const char* str_id, int columns_count, ImGuiTableFlags flags, const ImVec2& outer_size, float inner_width)\r\n{\r\n    ImGuiID id = GetID(str_id);\r\n    return BeginTableEx(str_id, id, columns_count, flags, outer_size, inner_width);\r\n}\r\n\r\nbool    ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImGuiTableFlags flags, const ImVec2& outer_size, float inner_width)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* outer_window = GetCurrentWindow();\r\n    if (outer_window->SkipItems) // Consistent with other tables + beneficial side effect that assert on miscalling EndTable() will be more visible.\r\n        return false;\r\n\r\n    // Sanity checks\r\n    IM_ASSERT(columns_count > 0 && columns_count <= IMGUI_TABLE_MAX_COLUMNS && \"Only 1..64 columns allowed!\");\r\n    if (flags & ImGuiTableFlags_ScrollX)\r\n        IM_ASSERT(inner_width >= 0.0f);\r\n\r\n    // If an outer size is specified ahead we will be able to early out when not visible. Exact clipping rules may evolve.\r\n    const bool use_child_window = (flags & (ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY)) != 0;\r\n    const ImVec2 avail_size = GetContentRegionAvail();\r\n    ImVec2 actual_outer_size = CalcItemSize(outer_size, ImMax(avail_size.x, 1.0f), use_child_window ? ImMax(avail_size.y, 1.0f) : 0.0f);\r\n    ImRect outer_rect(outer_window->DC.CursorPos, outer_window->DC.CursorPos + actual_outer_size);\r\n    if (use_child_window && IsClippedEx(outer_rect, 0))\r\n    {\r\n        ItemSize(outer_rect);\r\n        return false;\r\n    }\r\n\r\n    // Acquire storage for the table\r\n    ImGuiTable* table = g.Tables.GetOrAddByKey(id);\r\n    const int instance_no = (table->LastFrameActive != g.FrameCount) ? 0 : table->InstanceCurrent + 1;\r\n    const ImGuiID instance_id = id + instance_no;\r\n    const ImGuiTableFlags table_last_flags = table->Flags;\r\n    if (instance_no > 0)\r\n        IM_ASSERT(table->ColumnsCount == columns_count && \"BeginTable(): Cannot change columns count mid-frame while preserving same ID\");\r\n\r\n    // Acquire temporary buffers\r\n    const int table_idx = g.Tables.GetIndex(table);\r\n    if (++g.TablesTempDataStacked > g.TablesTempData.Size)\r\n        g.TablesTempData.resize(g.TablesTempDataStacked, ImGuiTableTempData());\r\n    ImGuiTableTempData* temp_data = table->TempData = &g.TablesTempData[g.TablesTempDataStacked - 1];\r\n    temp_data->TableIndex = table_idx;\r\n    table->DrawSplitter = &table->TempData->DrawSplitter;\r\n    table->DrawSplitter->Clear();\r\n\r\n    // Fix flags\r\n    table->IsDefaultSizingPolicy = (flags & ImGuiTableFlags_SizingMask_) == 0;\r\n    flags = TableFixFlags(flags, outer_window);\r\n\r\n    // Initialize\r\n    table->ID = id;\r\n    table->Flags = flags;\r\n    table->InstanceCurrent = (ImS16)instance_no;\r\n    table->LastFrameActive = g.FrameCount;\r\n    table->OuterWindow = table->InnerWindow = outer_window;\r\n    table->ColumnsCount = columns_count;\r\n    table->IsLayoutLocked = false;\r\n    table->InnerWidth = inner_width;\r\n    temp_data->UserOuterSize = outer_size;\r\n\r\n    // When not using a child window, WorkRect.Max will grow as we append contents.\r\n    if (use_child_window)\r\n    {\r\n        // Ensure no vertical scrollbar appears if we only want horizontal one, to make flag consistent\r\n        // (we have no other way to disable vertical scrollbar of a window while keeping the horizontal one showing)\r\n        ImVec2 override_content_size(FLT_MAX, FLT_MAX);\r\n        if ((flags & ImGuiTableFlags_ScrollX) && !(flags & ImGuiTableFlags_ScrollY))\r\n            override_content_size.y = FLT_MIN;\r\n\r\n        // Ensure specified width (when not specified, Stretched columns will act as if the width == OuterWidth and\r\n        // never lead to any scrolling). We don't handle inner_width < 0.0f, we could potentially use it to right-align\r\n        // based on the right side of the child window work rect, which would require knowing ahead if we are going to\r\n        // have decoration taking horizontal spaces (typically a vertical scrollbar).\r\n        if ((flags & ImGuiTableFlags_ScrollX) && inner_width > 0.0f)\r\n            override_content_size.x = inner_width;\r\n\r\n        if (override_content_size.x != FLT_MAX || override_content_size.y != FLT_MAX)\r\n            SetNextWindowContentSize(ImVec2(override_content_size.x != FLT_MAX ? override_content_size.x : 0.0f, override_content_size.y != FLT_MAX ? override_content_size.y : 0.0f));\r\n\r\n        // Reset scroll if we are reactivating it\r\n        if ((table_last_flags & (ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY)) == 0)\r\n            SetNextWindowScroll(ImVec2(0.0f, 0.0f));\r\n\r\n        // Create scrolling region (without border and zero window padding)\r\n        ImGuiWindowFlags child_flags = (flags & ImGuiTableFlags_ScrollX) ? ImGuiWindowFlags_HorizontalScrollbar : ImGuiWindowFlags_None;\r\n        BeginChildEx(name, instance_id, outer_rect.GetSize(), false, child_flags);\r\n        table->InnerWindow = g.CurrentWindow;\r\n        table->WorkRect = table->InnerWindow->WorkRect;\r\n        table->OuterRect = table->InnerWindow->Rect();\r\n        table->InnerRect = table->InnerWindow->InnerRect;\r\n        IM_ASSERT(table->InnerWindow->WindowPadding.x == 0.0f && table->InnerWindow->WindowPadding.y == 0.0f && table->InnerWindow->WindowBorderSize == 0.0f);\r\n    }\r\n    else\r\n    {\r\n        // For non-scrolling tables, WorkRect == OuterRect == InnerRect.\r\n        // But at this point we do NOT have a correct value for .Max.y (unless a height has been explicitly passed in). It will only be updated in EndTable().\r\n        table->WorkRect = table->OuterRect = table->InnerRect = outer_rect;\r\n    }\r\n\r\n    // Push a standardized ID for both child-using and not-child-using tables\r\n    PushOverrideID(instance_id);\r\n\r\n    // Backup a copy of host window members we will modify\r\n    ImGuiWindow* inner_window = table->InnerWindow;\r\n    table->HostIndentX = inner_window->DC.Indent.x;\r\n    table->HostClipRect = inner_window->ClipRect;\r\n    table->HostSkipItems = inner_window->SkipItems;\r\n    temp_data->HostBackupWorkRect = inner_window->WorkRect;\r\n    temp_data->HostBackupParentWorkRect = inner_window->ParentWorkRect;\r\n    temp_data->HostBackupColumnsOffset = outer_window->DC.ColumnsOffset;\r\n    temp_data->HostBackupPrevLineSize = inner_window->DC.PrevLineSize;\r\n    temp_data->HostBackupCurrLineSize = inner_window->DC.CurrLineSize;\r\n    temp_data->HostBackupCursorMaxPos = inner_window->DC.CursorMaxPos;\r\n    temp_data->HostBackupItemWidth = outer_window->DC.ItemWidth;\r\n    temp_data->HostBackupItemWidthStackSize = outer_window->DC.ItemWidthStack.Size;\r\n    inner_window->DC.PrevLineSize = inner_window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);\r\n\r\n    // Padding and Spacing\r\n    // - None               ........Content..... Pad .....Content........\r\n    // - PadOuter           | Pad ..Content..... Pad .....Content.. Pad |\r\n    // - PadInner           ........Content.. Pad | Pad ..Content........\r\n    // - PadOuter+PadInner  | Pad ..Content.. Pad | Pad ..Content.. Pad |\r\n    const bool pad_outer_x = (flags & ImGuiTableFlags_NoPadOuterX) ? false : (flags & ImGuiTableFlags_PadOuterX) ? true : (flags & ImGuiTableFlags_BordersOuterV) != 0;\r\n    const bool pad_inner_x = (flags & ImGuiTableFlags_NoPadInnerX) ? false : true;\r\n    const float inner_spacing_for_border = (flags & ImGuiTableFlags_BordersInnerV) ? TABLE_BORDER_SIZE : 0.0f;\r\n    const float inner_spacing_explicit = (pad_inner_x && (flags & ImGuiTableFlags_BordersInnerV) == 0) ? g.Style.CellPadding.x : 0.0f;\r\n    const float inner_padding_explicit = (pad_inner_x && (flags & ImGuiTableFlags_BordersInnerV) != 0) ? g.Style.CellPadding.x : 0.0f;\r\n    table->CellSpacingX1 = inner_spacing_explicit + inner_spacing_for_border;\r\n    table->CellSpacingX2 = inner_spacing_explicit;\r\n    table->CellPaddingX = inner_padding_explicit;\r\n    table->CellPaddingY = g.Style.CellPadding.y;\r\n\r\n    const float outer_padding_for_border = (flags & ImGuiTableFlags_BordersOuterV) ? TABLE_BORDER_SIZE : 0.0f;\r\n    const float outer_padding_explicit = pad_outer_x ? g.Style.CellPadding.x : 0.0f;\r\n    table->OuterPaddingX = (outer_padding_for_border + outer_padding_explicit) - table->CellPaddingX;\r\n\r\n    table->CurrentColumn = -1;\r\n    table->CurrentRow = -1;\r\n    table->RowBgColorCounter = 0;\r\n    table->LastRowFlags = ImGuiTableRowFlags_None;\r\n    table->InnerClipRect = (inner_window == outer_window) ? table->WorkRect : inner_window->ClipRect;\r\n    table->InnerClipRect.ClipWith(table->WorkRect);     // We need this to honor inner_width\r\n    table->InnerClipRect.ClipWithFull(table->HostClipRect);\r\n    table->InnerClipRect.Max.y = (flags & ImGuiTableFlags_NoHostExtendY) ? ImMin(table->InnerClipRect.Max.y, inner_window->WorkRect.Max.y) : inner_window->ClipRect.Max.y;\r\n\r\n    table->RowPosY1 = table->RowPosY2 = table->WorkRect.Min.y; // This is needed somehow\r\n    table->RowTextBaseline = 0.0f; // This will be cleared again by TableBeginRow()\r\n    table->FreezeRowsRequest = table->FreezeRowsCount = 0; // This will be setup by TableSetupScrollFreeze(), if any\r\n    table->FreezeColumnsRequest = table->FreezeColumnsCount = 0;\r\n    table->IsUnfrozenRows = true;\r\n    table->DeclColumnsCount = 0;\r\n\r\n    // Using opaque colors facilitate overlapping elements of the grid\r\n    table->BorderColorStrong = GetColorU32(ImGuiCol_TableBorderStrong);\r\n    table->BorderColorLight = GetColorU32(ImGuiCol_TableBorderLight);\r\n\r\n    // Make table current\r\n    g.CurrentTable = table;\r\n    outer_window->DC.CurrentTableIdx = table_idx;\r\n    if (inner_window != outer_window) // So EndChild() within the inner window can restore the table properly.\r\n        inner_window->DC.CurrentTableIdx = table_idx;\r\n\r\n    if ((table_last_flags & ImGuiTableFlags_Reorderable) && (flags & ImGuiTableFlags_Reorderable) == 0)\r\n        table->IsResetDisplayOrderRequest = true;\r\n\r\n    // Mark as used\r\n    if (table_idx >= g.TablesLastTimeActive.Size)\r\n        g.TablesLastTimeActive.resize(table_idx + 1, -1.0f);\r\n    g.TablesLastTimeActive[table_idx] = (float)g.Time;\r\n    temp_data->LastTimeActive = (float)g.Time;\r\n    table->MemoryCompacted = false;\r\n\r\n    // Setup memory buffer (clear data if columns count changed)\r\n    ImGuiTableColumn* old_columns_to_preserve = NULL;\r\n    void* old_columns_raw_data = NULL;\r\n    const int old_columns_count = table->Columns.size();\r\n    if (old_columns_count != 0 && old_columns_count != columns_count)\r\n    {\r\n        // Attempt to preserve width on column count change (#4046)\r\n        old_columns_to_preserve = table->Columns.Data;\r\n        old_columns_raw_data = table->RawData;\r\n        table->RawData = NULL;\r\n    }\r\n    if (table->RawData == NULL)\r\n    {\r\n        TableBeginInitMemory(table, columns_count);\r\n        table->IsInitializing = table->IsSettingsRequestLoad = true;\r\n    }\r\n    if (table->IsResetAllRequest)\r\n        TableResetSettings(table);\r\n    if (table->IsInitializing)\r\n    {\r\n        // Initialize\r\n        table->SettingsOffset = -1;\r\n        table->IsSortSpecsDirty = true;\r\n        table->InstanceInteracted = -1;\r\n        table->ContextPopupColumn = -1;\r\n        table->ReorderColumn = table->ResizedColumn = table->LastResizedColumn = -1;\r\n        table->AutoFitSingleColumn = -1;\r\n        table->HoveredColumnBody = table->HoveredColumnBorder = -1;\r\n        for (int n = 0; n < columns_count; n++)\r\n        {\r\n            ImGuiTableColumn* column = &table->Columns[n];\r\n            if (old_columns_to_preserve && n < old_columns_count)\r\n            {\r\n                // FIXME: We don't attempt to preserve column order in this path.\r\n                *column = old_columns_to_preserve[n];\r\n            }\r\n            else\r\n            {\r\n                float width_auto = column->WidthAuto;\r\n                *column = ImGuiTableColumn();\r\n                column->WidthAuto = width_auto;\r\n                column->IsPreserveWidthAuto = true; // Preserve WidthAuto when reinitializing a live table: not technically necessary but remove a visible flicker\r\n                column->IsEnabled = column->IsUserEnabled = column->IsUserEnabledNextFrame = true;\r\n            }\r\n            column->DisplayOrder = table->DisplayOrderToIndex[n] = (ImGuiTableColumnIdx)n;\r\n        }\r\n    }\r\n    if (old_columns_raw_data)\r\n        IM_FREE(old_columns_raw_data);\r\n\r\n    // Load settings\r\n    if (table->IsSettingsRequestLoad)\r\n        TableLoadSettings(table);\r\n\r\n    // Handle DPI/font resize\r\n    // This is designed to facilitate DPI changes with the assumption that e.g. style.CellPadding has been scaled as well.\r\n    // It will also react to changing fonts with mixed results. It doesn't need to be perfect but merely provide a decent transition.\r\n    // FIXME-DPI: Provide consistent standards for reference size. Perhaps using g.CurrentDpiScale would be more self explanatory.\r\n    // This is will lead us to non-rounded WidthRequest in columns, which should work but is a poorly tested path.\r\n    const float new_ref_scale_unit = g.FontSize; // g.Font->GetCharAdvance('A') ?\r\n    if (table->RefScale != 0.0f && table->RefScale != new_ref_scale_unit)\r\n    {\r\n        const float scale_factor = new_ref_scale_unit / table->RefScale;\r\n        //IMGUI_DEBUG_LOG(\"[table] %08X RefScaleUnit %.3f -> %.3f, scaling width by %.3f\\n\", table->ID, table->RefScaleUnit, new_ref_scale_unit, scale_factor);\r\n        for (int n = 0; n < columns_count; n++)\r\n            table->Columns[n].WidthRequest = table->Columns[n].WidthRequest * scale_factor;\r\n    }\r\n    table->RefScale = new_ref_scale_unit;\r\n\r\n    // Disable output until user calls TableNextRow() or TableNextColumn() leading to the TableUpdateLayout() call..\r\n    // This is not strictly necessary but will reduce cases were \"out of table\" output will be misleading to the user.\r\n    // Because we cannot safely assert in EndTable() when no rows have been created, this seems like our best option.\r\n    inner_window->SkipItems = true;\r\n\r\n    // Clear names\r\n    // At this point the ->NameOffset field of each column will be invalid until TableUpdateLayout() or the first call to TableSetupColumn()\r\n    if (table->ColumnsNames.Buf.Size > 0)\r\n        table->ColumnsNames.Buf.resize(0);\r\n\r\n    // Apply queued resizing/reordering/hiding requests\r\n    TableBeginApplyRequests(table);\r\n\r\n    return true;\r\n}\r\n\r\n// For reference, the average total _allocation count_ for a table is:\r\n// + 0 (for ImGuiTable instance, we are pooling allocations in g.Tables)\r\n// + 1 (for table->RawData allocated below)\r\n// + 1 (for table->ColumnsNames, if names are used)\r\n// Shared allocations per number of nested tables\r\n// + 1 (for table->Splitter._Channels)\r\n// + 2 * active_channels_count (for ImDrawCmd and ImDrawIdx buffers inside channels)\r\n// Where active_channels_count is variable but often == columns_count or columns_count + 1, see TableSetupDrawChannels() for details.\r\n// Unused channels don't perform their +2 allocations.\r\nvoid ImGui::TableBeginInitMemory(ImGuiTable* table, int columns_count)\r\n{\r\n    // Allocate single buffer for our arrays\r\n    ImSpanAllocator<3> span_allocator;\r\n    span_allocator.Reserve(0, columns_count * sizeof(ImGuiTableColumn));\r\n    span_allocator.Reserve(1, columns_count * sizeof(ImGuiTableColumnIdx));\r\n    span_allocator.Reserve(2, columns_count * sizeof(ImGuiTableCellData), 4);\r\n    table->RawData = IM_ALLOC(span_allocator.GetArenaSizeInBytes());\r\n    memset(table->RawData, 0, span_allocator.GetArenaSizeInBytes());\r\n    span_allocator.SetArenaBasePtr(table->RawData);\r\n    span_allocator.GetSpan(0, &table->Columns);\r\n    span_allocator.GetSpan(1, &table->DisplayOrderToIndex);\r\n    span_allocator.GetSpan(2, &table->RowCellData);\r\n}\r\n\r\n// Apply queued resizing/reordering/hiding requests\r\nvoid ImGui::TableBeginApplyRequests(ImGuiTable* table)\r\n{\r\n    // Handle resizing request\r\n    // (We process this at the first TableBegin of the frame)\r\n    // FIXME-TABLE: Contains columns if our work area doesn't allow for scrolling?\r\n    if (table->InstanceCurrent == 0)\r\n    {\r\n        if (table->ResizedColumn != -1 && table->ResizedColumnNextWidth != FLT_MAX)\r\n            TableSetColumnWidth(table->ResizedColumn, table->ResizedColumnNextWidth);\r\n        table->LastResizedColumn = table->ResizedColumn;\r\n        table->ResizedColumnNextWidth = FLT_MAX;\r\n        table->ResizedColumn = -1;\r\n\r\n        // Process auto-fit for single column, which is a special case for stretch columns and fixed columns with FixedSame policy.\r\n        // FIXME-TABLE: Would be nice to redistribute available stretch space accordingly to other weights, instead of giving it all to siblings.\r\n        if (table->AutoFitSingleColumn != -1)\r\n        {\r\n            TableSetColumnWidth(table->AutoFitSingleColumn, table->Columns[table->AutoFitSingleColumn].WidthAuto);\r\n            table->AutoFitSingleColumn = -1;\r\n        }\r\n    }\r\n\r\n    // Handle reordering request\r\n    // Note: we don't clear ReorderColumn after handling the request.\r\n    if (table->InstanceCurrent == 0)\r\n    {\r\n        if (table->HeldHeaderColumn == -1 && table->ReorderColumn != -1)\r\n            table->ReorderColumn = -1;\r\n        table->HeldHeaderColumn = -1;\r\n        if (table->ReorderColumn != -1 && table->ReorderColumnDir != 0)\r\n        {\r\n            // We need to handle reordering across hidden columns.\r\n            // In the configuration below, moving C to the right of E will lead to:\r\n            //    ... C [D] E  --->  ... [D] E  C   (Column name/index)\r\n            //    ... 2  3  4        ...  2  3  4   (Display order)\r\n            const int reorder_dir = table->ReorderColumnDir;\r\n            IM_ASSERT(reorder_dir == -1 || reorder_dir == +1);\r\n            IM_ASSERT(table->Flags & ImGuiTableFlags_Reorderable);\r\n            ImGuiTableColumn* src_column = &table->Columns[table->ReorderColumn];\r\n            ImGuiTableColumn* dst_column = &table->Columns[(reorder_dir == -1) ? src_column->PrevEnabledColumn : src_column->NextEnabledColumn];\r\n            IM_UNUSED(dst_column);\r\n            const int src_order = src_column->DisplayOrder;\r\n            const int dst_order = dst_column->DisplayOrder;\r\n            src_column->DisplayOrder = (ImGuiTableColumnIdx)dst_order;\r\n            for (int order_n = src_order + reorder_dir; order_n != dst_order + reorder_dir; order_n += reorder_dir)\r\n                table->Columns[table->DisplayOrderToIndex[order_n]].DisplayOrder -= (ImGuiTableColumnIdx)reorder_dir;\r\n            IM_ASSERT(dst_column->DisplayOrder == dst_order - reorder_dir);\r\n\r\n            // Display order is stored in both columns->IndexDisplayOrder and table->DisplayOrder[],\r\n            // rebuild the later from the former.\r\n            for (int column_n = 0; column_n < table->ColumnsCount; column_n++)\r\n                table->DisplayOrderToIndex[table->Columns[column_n].DisplayOrder] = (ImGuiTableColumnIdx)column_n;\r\n            table->ReorderColumnDir = 0;\r\n            table->IsSettingsDirty = true;\r\n        }\r\n    }\r\n\r\n    // Handle display order reset request\r\n    if (table->IsResetDisplayOrderRequest)\r\n    {\r\n        for (int n = 0; n < table->ColumnsCount; n++)\r\n            table->DisplayOrderToIndex[n] = table->Columns[n].DisplayOrder = (ImGuiTableColumnIdx)n;\r\n        table->IsResetDisplayOrderRequest = false;\r\n        table->IsSettingsDirty = true;\r\n    }\r\n}\r\n\r\n// Adjust flags: default width mode + stretch columns are not allowed when auto extending\r\nstatic void TableSetupColumnFlags(ImGuiTable* table, ImGuiTableColumn* column, ImGuiTableColumnFlags flags_in)\r\n{\r\n    ImGuiTableColumnFlags flags = flags_in;\r\n\r\n    // Sizing Policy\r\n    if ((flags & ImGuiTableColumnFlags_WidthMask_) == 0)\r\n    {\r\n        const ImGuiTableFlags table_sizing_policy = (table->Flags & ImGuiTableFlags_SizingMask_);\r\n        if (table_sizing_policy == ImGuiTableFlags_SizingFixedFit || table_sizing_policy == ImGuiTableFlags_SizingFixedSame)\r\n            flags |= ImGuiTableColumnFlags_WidthFixed;\r\n        else\r\n            flags |= ImGuiTableColumnFlags_WidthStretch;\r\n    }\r\n    else\r\n    {\r\n        IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiTableColumnFlags_WidthMask_)); // Check that only 1 of each set is used.\r\n    }\r\n\r\n    // Resize\r\n    if ((table->Flags & ImGuiTableFlags_Resizable) == 0)\r\n        flags |= ImGuiTableColumnFlags_NoResize;\r\n\r\n    // Sorting\r\n    if ((flags & ImGuiTableColumnFlags_NoSortAscending) && (flags & ImGuiTableColumnFlags_NoSortDescending))\r\n        flags |= ImGuiTableColumnFlags_NoSort;\r\n\r\n    // Indentation\r\n    if ((flags & ImGuiTableColumnFlags_IndentMask_) == 0)\r\n        flags |= (table->Columns.index_from_ptr(column) == 0) ? ImGuiTableColumnFlags_IndentEnable : ImGuiTableColumnFlags_IndentDisable;\r\n\r\n    // Alignment\r\n    //if ((flags & ImGuiTableColumnFlags_AlignMask_) == 0)\r\n    //    flags |= ImGuiTableColumnFlags_AlignCenter;\r\n    //IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiTableColumnFlags_AlignMask_)); // Check that only 1 of each set is used.\r\n\r\n    // Preserve status flags\r\n    column->Flags = flags | (column->Flags & ImGuiTableColumnFlags_StatusMask_);\r\n\r\n    // Build an ordered list of available sort directions\r\n    column->SortDirectionsAvailCount = column->SortDirectionsAvailMask = column->SortDirectionsAvailList = 0;\r\n    if (table->Flags & ImGuiTableFlags_Sortable)\r\n    {\r\n        int count = 0, mask = 0, list = 0;\r\n        if ((flags & ImGuiTableColumnFlags_PreferSortAscending)  != 0 && (flags & ImGuiTableColumnFlags_NoSortAscending)  == 0) { mask |= 1 << ImGuiSortDirection_Ascending;  list |= ImGuiSortDirection_Ascending  << (count << 1); count++; }\r\n        if ((flags & ImGuiTableColumnFlags_PreferSortDescending) != 0 && (flags & ImGuiTableColumnFlags_NoSortDescending) == 0) { mask |= 1 << ImGuiSortDirection_Descending; list |= ImGuiSortDirection_Descending << (count << 1); count++; }\r\n        if ((flags & ImGuiTableColumnFlags_PreferSortAscending)  == 0 && (flags & ImGuiTableColumnFlags_NoSortAscending)  == 0) { mask |= 1 << ImGuiSortDirection_Ascending;  list |= ImGuiSortDirection_Ascending  << (count << 1); count++; }\r\n        if ((flags & ImGuiTableColumnFlags_PreferSortDescending) == 0 && (flags & ImGuiTableColumnFlags_NoSortDescending) == 0) { mask |= 1 << ImGuiSortDirection_Descending; list |= ImGuiSortDirection_Descending << (count << 1); count++; }\r\n        if ((table->Flags & ImGuiTableFlags_SortTristate) || count == 0) { mask |= 1 << ImGuiSortDirection_None; count++; }\r\n        column->SortDirectionsAvailList = (ImU8)list;\r\n        column->SortDirectionsAvailMask = (ImU8)mask;\r\n        column->SortDirectionsAvailCount = (ImU8)count;\r\n        ImGui::TableFixColumnSortDirection(table, column);\r\n    }\r\n}\r\n\r\n// Layout columns for the frame. This is in essence the followup to BeginTable().\r\n// Runs on the first call to TableNextRow(), to give a chance for TableSetupColumn() to be called first.\r\n// FIXME-TABLE: Our width (and therefore our WorkRect) will be minimal in the first frame for _WidthAuto columns.\r\n// Increase feedback side-effect with widgets relying on WorkRect.Max.x... Maybe provide a default distribution for _WidthAuto columns?\r\nvoid ImGui::TableUpdateLayout(ImGuiTable* table)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(table->IsLayoutLocked == false);\r\n\r\n    const ImGuiTableFlags table_sizing_policy = (table->Flags & ImGuiTableFlags_SizingMask_);\r\n    table->IsDefaultDisplayOrder = true;\r\n    table->ColumnsEnabledCount = 0;\r\n    table->EnabledMaskByIndex = 0x00;\r\n    table->EnabledMaskByDisplayOrder = 0x00;\r\n    table->LeftMostEnabledColumn = -1;\r\n    table->MinColumnWidth = ImMax(1.0f, g.Style.FramePadding.x * 1.0f); // g.Style.ColumnsMinSpacing; // FIXME-TABLE\r\n\r\n    // [Part 1] Apply/lock Enabled and Order states. Calculate auto/ideal width for columns. Count fixed/stretch columns.\r\n    // Process columns in their visible orders as we are building the Prev/Next indices.\r\n    int count_fixed = 0;                // Number of columns that have fixed sizing policies\r\n    int count_stretch = 0;              // Number of columns that have stretch sizing policies\r\n    int prev_visible_column_idx = -1;\r\n    bool has_auto_fit_request = false;\r\n    bool has_resizable = false;\r\n    float stretch_sum_width_auto = 0.0f;\r\n    float fixed_max_width_auto = 0.0f;\r\n    for (int order_n = 0; order_n < table->ColumnsCount; order_n++)\r\n    {\r\n        const int column_n = table->DisplayOrderToIndex[order_n];\r\n        if (column_n != order_n)\r\n            table->IsDefaultDisplayOrder = false;\r\n        ImGuiTableColumn* column = &table->Columns[column_n];\r\n\r\n        // Clear column setup if not submitted by user. Currently we make it mandatory to call TableSetupColumn() every frame.\r\n        // It would easily work without but we're not ready to guarantee it since e.g. names need resubmission anyway.\r\n        // We take a slight shortcut but in theory we could be calling TableSetupColumn() here with dummy values, it should yield the same effect.\r\n        if (table->DeclColumnsCount <= column_n)\r\n        {\r\n            TableSetupColumnFlags(table, column, ImGuiTableColumnFlags_None);\r\n            column->NameOffset = -1;\r\n            column->UserID = 0;\r\n            column->InitStretchWeightOrWidth = -1.0f;\r\n        }\r\n\r\n        // Update Enabled state, mark settings and sort specs dirty\r\n        if (!(table->Flags & ImGuiTableFlags_Hideable) || (column->Flags & ImGuiTableColumnFlags_NoHide))\r\n            column->IsUserEnabledNextFrame = true;\r\n        if (column->IsUserEnabled != column->IsUserEnabledNextFrame)\r\n        {\r\n            column->IsUserEnabled = column->IsUserEnabledNextFrame;\r\n            table->IsSettingsDirty = true;\r\n        }\r\n        column->IsEnabled = column->IsUserEnabled && (column->Flags & ImGuiTableColumnFlags_Disabled) == 0;\r\n\r\n        if (column->SortOrder != -1 && !column->IsEnabled)\r\n            table->IsSortSpecsDirty = true;\r\n        if (column->SortOrder > 0 && !(table->Flags & ImGuiTableFlags_SortMulti))\r\n            table->IsSortSpecsDirty = true;\r\n\r\n        // Auto-fit unsized columns\r\n        const bool start_auto_fit = (column->Flags & ImGuiTableColumnFlags_WidthFixed) ? (column->WidthRequest < 0.0f) : (column->StretchWeight < 0.0f);\r\n        if (start_auto_fit)\r\n            column->AutoFitQueue = column->CannotSkipItemsQueue = (1 << 3) - 1; // Fit for three frames\r\n\r\n        if (!column->IsEnabled)\r\n        {\r\n            column->IndexWithinEnabledSet = -1;\r\n            continue;\r\n        }\r\n\r\n        // Mark as enabled and link to previous/next enabled column\r\n        column->PrevEnabledColumn = (ImGuiTableColumnIdx)prev_visible_column_idx;\r\n        column->NextEnabledColumn = -1;\r\n        if (prev_visible_column_idx != -1)\r\n            table->Columns[prev_visible_column_idx].NextEnabledColumn = (ImGuiTableColumnIdx)column_n;\r\n        else\r\n            table->LeftMostEnabledColumn = (ImGuiTableColumnIdx)column_n;\r\n        column->IndexWithinEnabledSet = table->ColumnsEnabledCount++;\r\n        table->EnabledMaskByIndex |= (ImU64)1 << column_n;\r\n        table->EnabledMaskByDisplayOrder |= (ImU64)1 << column->DisplayOrder;\r\n        prev_visible_column_idx = column_n;\r\n        IM_ASSERT(column->IndexWithinEnabledSet <= column->DisplayOrder);\r\n\r\n        // Calculate ideal/auto column width (that's the width required for all contents to be visible without clipping)\r\n        // Combine width from regular rows + width from headers unless requested not to.\r\n        if (!column->IsPreserveWidthAuto)\r\n            column->WidthAuto = TableGetColumnWidthAuto(table, column);\r\n\r\n        // Non-resizable columns keep their requested width (apply user value regardless of IsPreserveWidthAuto)\r\n        const bool column_is_resizable = (column->Flags & ImGuiTableColumnFlags_NoResize) == 0;\r\n        if (column_is_resizable)\r\n            has_resizable = true;\r\n        if ((column->Flags & ImGuiTableColumnFlags_WidthFixed) && column->InitStretchWeightOrWidth > 0.0f && !column_is_resizable)\r\n            column->WidthAuto = column->InitStretchWeightOrWidth;\r\n\r\n        if (column->AutoFitQueue != 0x00)\r\n            has_auto_fit_request = true;\r\n        if (column->Flags & ImGuiTableColumnFlags_WidthStretch)\r\n        {\r\n            stretch_sum_width_auto += column->WidthAuto;\r\n            count_stretch++;\r\n        }\r\n        else\r\n        {\r\n            fixed_max_width_auto = ImMax(fixed_max_width_auto, column->WidthAuto);\r\n            count_fixed++;\r\n        }\r\n    }\r\n    if ((table->Flags & ImGuiTableFlags_Sortable) && table->SortSpecsCount == 0 && !(table->Flags & ImGuiTableFlags_SortTristate))\r\n        table->IsSortSpecsDirty = true;\r\n    table->RightMostEnabledColumn = (ImGuiTableColumnIdx)prev_visible_column_idx;\r\n    IM_ASSERT(table->LeftMostEnabledColumn >= 0 && table->RightMostEnabledColumn >= 0);\r\n\r\n    // [Part 2] Disable child window clipping while fitting columns. This is not strictly necessary but makes it possible\r\n    // to avoid the column fitting having to wait until the first visible frame of the child container (may or not be a good thing).\r\n    // FIXME-TABLE: for always auto-resizing columns may not want to do that all the time.\r\n    if (has_auto_fit_request && table->OuterWindow != table->InnerWindow)\r\n        table->InnerWindow->SkipItems = false;\r\n    if (has_auto_fit_request)\r\n        table->IsSettingsDirty = true;\r\n\r\n    // [Part 3] Fix column flags and record a few extra information.\r\n    float sum_width_requests = 0.0f;        // Sum of all width for fixed and auto-resize columns, excluding width contributed by Stretch columns but including spacing/padding.\r\n    float stretch_sum_weights = 0.0f;       // Sum of all weights for stretch columns.\r\n    table->LeftMostStretchedColumn = table->RightMostStretchedColumn = -1;\r\n    for (int column_n = 0; column_n < table->ColumnsCount; column_n++)\r\n    {\r\n        if (!(table->EnabledMaskByIndex & ((ImU64)1 << column_n)))\r\n            continue;\r\n        ImGuiTableColumn* column = &table->Columns[column_n];\r\n\r\n        const bool column_is_resizable = (column->Flags & ImGuiTableColumnFlags_NoResize) == 0;\r\n        if (column->Flags & ImGuiTableColumnFlags_WidthFixed)\r\n        {\r\n            // Apply same widths policy\r\n            float width_auto = column->WidthAuto;\r\n            if (table_sizing_policy == ImGuiTableFlags_SizingFixedSame && (column->AutoFitQueue != 0x00 || !column_is_resizable))\r\n                width_auto = fixed_max_width_auto;\r\n\r\n            // Apply automatic width\r\n            // Latch initial size for fixed columns and update it constantly for auto-resizing column (unless clipped!)\r\n            if (column->AutoFitQueue != 0x00)\r\n                column->WidthRequest = width_auto;\r\n            else if ((column->Flags & ImGuiTableColumnFlags_WidthFixed) && !column_is_resizable && (table->RequestOutputMaskByIndex & ((ImU64)1 << column_n)))\r\n                column->WidthRequest = width_auto;\r\n\r\n            // FIXME-TABLE: Increase minimum size during init frame to avoid biasing auto-fitting widgets\r\n            // (e.g. TextWrapped) too much. Otherwise what tends to happen is that TextWrapped would output a very\r\n            // large height (= first frame scrollbar display very off + clipper would skip lots of items).\r\n            // This is merely making the side-effect less extreme, but doesn't properly fixes it.\r\n            // FIXME: Move this to ->WidthGiven to avoid temporary lossyless?\r\n            // FIXME: This break IsPreserveWidthAuto from not flickering if the stored WidthAuto was smaller.\r\n            if (column->AutoFitQueue > 0x01 && table->IsInitializing && !column->IsPreserveWidthAuto)\r\n                column->WidthRequest = ImMax(column->WidthRequest, table->MinColumnWidth * 4.0f); // FIXME-TABLE: Another constant/scale?\r\n            sum_width_requests += column->WidthRequest;\r\n        }\r\n        else\r\n        {\r\n            // Initialize stretch weight\r\n            if (column->AutoFitQueue != 0x00 || column->StretchWeight < 0.0f || !column_is_resizable)\r\n            {\r\n                if (column->InitStretchWeightOrWidth > 0.0f)\r\n                    column->StretchWeight = column->InitStretchWeightOrWidth;\r\n                else if (table_sizing_policy == ImGuiTableFlags_SizingStretchProp)\r\n                    column->StretchWeight = (column->WidthAuto / stretch_sum_width_auto) * count_stretch;\r\n                else\r\n                    column->StretchWeight = 1.0f;\r\n            }\r\n\r\n            stretch_sum_weights += column->StretchWeight;\r\n            if (table->LeftMostStretchedColumn == -1 || table->Columns[table->LeftMostStretchedColumn].DisplayOrder > column->DisplayOrder)\r\n                table->LeftMostStretchedColumn = (ImGuiTableColumnIdx)column_n;\r\n            if (table->RightMostStretchedColumn == -1 || table->Columns[table->RightMostStretchedColumn].DisplayOrder < column->DisplayOrder)\r\n                table->RightMostStretchedColumn = (ImGuiTableColumnIdx)column_n;\r\n        }\r\n        column->IsPreserveWidthAuto = false;\r\n        sum_width_requests += table->CellPaddingX * 2.0f;\r\n    }\r\n    table->ColumnsEnabledFixedCount = (ImGuiTableColumnIdx)count_fixed;\r\n\r\n    // [Part 4] Apply final widths based on requested widths\r\n    const ImRect work_rect = table->WorkRect;\r\n    const float width_spacings = (table->OuterPaddingX * 2.0f) + (table->CellSpacingX1 + table->CellSpacingX2) * (table->ColumnsEnabledCount - 1);\r\n    const float width_avail = ((table->Flags & ImGuiTableFlags_ScrollX) && table->InnerWidth == 0.0f) ? table->InnerClipRect.GetWidth() : work_rect.GetWidth();\r\n    const float width_avail_for_stretched_columns = width_avail - width_spacings - sum_width_requests;\r\n    float width_remaining_for_stretched_columns = width_avail_for_stretched_columns;\r\n    table->ColumnsGivenWidth = width_spacings + (table->CellPaddingX * 2.0f) * table->ColumnsEnabledCount;\r\n    for (int column_n = 0; column_n < table->ColumnsCount; column_n++)\r\n    {\r\n        if (!(table->EnabledMaskByIndex & ((ImU64)1 << column_n)))\r\n            continue;\r\n        ImGuiTableColumn* column = &table->Columns[column_n];\r\n\r\n        // Allocate width for stretched/weighted columns (StretchWeight gets converted into WidthRequest)\r\n        if (column->Flags & ImGuiTableColumnFlags_WidthStretch)\r\n        {\r\n            float weight_ratio = column->StretchWeight / stretch_sum_weights;\r\n            column->WidthRequest = IM_FLOOR(ImMax(width_avail_for_stretched_columns * weight_ratio, table->MinColumnWidth) + 0.01f);\r\n            width_remaining_for_stretched_columns -= column->WidthRequest;\r\n        }\r\n\r\n        // [Resize Rule 1] The right-most Visible column is not resizable if there is at least one Stretch column\r\n        // See additional comments in TableSetColumnWidth().\r\n        if (column->NextEnabledColumn == -1 && table->LeftMostStretchedColumn != -1)\r\n            column->Flags |= ImGuiTableColumnFlags_NoDirectResize_;\r\n\r\n        // Assign final width, record width in case we will need to shrink\r\n        column->WidthGiven = ImFloor(ImMax(column->WidthRequest, table->MinColumnWidth));\r\n        table->ColumnsGivenWidth += column->WidthGiven;\r\n    }\r\n\r\n    // [Part 5] Redistribute stretch remainder width due to rounding (remainder width is < 1.0f * number of Stretch column).\r\n    // Using right-to-left distribution (more likely to match resizing cursor).\r\n    if (width_remaining_for_stretched_columns >= 1.0f && !(table->Flags & ImGuiTableFlags_PreciseWidths))\r\n        for (int order_n = table->ColumnsCount - 1; stretch_sum_weights > 0.0f && width_remaining_for_stretched_columns >= 1.0f && order_n >= 0; order_n--)\r\n        {\r\n            if (!(table->EnabledMaskByDisplayOrder & ((ImU64)1 << order_n)))\r\n                continue;\r\n            ImGuiTableColumn* column = &table->Columns[table->DisplayOrderToIndex[order_n]];\r\n            if (!(column->Flags & ImGuiTableColumnFlags_WidthStretch))\r\n                continue;\r\n            column->WidthRequest += 1.0f;\r\n            column->WidthGiven += 1.0f;\r\n            width_remaining_for_stretched_columns -= 1.0f;\r\n        }\r\n\r\n    table->HoveredColumnBody = -1;\r\n    table->HoveredColumnBorder = -1;\r\n    const ImRect mouse_hit_rect(table->OuterRect.Min.x, table->OuterRect.Min.y, table->OuterRect.Max.x, ImMax(table->OuterRect.Max.y, table->OuterRect.Min.y + table->LastOuterHeight));\r\n    const bool is_hovering_table = ItemHoverable(mouse_hit_rect, 0);\r\n\r\n    // [Part 6] Setup final position, offset, skip/clip states and clipping rectangles, detect hovered column\r\n    // Process columns in their visible orders as we are comparing the visible order and adjusting host_clip_rect while looping.\r\n    int visible_n = 0;\r\n    bool offset_x_frozen = (table->FreezeColumnsCount > 0);\r\n    float offset_x = ((table->FreezeColumnsCount > 0) ? table->OuterRect.Min.x : work_rect.Min.x) + table->OuterPaddingX - table->CellSpacingX1;\r\n    ImRect host_clip_rect = table->InnerClipRect;\r\n    //host_clip_rect.Max.x += table->CellPaddingX + table->CellSpacingX2;\r\n    table->VisibleMaskByIndex = 0x00;\r\n    table->RequestOutputMaskByIndex = 0x00;\r\n    for (int order_n = 0; order_n < table->ColumnsCount; order_n++)\r\n    {\r\n        const int column_n = table->DisplayOrderToIndex[order_n];\r\n        ImGuiTableColumn* column = &table->Columns[column_n];\r\n\r\n        column->NavLayerCurrent = (ImS8)((table->FreezeRowsCount > 0 || column_n < table->FreezeColumnsCount) ? ImGuiNavLayer_Menu : ImGuiNavLayer_Main);\r\n\r\n        if (offset_x_frozen && table->FreezeColumnsCount == visible_n)\r\n        {\r\n            offset_x += work_rect.Min.x - table->OuterRect.Min.x;\r\n            offset_x_frozen = false;\r\n        }\r\n\r\n        // Clear status flags\r\n        column->Flags &= ~ImGuiTableColumnFlags_StatusMask_;\r\n\r\n        if ((table->EnabledMaskByDisplayOrder & ((ImU64)1 << order_n)) == 0)\r\n        {\r\n            // Hidden column: clear a few fields and we are done with it for the remainder of the function.\r\n            // We set a zero-width clip rect but set Min.y/Max.y properly to not interfere with the clipper.\r\n            column->MinX = column->MaxX = column->WorkMinX = column->ClipRect.Min.x = column->ClipRect.Max.x = offset_x;\r\n            column->WidthGiven = 0.0f;\r\n            column->ClipRect.Min.y = work_rect.Min.y;\r\n            column->ClipRect.Max.y = FLT_MAX;\r\n            column->ClipRect.ClipWithFull(host_clip_rect);\r\n            column->IsVisibleX = column->IsVisibleY = column->IsRequestOutput = false;\r\n            column->IsSkipItems = true;\r\n            column->ItemWidth = 1.0f;\r\n            continue;\r\n        }\r\n\r\n        // Detect hovered column\r\n        if (is_hovering_table && g.IO.MousePos.x >= column->ClipRect.Min.x && g.IO.MousePos.x < column->ClipRect.Max.x)\r\n            table->HoveredColumnBody = (ImGuiTableColumnIdx)column_n;\r\n\r\n        // Lock start position\r\n        column->MinX = offset_x;\r\n\r\n        // Lock width based on start position and minimum/maximum width for this position\r\n        float max_width = TableGetMaxColumnWidth(table, column_n);\r\n        column->WidthGiven = ImMin(column->WidthGiven, max_width);\r\n        column->WidthGiven = ImMax(column->WidthGiven, ImMin(column->WidthRequest, table->MinColumnWidth));\r\n        column->MaxX = offset_x + column->WidthGiven + table->CellSpacingX1 + table->CellSpacingX2 + table->CellPaddingX * 2.0f;\r\n\r\n        // Lock other positions\r\n        // - ClipRect.Min.x: Because merging draw commands doesn't compare min boundaries, we make ClipRect.Min.x match left bounds to be consistent regardless of merging.\r\n        // - ClipRect.Max.x: using WorkMaxX instead of MaxX (aka including padding) makes things more consistent when resizing down, tho slightly detrimental to visibility in very-small column.\r\n        // - ClipRect.Max.x: using MaxX makes it easier for header to receive hover highlight with no discontinuity and display sorting arrow.\r\n        // - FIXME-TABLE: We want equal width columns to have equal (ClipRect.Max.x - WorkMinX) width, which means ClipRect.max.x cannot stray off host_clip_rect.Max.x else right-most column may appear shorter.\r\n        column->WorkMinX = column->MinX + table->CellPaddingX + table->CellSpacingX1;\r\n        column->WorkMaxX = column->MaxX - table->CellPaddingX - table->CellSpacingX2; // Expected max\r\n        column->ItemWidth = ImFloor(column->WidthGiven * 0.65f);\r\n        column->ClipRect.Min.x = column->MinX;\r\n        column->ClipRect.Min.y = work_rect.Min.y;\r\n        column->ClipRect.Max.x = column->MaxX; //column->WorkMaxX;\r\n        column->ClipRect.Max.y = FLT_MAX;\r\n        column->ClipRect.ClipWithFull(host_clip_rect);\r\n\r\n        // Mark column as Clipped (not in sight)\r\n        // Note that scrolling tables (where inner_window != outer_window) handle Y clipped earlier in BeginTable() so IsVisibleY really only applies to non-scrolling tables.\r\n        // FIXME-TABLE: Because InnerClipRect.Max.y is conservatively ==outer_window->ClipRect.Max.y, we never can mark columns _Above_ the scroll line as not IsVisibleY.\r\n        // Taking advantage of LastOuterHeight would yield good results there...\r\n        // FIXME-TABLE: Y clipping is disabled because it effectively means not submitting will reduce contents width which is fed to outer_window->DC.CursorMaxPos.x,\r\n        // and this may be used (e.g. typically by outer_window using AlwaysAutoResize or outer_window's horizontal scrollbar, but could be something else).\r\n        // Possible solution to preserve last known content width for clipped column. Test 'table_reported_size' fails when enabling Y clipping and window is resized small.\r\n        column->IsVisibleX = (column->ClipRect.Max.x > column->ClipRect.Min.x);\r\n        column->IsVisibleY = true; // (column->ClipRect.Max.y > column->ClipRect.Min.y);\r\n        const bool is_visible = column->IsVisibleX; //&& column->IsVisibleY;\r\n        if (is_visible)\r\n            table->VisibleMaskByIndex |= ((ImU64)1 << column_n);\r\n\r\n        // Mark column as requesting output from user. Note that fixed + non-resizable sets are auto-fitting at all times and therefore always request output.\r\n        column->IsRequestOutput = is_visible || column->AutoFitQueue != 0 || column->CannotSkipItemsQueue != 0;\r\n        if (column->IsRequestOutput)\r\n            table->RequestOutputMaskByIndex |= ((ImU64)1 << column_n);\r\n\r\n        // Mark column as SkipItems (ignoring all items/layout)\r\n        column->IsSkipItems = !column->IsEnabled || table->HostSkipItems;\r\n        if (column->IsSkipItems)\r\n            IM_ASSERT(!is_visible);\r\n\r\n        // Update status flags\r\n        column->Flags |= ImGuiTableColumnFlags_IsEnabled;\r\n        if (is_visible)\r\n            column->Flags |= ImGuiTableColumnFlags_IsVisible;\r\n        if (column->SortOrder != -1)\r\n            column->Flags |= ImGuiTableColumnFlags_IsSorted;\r\n        if (table->HoveredColumnBody == column_n)\r\n            column->Flags |= ImGuiTableColumnFlags_IsHovered;\r\n\r\n        // Alignment\r\n        // FIXME-TABLE: This align based on the whole column width, not per-cell, and therefore isn't useful in\r\n        // many cases (to be able to honor this we might be able to store a log of cells width, per row, for\r\n        // visible rows, but nav/programmatic scroll would have visible artifacts.)\r\n        //if (column->Flags & ImGuiTableColumnFlags_AlignRight)\r\n        //    column->WorkMinX = ImMax(column->WorkMinX, column->MaxX - column->ContentWidthRowsUnfrozen);\r\n        //else if (column->Flags & ImGuiTableColumnFlags_AlignCenter)\r\n        //    column->WorkMinX = ImLerp(column->WorkMinX, ImMax(column->StartX, column->MaxX - column->ContentWidthRowsUnfrozen), 0.5f);\r\n\r\n        // Reset content width variables\r\n        column->ContentMaxXFrozen = column->ContentMaxXUnfrozen = column->WorkMinX;\r\n        column->ContentMaxXHeadersUsed = column->ContentMaxXHeadersIdeal = column->WorkMinX;\r\n\r\n        // Don't decrement auto-fit counters until container window got a chance to submit its items\r\n        if (table->HostSkipItems == false)\r\n        {\r\n            column->AutoFitQueue >>= 1;\r\n            column->CannotSkipItemsQueue >>= 1;\r\n        }\r\n\r\n        if (visible_n < table->FreezeColumnsCount)\r\n            host_clip_rect.Min.x = ImClamp(column->MaxX + TABLE_BORDER_SIZE, host_clip_rect.Min.x, host_clip_rect.Max.x);\r\n\r\n        offset_x += column->WidthGiven + table->CellSpacingX1 + table->CellSpacingX2 + table->CellPaddingX * 2.0f;\r\n        visible_n++;\r\n    }\r\n\r\n    // [Part 7] Detect/store when we are hovering the unused space after the right-most column (so e.g. context menus can react on it)\r\n    // Clear Resizable flag if none of our column are actually resizable (either via an explicit _NoResize flag, either\r\n    // because of using _WidthAuto/_WidthStretch). This will hide the resizing option from the context menu.\r\n    const float unused_x1 = ImMax(table->WorkRect.Min.x, table->Columns[table->RightMostEnabledColumn].ClipRect.Max.x);\r\n    if (is_hovering_table && table->HoveredColumnBody == -1)\r\n    {\r\n        if (g.IO.MousePos.x >= unused_x1)\r\n            table->HoveredColumnBody = (ImGuiTableColumnIdx)table->ColumnsCount;\r\n    }\r\n    if (has_resizable == false && (table->Flags & ImGuiTableFlags_Resizable))\r\n        table->Flags &= ~ImGuiTableFlags_Resizable;\r\n\r\n    // [Part 8] Lock actual OuterRect/WorkRect right-most position.\r\n    // This is done late to handle the case of fixed-columns tables not claiming more widths that they need.\r\n    // Because of this we are careful with uses of WorkRect and InnerClipRect before this point.\r\n    if (table->RightMostStretchedColumn != -1)\r\n        table->Flags &= ~ImGuiTableFlags_NoHostExtendX;\r\n    if (table->Flags & ImGuiTableFlags_NoHostExtendX)\r\n    {\r\n        table->OuterRect.Max.x = table->WorkRect.Max.x = unused_x1;\r\n        table->InnerClipRect.Max.x = ImMin(table->InnerClipRect.Max.x, unused_x1);\r\n    }\r\n    table->InnerWindow->ParentWorkRect = table->WorkRect;\r\n    table->BorderX1 = table->InnerClipRect.Min.x;// +((table->Flags & ImGuiTableFlags_BordersOuter) ? 0.0f : -1.0f);\r\n    table->BorderX2 = table->InnerClipRect.Max.x;// +((table->Flags & ImGuiTableFlags_BordersOuter) ? 0.0f : +1.0f);\r\n\r\n    // [Part 9] Allocate draw channels and setup background cliprect\r\n    TableSetupDrawChannels(table);\r\n\r\n    // [Part 10] Hit testing on borders\r\n    if (table->Flags & ImGuiTableFlags_Resizable)\r\n        TableUpdateBorders(table);\r\n    table->LastFirstRowHeight = 0.0f;\r\n    table->IsLayoutLocked = true;\r\n    table->IsUsingHeaders = false;\r\n\r\n    // [Part 11] Context menu\r\n    if (table->IsContextPopupOpen && table->InstanceCurrent == table->InstanceInteracted)\r\n    {\r\n        const ImGuiID context_menu_id = ImHashStr(\"##ContextMenu\", 0, table->ID);\r\n        if (BeginPopupEx(context_menu_id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings))\r\n        {\r\n            TableDrawContextMenu(table);\r\n            EndPopup();\r\n        }\r\n        else\r\n        {\r\n            table->IsContextPopupOpen = false;\r\n        }\r\n    }\r\n\r\n    // [Part 13] Sanitize and build sort specs before we have a change to use them for display.\r\n    // This path will only be exercised when sort specs are modified before header rows (e.g. init or visibility change)\r\n    if (table->IsSortSpecsDirty && (table->Flags & ImGuiTableFlags_Sortable))\r\n        TableSortSpecsBuild(table);\r\n\r\n    // Initial state\r\n    ImGuiWindow* inner_window = table->InnerWindow;\r\n    if (table->Flags & ImGuiTableFlags_NoClip)\r\n        table->DrawSplitter->SetCurrentChannel(inner_window->DrawList, TABLE_DRAW_CHANNEL_NOCLIP);\r\n    else\r\n        inner_window->DrawList->PushClipRect(inner_window->ClipRect.Min, inner_window->ClipRect.Max, false);\r\n}\r\n\r\n// Process hit-testing on resizing borders. Actual size change will be applied in EndTable()\r\n// - Set table->HoveredColumnBorder with a short delay/timer to reduce feedback noise\r\n// - Submit ahead of table contents and header, use ImGuiButtonFlags_AllowItemOverlap to prioritize widgets\r\n//   overlapping the same area.\r\nvoid ImGui::TableUpdateBorders(ImGuiTable* table)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(table->Flags & ImGuiTableFlags_Resizable);\r\n\r\n    // At this point OuterRect height may be zero or under actual final height, so we rely on temporal coherency and\r\n    // use the final height from last frame. Because this is only affecting _interaction_ with columns, it is not\r\n    // really problematic (whereas the actual visual will be displayed in EndTable() and using the current frame height).\r\n    // Actual columns highlight/render will be performed in EndTable() and not be affected.\r\n    const float hit_half_width = TABLE_RESIZE_SEPARATOR_HALF_THICKNESS;\r\n    const float hit_y1 = table->OuterRect.Min.y;\r\n    const float hit_y2_body = ImMax(table->OuterRect.Max.y, hit_y1 + table->LastOuterHeight);\r\n    const float hit_y2_head = hit_y1 + table->LastFirstRowHeight;\r\n\r\n    for (int order_n = 0; order_n < table->ColumnsCount; order_n++)\r\n    {\r\n        if (!(table->EnabledMaskByDisplayOrder & ((ImU64)1 << order_n)))\r\n            continue;\r\n\r\n        const int column_n = table->DisplayOrderToIndex[order_n];\r\n        ImGuiTableColumn* column = &table->Columns[column_n];\r\n        if (column->Flags & (ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_NoDirectResize_))\r\n            continue;\r\n\r\n        // ImGuiTableFlags_NoBordersInBodyUntilResize will be honored in TableDrawBorders()\r\n        const float border_y2_hit = (table->Flags & ImGuiTableFlags_NoBordersInBody) ? hit_y2_head : hit_y2_body;\r\n        if ((table->Flags & ImGuiTableFlags_NoBordersInBody) && table->IsUsingHeaders == false)\r\n            continue;\r\n\r\n        if (!column->IsVisibleX && table->LastResizedColumn != column_n)\r\n            continue;\r\n\r\n        ImGuiID column_id = TableGetColumnResizeID(table, column_n, table->InstanceCurrent);\r\n        ImRect hit_rect(column->MaxX - hit_half_width, hit_y1, column->MaxX + hit_half_width, border_y2_hit);\r\n        //GetForegroundDrawList()->AddRect(hit_rect.Min, hit_rect.Max, IM_COL32(255, 0, 0, 100));\r\n        KeepAliveID(column_id);\r\n\r\n        bool hovered = false, held = false;\r\n        bool pressed = ButtonBehavior(hit_rect, column_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_AllowItemOverlap | ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnDoubleClick | ImGuiButtonFlags_NoNavFocus);\r\n        if (pressed && IsMouseDoubleClicked(0))\r\n        {\r\n            TableSetColumnWidthAutoSingle(table, column_n);\r\n            ClearActiveID();\r\n            held = hovered = false;\r\n        }\r\n        if (held)\r\n        {\r\n            if (table->LastResizedColumn == -1)\r\n                table->ResizeLockMinContentsX2 = table->RightMostEnabledColumn != -1 ? table->Columns[table->RightMostEnabledColumn].MaxX : -FLT_MAX;\r\n            table->ResizedColumn = (ImGuiTableColumnIdx)column_n;\r\n            table->InstanceInteracted = table->InstanceCurrent;\r\n        }\r\n        if ((hovered && g.HoveredIdTimer > TABLE_RESIZE_SEPARATOR_FEEDBACK_TIMER) || held)\r\n        {\r\n            table->HoveredColumnBorder = (ImGuiTableColumnIdx)column_n;\r\n            SetMouseCursor(ImGuiMouseCursor_ResizeEW);\r\n        }\r\n    }\r\n}\r\n\r\nvoid    ImGui::EndTable()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiTable* table = g.CurrentTable;\r\n    IM_ASSERT(table != NULL && \"Only call EndTable() if BeginTable() returns true!\");\r\n\r\n    // This assert would be very useful to catch a common error... unfortunately it would probably trigger in some\r\n    // cases, and for consistency user may sometimes output empty tables (and still benefit from e.g. outer border)\r\n    //IM_ASSERT(table->IsLayoutLocked && \"Table unused: never called TableNextRow(), is that the intent?\");\r\n\r\n    // If the user never got to call TableNextRow() or TableNextColumn(), we call layout ourselves to ensure all our\r\n    // code paths are consistent (instead of just hoping that TableBegin/TableEnd will work), get borders drawn, etc.\r\n    if (!table->IsLayoutLocked)\r\n        TableUpdateLayout(table);\r\n\r\n    const ImGuiTableFlags flags = table->Flags;\r\n    ImGuiWindow* inner_window = table->InnerWindow;\r\n    ImGuiWindow* outer_window = table->OuterWindow;\r\n    ImGuiTableTempData* temp_data = table->TempData;\r\n    IM_ASSERT(inner_window == g.CurrentWindow);\r\n    IM_ASSERT(outer_window == inner_window || outer_window == inner_window->ParentWindow);\r\n\r\n    if (table->IsInsideRow)\r\n        TableEndRow(table);\r\n\r\n    // Context menu in columns body\r\n    if (flags & ImGuiTableFlags_ContextMenuInBody)\r\n        if (table->HoveredColumnBody != -1 && !IsAnyItemHovered() && IsMouseReleased(ImGuiMouseButton_Right))\r\n            TableOpenContextMenu((int)table->HoveredColumnBody);\r\n\r\n    // Finalize table height\r\n    inner_window->DC.PrevLineSize = temp_data->HostBackupPrevLineSize;\r\n    inner_window->DC.CurrLineSize = temp_data->HostBackupCurrLineSize;\r\n    inner_window->DC.CursorMaxPos = temp_data->HostBackupCursorMaxPos;\r\n    const float inner_content_max_y = table->RowPosY2;\r\n    IM_ASSERT(table->RowPosY2 == inner_window->DC.CursorPos.y);\r\n    if (inner_window != outer_window)\r\n        inner_window->DC.CursorMaxPos.y = inner_content_max_y;\r\n    else if (!(flags & ImGuiTableFlags_NoHostExtendY))\r\n        table->OuterRect.Max.y = table->InnerRect.Max.y = ImMax(table->OuterRect.Max.y, inner_content_max_y); // Patch OuterRect/InnerRect height\r\n    table->WorkRect.Max.y = ImMax(table->WorkRect.Max.y, table->OuterRect.Max.y);\r\n    table->LastOuterHeight = table->OuterRect.GetHeight();\r\n\r\n    // Setup inner scrolling range\r\n    // FIXME: This ideally should be done earlier, in BeginTable() SetNextWindowContentSize call, just like writing to inner_window->DC.CursorMaxPos.y,\r\n    // but since the later is likely to be impossible to do we'd rather update both axises together.\r\n    if (table->Flags & ImGuiTableFlags_ScrollX)\r\n    {\r\n        const float outer_padding_for_border = (table->Flags & ImGuiTableFlags_BordersOuterV) ? TABLE_BORDER_SIZE : 0.0f;\r\n        float max_pos_x = table->InnerWindow->DC.CursorMaxPos.x;\r\n        if (table->RightMostEnabledColumn != -1)\r\n            max_pos_x = ImMax(max_pos_x, table->Columns[table->RightMostEnabledColumn].WorkMaxX + table->CellPaddingX + table->OuterPaddingX - outer_padding_for_border);\r\n        if (table->ResizedColumn != -1)\r\n            max_pos_x = ImMax(max_pos_x, table->ResizeLockMinContentsX2);\r\n        table->InnerWindow->DC.CursorMaxPos.x = max_pos_x;\r\n    }\r\n\r\n    // Pop clipping rect\r\n    if (!(flags & ImGuiTableFlags_NoClip))\r\n        inner_window->DrawList->PopClipRect();\r\n    inner_window->ClipRect = inner_window->DrawList->_ClipRectStack.back();\r\n\r\n    // Draw borders\r\n    if ((flags & ImGuiTableFlags_Borders) != 0)\r\n        TableDrawBorders(table);\r\n\r\n#if 0\r\n    // Strip out dummy channel draw calls\r\n    // We have no way to prevent user submitting direct ImDrawList calls into a hidden column (but ImGui:: calls will be clipped out)\r\n    // Pros: remove draw calls which will have no effect. since they'll have zero-size cliprect they may be early out anyway.\r\n    // Cons: making it harder for users watching metrics/debugger to spot the wasted vertices.\r\n    if (table->DummyDrawChannel != (ImGuiTableColumnIdx)-1)\r\n    {\r\n        ImDrawChannel* dummy_channel = &table->DrawSplitter._Channels[table->DummyDrawChannel];\r\n        dummy_channel->_CmdBuffer.resize(0);\r\n        dummy_channel->_IdxBuffer.resize(0);\r\n    }\r\n#endif\r\n\r\n    // Flatten channels and merge draw calls\r\n    ImDrawListSplitter* splitter = table->DrawSplitter;\r\n    splitter->SetCurrentChannel(inner_window->DrawList, 0);\r\n    if ((table->Flags & ImGuiTableFlags_NoClip) == 0)\r\n        TableMergeDrawChannels(table);\r\n    splitter->Merge(inner_window->DrawList);\r\n\r\n    // Update ColumnsAutoFitWidth to get us ahead for host using our size to auto-resize without waiting for next BeginTable()\r\n    const float width_spacings = (table->OuterPaddingX * 2.0f) + (table->CellSpacingX1 + table->CellSpacingX2) * (table->ColumnsEnabledCount - 1);\r\n    table->ColumnsAutoFitWidth = width_spacings + (table->CellPaddingX * 2.0f) * table->ColumnsEnabledCount;\r\n    for (int column_n = 0; column_n < table->ColumnsCount; column_n++)\r\n        if (table->EnabledMaskByIndex & ((ImU64)1 << column_n))\r\n        {\r\n            ImGuiTableColumn* column = &table->Columns[column_n];\r\n            if ((column->Flags & ImGuiTableColumnFlags_WidthFixed) && !(column->Flags & ImGuiTableColumnFlags_NoResize))\r\n                table->ColumnsAutoFitWidth += column->WidthRequest;\r\n            else\r\n                table->ColumnsAutoFitWidth += TableGetColumnWidthAuto(table, column);\r\n        }\r\n\r\n    // Update scroll\r\n    if ((table->Flags & ImGuiTableFlags_ScrollX) == 0 && inner_window != outer_window)\r\n    {\r\n        inner_window->Scroll.x = 0.0f;\r\n    }\r\n    else if (table->LastResizedColumn != -1 && table->ResizedColumn == -1 && inner_window->ScrollbarX && table->InstanceInteracted == table->InstanceCurrent)\r\n    {\r\n        // When releasing a column being resized, scroll to keep the resulting column in sight\r\n        const float neighbor_width_to_keep_visible = table->MinColumnWidth + table->CellPaddingX * 2.0f;\r\n        ImGuiTableColumn* column = &table->Columns[table->LastResizedColumn];\r\n        if (column->MaxX < table->InnerClipRect.Min.x)\r\n            SetScrollFromPosX(inner_window, column->MaxX - inner_window->Pos.x - neighbor_width_to_keep_visible, 1.0f);\r\n        else if (column->MaxX > table->InnerClipRect.Max.x)\r\n            SetScrollFromPosX(inner_window, column->MaxX - inner_window->Pos.x + neighbor_width_to_keep_visible, 1.0f);\r\n    }\r\n\r\n    // Apply resizing/dragging at the end of the frame\r\n    if (table->ResizedColumn != -1 && table->InstanceCurrent == table->InstanceInteracted)\r\n    {\r\n        ImGuiTableColumn* column = &table->Columns[table->ResizedColumn];\r\n        const float new_x2 = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + TABLE_RESIZE_SEPARATOR_HALF_THICKNESS);\r\n        const float new_width = ImFloor(new_x2 - column->MinX - table->CellSpacingX1 - table->CellPaddingX * 2.0f);\r\n        table->ResizedColumnNextWidth = new_width;\r\n    }\r\n\r\n    // Pop from id stack\r\n    IM_ASSERT_USER_ERROR(inner_window->IDStack.back() == table->ID + table->InstanceCurrent, \"Mismatching PushID/PopID!\");\r\n    IM_ASSERT_USER_ERROR(outer_window->DC.ItemWidthStack.Size >= temp_data->HostBackupItemWidthStackSize, \"Too many PopItemWidth!\");\r\n    PopID();\r\n\r\n    // Restore window data that we modified\r\n    const ImVec2 backup_outer_max_pos = outer_window->DC.CursorMaxPos;\r\n    inner_window->WorkRect = temp_data->HostBackupWorkRect;\r\n    inner_window->ParentWorkRect = temp_data->HostBackupParentWorkRect;\r\n    inner_window->SkipItems = table->HostSkipItems;\r\n    outer_window->DC.CursorPos = table->OuterRect.Min;\r\n    outer_window->DC.ItemWidth = temp_data->HostBackupItemWidth;\r\n    outer_window->DC.ItemWidthStack.Size = temp_data->HostBackupItemWidthStackSize;\r\n    outer_window->DC.ColumnsOffset = temp_data->HostBackupColumnsOffset;\r\n\r\n    // Layout in outer window\r\n    // (FIXME: To allow auto-fit and allow desirable effect of SameLine() we dissociate 'used' vs 'ideal' size by overriding\r\n    // CursorPosPrevLine and CursorMaxPos manually. That should be a more general layout feature, see same problem e.g. #3414)\r\n    if (inner_window != outer_window)\r\n    {\r\n        EndChild();\r\n    }\r\n    else\r\n    {\r\n        ItemSize(table->OuterRect.GetSize());\r\n        ItemAdd(table->OuterRect, 0);\r\n    }\r\n\r\n    // Override declared contents width/height to enable auto-resize while not needlessly adding a scrollbar\r\n    if (table->Flags & ImGuiTableFlags_NoHostExtendX)\r\n    {\r\n        // FIXME-TABLE: Could we remove this section?\r\n        // ColumnsAutoFitWidth may be one frame ahead here since for Fixed+NoResize is calculated from latest contents\r\n        IM_ASSERT((table->Flags & ImGuiTableFlags_ScrollX) == 0);\r\n        outer_window->DC.CursorMaxPos.x = ImMax(backup_outer_max_pos.x, table->OuterRect.Min.x + table->ColumnsAutoFitWidth);\r\n    }\r\n    else if (temp_data->UserOuterSize.x <= 0.0f)\r\n    {\r\n        const float decoration_size = (table->Flags & ImGuiTableFlags_ScrollX) ? inner_window->ScrollbarSizes.x : 0.0f;\r\n        outer_window->DC.IdealMaxPos.x = ImMax(outer_window->DC.IdealMaxPos.x, table->OuterRect.Min.x + table->ColumnsAutoFitWidth + decoration_size - temp_data->UserOuterSize.x);\r\n        outer_window->DC.CursorMaxPos.x = ImMax(backup_outer_max_pos.x, ImMin(table->OuterRect.Max.x, table->OuterRect.Min.x + table->ColumnsAutoFitWidth));\r\n    }\r\n    else\r\n    {\r\n        outer_window->DC.CursorMaxPos.x = ImMax(backup_outer_max_pos.x, table->OuterRect.Max.x);\r\n    }\r\n    if (temp_data->UserOuterSize.y <= 0.0f)\r\n    {\r\n        const float decoration_size = (table->Flags & ImGuiTableFlags_ScrollY) ? inner_window->ScrollbarSizes.y : 0.0f;\r\n        outer_window->DC.IdealMaxPos.y = ImMax(outer_window->DC.IdealMaxPos.y, inner_content_max_y + decoration_size - temp_data->UserOuterSize.y);\r\n        outer_window->DC.CursorMaxPos.y = ImMax(backup_outer_max_pos.y, ImMin(table->OuterRect.Max.y, inner_content_max_y));\r\n    }\r\n    else\r\n    {\r\n        // OuterRect.Max.y may already have been pushed downward from the initial value (unless ImGuiTableFlags_NoHostExtendY is set)\r\n        outer_window->DC.CursorMaxPos.y = ImMax(backup_outer_max_pos.y, table->OuterRect.Max.y);\r\n    }\r\n\r\n    // Save settings\r\n    if (table->IsSettingsDirty)\r\n        TableSaveSettings(table);\r\n    table->IsInitializing = false;\r\n\r\n    // Clear or restore current table, if any\r\n    IM_ASSERT(g.CurrentWindow == outer_window && g.CurrentTable == table);\r\n    IM_ASSERT(g.TablesTempDataStacked > 0);\r\n    temp_data = (--g.TablesTempDataStacked > 0) ? &g.TablesTempData[g.TablesTempDataStacked - 1] : NULL;\r\n    g.CurrentTable = temp_data ? g.Tables.GetByIndex(temp_data->TableIndex) : NULL;\r\n    if (g.CurrentTable)\r\n    {\r\n        g.CurrentTable->TempData = temp_data;\r\n        g.CurrentTable->DrawSplitter = &temp_data->DrawSplitter;\r\n    }\r\n    outer_window->DC.CurrentTableIdx = g.CurrentTable ? g.Tables.GetIndex(g.CurrentTable) : -1;\r\n}\r\n\r\n// See \"COLUMN SIZING POLICIES\" comments at the top of this file\r\n// If (init_width_or_weight <= 0.0f) it is ignored\r\nvoid ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, float init_width_or_weight, ImGuiID user_id)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiTable* table = g.CurrentTable;\r\n    IM_ASSERT(table != NULL && \"Need to call TableSetupColumn() after BeginTable()!\");\r\n    IM_ASSERT(table->IsLayoutLocked == false && \"Need to call call TableSetupColumn() before first row!\");\r\n    IM_ASSERT((flags & ImGuiTableColumnFlags_StatusMask_) == 0 && \"Illegal to pass StatusMask values to TableSetupColumn()\");\r\n    if (table->DeclColumnsCount >= table->ColumnsCount)\r\n    {\r\n        IM_ASSERT_USER_ERROR(table->DeclColumnsCount < table->ColumnsCount, \"Called TableSetupColumn() too many times!\");\r\n        return;\r\n    }\r\n\r\n    ImGuiTableColumn* column = &table->Columns[table->DeclColumnsCount];\r\n    table->DeclColumnsCount++;\r\n\r\n    // Assert when passing a width or weight if policy is entirely left to default, to avoid storing width into weight and vice-versa.\r\n    // Give a grace to users of ImGuiTableFlags_ScrollX.\r\n    if (table->IsDefaultSizingPolicy && (flags & ImGuiTableColumnFlags_WidthMask_) == 0 && (flags & ImGuiTableFlags_ScrollX) == 0)\r\n        IM_ASSERT(init_width_or_weight <= 0.0f && \"Can only specify width/weight if sizing policy is set explicitly in either Table or Column.\");\r\n\r\n    // When passing a width automatically enforce WidthFixed policy\r\n    // (whereas TableSetupColumnFlags would default to WidthAuto if table is not Resizable)\r\n    if ((flags & ImGuiTableColumnFlags_WidthMask_) == 0 && init_width_or_weight > 0.0f)\r\n        if ((table->Flags & ImGuiTableFlags_SizingMask_) == ImGuiTableFlags_SizingFixedFit || (table->Flags & ImGuiTableFlags_SizingMask_) == ImGuiTableFlags_SizingFixedSame)\r\n            flags |= ImGuiTableColumnFlags_WidthFixed;\r\n\r\n    TableSetupColumnFlags(table, column, flags);\r\n    column->UserID = user_id;\r\n    flags = column->Flags;\r\n\r\n    // Initialize defaults\r\n    column->InitStretchWeightOrWidth = init_width_or_weight;\r\n    if (table->IsInitializing)\r\n    {\r\n        // Init width or weight\r\n        if (column->WidthRequest < 0.0f && column->StretchWeight < 0.0f)\r\n        {\r\n            if ((flags & ImGuiTableColumnFlags_WidthFixed) && init_width_or_weight > 0.0f)\r\n                column->WidthRequest = init_width_or_weight;\r\n            if (flags & ImGuiTableColumnFlags_WidthStretch)\r\n                column->StretchWeight = (init_width_or_weight > 0.0f) ? init_width_or_weight : -1.0f;\r\n\r\n            // Disable auto-fit if an explicit width/weight has been specified\r\n            if (init_width_or_weight > 0.0f)\r\n                column->AutoFitQueue = 0x00;\r\n        }\r\n\r\n        // Init default visibility/sort state\r\n        if ((flags & ImGuiTableColumnFlags_DefaultHide) && (table->SettingsLoadedFlags & ImGuiTableFlags_Hideable) == 0)\r\n            column->IsUserEnabled = column->IsUserEnabledNextFrame = false;\r\n        if (flags & ImGuiTableColumnFlags_DefaultSort && (table->SettingsLoadedFlags & ImGuiTableFlags_Sortable) == 0)\r\n        {\r\n            column->SortOrder = 0; // Multiple columns using _DefaultSort will be reassigned unique SortOrder values when building the sort specs.\r\n            column->SortDirection = (column->Flags & ImGuiTableColumnFlags_PreferSortDescending) ? (ImS8)ImGuiSortDirection_Descending : (ImU8)(ImGuiSortDirection_Ascending);\r\n        }\r\n    }\r\n\r\n    // Store name (append with zero-terminator in contiguous buffer)\r\n    column->NameOffset = -1;\r\n    if (label != NULL && label[0] != 0)\r\n    {\r\n        column->NameOffset = (ImS16)table->ColumnsNames.size();\r\n        table->ColumnsNames.append(label, label + strlen(label) + 1);\r\n    }\r\n}\r\n\r\n// [Public]\r\nvoid ImGui::TableSetupScrollFreeze(int columns, int rows)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiTable* table = g.CurrentTable;\r\n    IM_ASSERT(table != NULL && \"Need to call TableSetupColumn() after BeginTable()!\");\r\n    IM_ASSERT(table->IsLayoutLocked == false && \"Need to call TableSetupColumn() before first row!\");\r\n    IM_ASSERT(columns >= 0 && columns < IMGUI_TABLE_MAX_COLUMNS);\r\n    IM_ASSERT(rows >= 0 && rows < 128); // Arbitrary limit\r\n\r\n    table->FreezeColumnsRequest = (table->Flags & ImGuiTableFlags_ScrollX) ? (ImGuiTableColumnIdx)ImMin(columns, table->ColumnsCount) : 0;\r\n    table->FreezeColumnsCount = (table->InnerWindow->Scroll.x != 0.0f) ? table->FreezeColumnsRequest : 0;\r\n    table->FreezeRowsRequest = (table->Flags & ImGuiTableFlags_ScrollY) ? (ImGuiTableColumnIdx)rows : 0;\r\n    table->FreezeRowsCount = (table->InnerWindow->Scroll.y != 0.0f) ? table->FreezeRowsRequest : 0;\r\n    table->IsUnfrozenRows = (table->FreezeRowsCount == 0); // Make sure this is set before TableUpdateLayout() so ImGuiListClipper can benefit from it.b\r\n\r\n    // Ensure frozen columns are ordered in their section. We still allow multiple frozen columns to be reordered.\r\n    // FIXME-TABLE: This work for preserving 2143 into 21|43. How about 4321 turning into 21|43? (preserve relative order in each section)\r\n    for (int column_n = 0; column_n < table->FreezeColumnsRequest; column_n++)\r\n    {\r\n        int order_n = table->DisplayOrderToIndex[column_n];\r\n        if (order_n != column_n && order_n >= table->FreezeColumnsRequest)\r\n        {\r\n            ImSwap(table->Columns[table->DisplayOrderToIndex[order_n]].DisplayOrder, table->Columns[table->DisplayOrderToIndex[column_n]].DisplayOrder);\r\n            ImSwap(table->DisplayOrderToIndex[order_n], table->DisplayOrderToIndex[column_n]);\r\n        }\r\n    }\r\n}\r\n\r\n//-----------------------------------------------------------------------------\r\n// [SECTION] Tables: Simple accessors\r\n//-----------------------------------------------------------------------------\r\n// - TableGetColumnCount()\r\n// - TableGetColumnName()\r\n// - TableGetColumnName() [Internal]\r\n// - TableSetColumnEnabled()\r\n// - TableGetColumnFlags()\r\n// - TableGetCellBgRect() [Internal]\r\n// - TableGetColumnResizeID() [Internal]\r\n// - TableGetHoveredColumn() [Internal]\r\n// - TableSetBgColor()\r\n//-----------------------------------------------------------------------------\r\n\r\nint ImGui::TableGetColumnCount()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiTable* table = g.CurrentTable;\r\n    return table ? table->ColumnsCount : 0;\r\n}\r\n\r\nconst char* ImGui::TableGetColumnName(int column_n)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiTable* table = g.CurrentTable;\r\n    if (!table)\r\n        return NULL;\r\n    if (column_n < 0)\r\n        column_n = table->CurrentColumn;\r\n    return TableGetColumnName(table, column_n);\r\n}\r\n\r\nconst char* ImGui::TableGetColumnName(const ImGuiTable* table, int column_n)\r\n{\r\n    if (table->IsLayoutLocked == false && column_n >= table->DeclColumnsCount)\r\n        return \"\"; // NameOffset is invalid at this point\r\n    const ImGuiTableColumn* column = &table->Columns[column_n];\r\n    if (column->NameOffset == -1)\r\n        return \"\";\r\n    return &table->ColumnsNames.Buf[column->NameOffset];\r\n}\r\n\r\n// Change user accessible enabled/disabled state of a column (often perceived as \"showing/hiding\" from users point of view)\r\n// Note that end-user can use the context menu to change this themselves (right-click in headers, or right-click in columns body with ImGuiTableFlags_ContextMenuInBody)\r\n// - Require table to have the ImGuiTableFlags_Hideable flag because we are manipulating user accessible state.\r\n// - Request will be applied during next layout, which happens on the first call to TableNextRow() after BeginTable().\r\n// - For the getter you can test (TableGetColumnFlags() & ImGuiTableColumnFlags_IsEnabled) != 0.\r\n// - Alternative: the ImGuiTableColumnFlags_Disabled is an overriding/master disable flag which will also hide the column from context menu.\r\nvoid ImGui::TableSetColumnEnabled(int column_n, bool enabled)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiTable* table = g.CurrentTable;\r\n    IM_ASSERT(table != NULL);\r\n    if (!table)\r\n        return;\r\n    IM_ASSERT(table->Flags & ImGuiTableFlags_Hideable); // See comments above\r\n    if (column_n < 0)\r\n        column_n = table->CurrentColumn;\r\n    IM_ASSERT(column_n >= 0 && column_n < table->ColumnsCount);\r\n    ImGuiTableColumn* column = &table->Columns[column_n];\r\n    column->IsUserEnabledNextFrame = enabled;\r\n}\r\n\r\n// We allow querying for an extra column in order to poll the IsHovered state of the right-most section\r\nImGuiTableColumnFlags ImGui::TableGetColumnFlags(int column_n)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiTable* table = g.CurrentTable;\r\n    if (!table)\r\n        return ImGuiTableColumnFlags_None;\r\n    if (column_n < 0)\r\n        column_n = table->CurrentColumn;\r\n    if (column_n == table->ColumnsCount)\r\n        return (table->HoveredColumnBody == column_n) ? ImGuiTableColumnFlags_IsHovered : ImGuiTableColumnFlags_None;\r\n    return table->Columns[column_n].Flags;\r\n}\r\n\r\n// Return the cell rectangle based on currently known height.\r\n// - Important: we generally don't know our row height until the end of the row, so Max.y will be incorrect in many situations.\r\n//   The only case where this is correct is if we provided a min_row_height to TableNextRow() and don't go below it, or in TableEndRow() when we locked that height.\r\n// - Important: if ImGuiTableFlags_PadOuterX is set but ImGuiTableFlags_PadInnerX is not set, the outer-most left and right\r\n//   columns report a small offset so their CellBgRect can extend up to the outer border.\r\n//   FIXME: But the rendering code in TableEndRow() nullifies that with clamping required for scrolling.\r\nImRect ImGui::TableGetCellBgRect(const ImGuiTable* table, int column_n)\r\n{\r\n    const ImGuiTableColumn* column = &table->Columns[column_n];\r\n    float x1 = column->MinX;\r\n    float x2 = column->MaxX;\r\n    //if (column->PrevEnabledColumn == -1)\r\n    //    x1 -= table->OuterPaddingX;\r\n    //if (column->NextEnabledColumn == -1)\r\n    //    x2 += table->OuterPaddingX;\r\n    x1 = ImMax(x1, table->WorkRect.Min.x);\r\n    x2 = ImMin(x2, table->WorkRect.Max.x);\r\n    return ImRect(x1, table->RowPosY1, x2, table->RowPosY2);\r\n}\r\n\r\n// Return the resizing ID for the right-side of the given column.\r\nImGuiID ImGui::TableGetColumnResizeID(const ImGuiTable* table, int column_n, int instance_no)\r\n{\r\n    IM_ASSERT(column_n >= 0 && column_n < table->ColumnsCount);\r\n    ImGuiID id = table->ID + 1 + (instance_no * table->ColumnsCount) + column_n;\r\n    return id;\r\n}\r\n\r\n// Return -1 when table is not hovered. return columns_count if the unused space at the right of visible columns is hovered.\r\nint ImGui::TableGetHoveredColumn()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiTable* table = g.CurrentTable;\r\n    if (!table)\r\n        return -1;\r\n    return (int)table->HoveredColumnBody;\r\n}\r\n\r\nvoid ImGui::TableSetBgColor(ImGuiTableBgTarget target, ImU32 color, int column_n)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiTable* table = g.CurrentTable;\r\n    IM_ASSERT(target != ImGuiTableBgTarget_None);\r\n\r\n    if (color == IM_COL32_DISABLE)\r\n        color = 0;\r\n\r\n    // We cannot draw neither the cell or row background immediately as we don't know the row height at this point in time.\r\n    switch (target)\r\n    {\r\n    case ImGuiTableBgTarget_CellBg:\r\n    {\r\n        if (table->RowPosY1 > table->InnerClipRect.Max.y) // Discard\r\n            return;\r\n        if (column_n == -1)\r\n            column_n = table->CurrentColumn;\r\n        if ((table->VisibleMaskByIndex & ((ImU64)1 << column_n)) == 0)\r\n            return;\r\n        if (table->RowCellDataCurrent < 0 || table->RowCellData[table->RowCellDataCurrent].Column != column_n)\r\n            table->RowCellDataCurrent++;\r\n        ImGuiTableCellData* cell_data = &table->RowCellData[table->RowCellDataCurrent];\r\n        cell_data->BgColor = color;\r\n        cell_data->Column = (ImGuiTableColumnIdx)column_n;\r\n        break;\r\n    }\r\n    case ImGuiTableBgTarget_RowBg0:\r\n    case ImGuiTableBgTarget_RowBg1:\r\n    {\r\n        if (table->RowPosY1 > table->InnerClipRect.Max.y) // Discard\r\n            return;\r\n        IM_ASSERT(column_n == -1);\r\n        int bg_idx = (target == ImGuiTableBgTarget_RowBg1) ? 1 : 0;\r\n        table->RowBgColor[bg_idx] = color;\r\n        break;\r\n    }\r\n    default:\r\n        IM_ASSERT(0);\r\n    }\r\n}\r\n\r\n//-------------------------------------------------------------------------\r\n// [SECTION] Tables: Row changes\r\n//-------------------------------------------------------------------------\r\n// - TableGetRowIndex()\r\n// - TableNextRow()\r\n// - TableBeginRow() [Internal]\r\n// - TableEndRow() [Internal]\r\n//-------------------------------------------------------------------------\r\n\r\n// [Public] Note: for row coloring we use ->RowBgColorCounter which is the same value without counting header rows\r\nint ImGui::TableGetRowIndex()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiTable* table = g.CurrentTable;\r\n    if (!table)\r\n        return 0;\r\n    return table->CurrentRow;\r\n}\r\n\r\n// [Public] Starts into the first cell of a new row\r\nvoid ImGui::TableNextRow(ImGuiTableRowFlags row_flags, float row_min_height)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiTable* table = g.CurrentTable;\r\n\r\n    if (!table->IsLayoutLocked)\r\n        TableUpdateLayout(table);\r\n    if (table->IsInsideRow)\r\n        TableEndRow(table);\r\n\r\n    table->LastRowFlags = table->RowFlags;\r\n    table->RowFlags = row_flags;\r\n    table->RowMinHeight = row_min_height;\r\n    TableBeginRow(table);\r\n\r\n    // We honor min_row_height requested by user, but cannot guarantee per-row maximum height,\r\n    // because that would essentially require a unique clipping rectangle per-cell.\r\n    table->RowPosY2 += table->CellPaddingY * 2.0f;\r\n    table->RowPosY2 = ImMax(table->RowPosY2, table->RowPosY1 + row_min_height);\r\n\r\n    // Disable output until user calls TableNextColumn()\r\n    table->InnerWindow->SkipItems = true;\r\n}\r\n\r\n// [Internal] Called by TableNextRow()\r\nvoid ImGui::TableBeginRow(ImGuiTable* table)\r\n{\r\n    ImGuiWindow* window = table->InnerWindow;\r\n    IM_ASSERT(!table->IsInsideRow);\r\n\r\n    // New row\r\n    table->CurrentRow++;\r\n    table->CurrentColumn = -1;\r\n    table->RowBgColor[0] = table->RowBgColor[1] = IM_COL32_DISABLE;\r\n    table->RowCellDataCurrent = -1;\r\n    table->IsInsideRow = true;\r\n\r\n    // Begin frozen rows\r\n    float next_y1 = table->RowPosY2;\r\n    if (table->CurrentRow == 0 && table->FreezeRowsCount > 0)\r\n        next_y1 = window->DC.CursorPos.y = table->OuterRect.Min.y;\r\n\r\n    table->RowPosY1 = table->RowPosY2 = next_y1;\r\n    table->RowTextBaseline = 0.0f;\r\n    table->RowIndentOffsetX = window->DC.Indent.x - table->HostIndentX; // Lock indent\r\n    window->DC.PrevLineTextBaseOffset = 0.0f;\r\n    window->DC.CursorMaxPos.y = next_y1;\r\n\r\n    // Making the header BG color non-transparent will allow us to overlay it multiple times when handling smooth dragging.\r\n    if (table->RowFlags & ImGuiTableRowFlags_Headers)\r\n    {\r\n        TableSetBgColor(ImGuiTableBgTarget_RowBg0, GetColorU32(ImGuiCol_TableHeaderBg));\r\n        if (table->CurrentRow == 0)\r\n            table->IsUsingHeaders = true;\r\n    }\r\n}\r\n\r\n// [Internal] Called by TableNextRow()\r\nvoid ImGui::TableEndRow(ImGuiTable* table)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    IM_ASSERT(window == table->InnerWindow);\r\n    IM_ASSERT(table->IsInsideRow);\r\n\r\n    if (table->CurrentColumn != -1)\r\n        TableEndCell(table);\r\n\r\n    // Logging\r\n    if (g.LogEnabled)\r\n        LogRenderedText(NULL, \"|\");\r\n\r\n    // Position cursor at the bottom of our row so it can be used for e.g. clipping calculation. However it is\r\n    // likely that the next call to TableBeginCell() will reposition the cursor to take account of vertical padding.\r\n    window->DC.CursorPos.y = table->RowPosY2;\r\n\r\n    // Row background fill\r\n    const float bg_y1 = table->RowPosY1;\r\n    const float bg_y2 = table->RowPosY2;\r\n    const bool unfreeze_rows_actual = (table->CurrentRow + 1 == table->FreezeRowsCount);\r\n    const bool unfreeze_rows_request = (table->CurrentRow + 1 == table->FreezeRowsRequest);\r\n    if (table->CurrentRow == 0)\r\n        table->LastFirstRowHeight = bg_y2 - bg_y1;\r\n\r\n    const bool is_visible = (bg_y2 >= table->InnerClipRect.Min.y && bg_y1 <= table->InnerClipRect.Max.y);\r\n    if (is_visible)\r\n    {\r\n        // Decide of background color for the row\r\n        ImU32 bg_col0 = 0;\r\n        ImU32 bg_col1 = 0;\r\n        if (table->RowBgColor[0] != IM_COL32_DISABLE)\r\n            bg_col0 = table->RowBgColor[0];\r\n        else if (table->Flags & ImGuiTableFlags_RowBg)\r\n            bg_col0 = GetColorU32((table->RowBgColorCounter & 1) ? ImGuiCol_TableRowBgAlt : ImGuiCol_TableRowBg);\r\n        if (table->RowBgColor[1] != IM_COL32_DISABLE)\r\n            bg_col1 = table->RowBgColor[1];\r\n\r\n        // Decide of top border color\r\n        ImU32 border_col = 0;\r\n        const float border_size = TABLE_BORDER_SIZE;\r\n        if (table->CurrentRow > 0 || table->InnerWindow == table->OuterWindow)\r\n            if (table->Flags & ImGuiTableFlags_BordersInnerH)\r\n                border_col = (table->LastRowFlags & ImGuiTableRowFlags_Headers) ? table->BorderColorStrong : table->BorderColorLight;\r\n\r\n        const bool draw_cell_bg_color = table->RowCellDataCurrent >= 0;\r\n        const bool draw_strong_bottom_border = unfreeze_rows_actual;\r\n        if ((bg_col0 | bg_col1 | border_col) != 0 || draw_strong_bottom_border || draw_cell_bg_color)\r\n        {\r\n            // In theory we could call SetWindowClipRectBeforeSetChannel() but since we know TableEndRow() is\r\n            // always followed by a change of clipping rectangle we perform the smallest overwrite possible here.\r\n            if ((table->Flags & ImGuiTableFlags_NoClip) == 0)\r\n                window->DrawList->_CmdHeader.ClipRect = table->Bg0ClipRectForDrawCmd.ToVec4();\r\n            table->DrawSplitter->SetCurrentChannel(window->DrawList, TABLE_DRAW_CHANNEL_BG0);\r\n        }\r\n\r\n        // Draw row background\r\n        // We soft/cpu clip this so all backgrounds and borders can share the same clipping rectangle\r\n        if (bg_col0 || bg_col1)\r\n        {\r\n            ImRect row_rect(table->WorkRect.Min.x, bg_y1, table->WorkRect.Max.x, bg_y2);\r\n            row_rect.ClipWith(table->BgClipRect);\r\n            if (bg_col0 != 0 && row_rect.Min.y < row_rect.Max.y)\r\n                window->DrawList->AddRectFilled(row_rect.Min, row_rect.Max, bg_col0);\r\n            if (bg_col1 != 0 && row_rect.Min.y < row_rect.Max.y)\r\n                window->DrawList->AddRectFilled(row_rect.Min, row_rect.Max, bg_col1);\r\n        }\r\n\r\n        // Draw cell background color\r\n        if (draw_cell_bg_color)\r\n        {\r\n            ImGuiTableCellData* cell_data_end = &table->RowCellData[table->RowCellDataCurrent];\r\n            for (ImGuiTableCellData* cell_data = &table->RowCellData[0]; cell_data <= cell_data_end; cell_data++)\r\n            {\r\n                // As we render the BG here we need to clip things (for layout we would not)\r\n                // FIXME: This cancels the OuterPadding addition done by TableGetCellBgRect(), need to keep it while rendering correctly while scrolling.\r\n                const ImGuiTableColumn* column = &table->Columns[cell_data->Column];\r\n                ImRect cell_bg_rect = TableGetCellBgRect(table, cell_data->Column);\r\n                cell_bg_rect.ClipWith(table->BgClipRect);\r\n                cell_bg_rect.Min.x = ImMax(cell_bg_rect.Min.x, column->ClipRect.Min.x);     // So that first column after frozen one gets clipped when scrolling\r\n                cell_bg_rect.Max.x = ImMin(cell_bg_rect.Max.x, column->MaxX);\r\n                window->DrawList->AddRectFilled(cell_bg_rect.Min, cell_bg_rect.Max, cell_data->BgColor);\r\n            }\r\n        }\r\n\r\n        // Draw top border\r\n        if (border_col && bg_y1 >= table->BgClipRect.Min.y && bg_y1 < table->BgClipRect.Max.y)\r\n            window->DrawList->AddLine(ImVec2(table->BorderX1, bg_y1), ImVec2(table->BorderX2, bg_y1), border_col, border_size);\r\n\r\n        // Draw bottom border at the row unfreezing mark (always strong)\r\n        if (draw_strong_bottom_border && bg_y2 >= table->BgClipRect.Min.y && bg_y2 < table->BgClipRect.Max.y)\r\n            window->DrawList->AddLine(ImVec2(table->BorderX1, bg_y2), ImVec2(table->BorderX2, bg_y2), table->BorderColorStrong, border_size);\r\n    }\r\n\r\n    // End frozen rows (when we are past the last frozen row line, teleport cursor and alter clipping rectangle)\r\n    // We need to do that in TableEndRow() instead of TableBeginRow() so the list clipper can mark end of row and\r\n    // get the new cursor position.\r\n    if (unfreeze_rows_request)\r\n        for (int column_n = 0; column_n < table->ColumnsCount; column_n++)\r\n        {\r\n            ImGuiTableColumn* column = &table->Columns[column_n];\r\n            column->NavLayerCurrent = (ImS8)((column_n < table->FreezeColumnsCount) ? ImGuiNavLayer_Menu : ImGuiNavLayer_Main);\r\n        }\r\n    if (unfreeze_rows_actual)\r\n    {\r\n        IM_ASSERT(table->IsUnfrozenRows == false);\r\n        table->IsUnfrozenRows = true;\r\n\r\n        // BgClipRect starts as table->InnerClipRect, reduce it now and make BgClipRectForDrawCmd == BgClipRect\r\n        float y0 = ImMax(table->RowPosY2 + 1, window->InnerClipRect.Min.y);\r\n        table->BgClipRect.Min.y = table->Bg2ClipRectForDrawCmd.Min.y = ImMin(y0, window->InnerClipRect.Max.y);\r\n        table->BgClipRect.Max.y = table->Bg2ClipRectForDrawCmd.Max.y = window->InnerClipRect.Max.y;\r\n        table->Bg2DrawChannelCurrent = table->Bg2DrawChannelUnfrozen;\r\n        IM_ASSERT(table->Bg2ClipRectForDrawCmd.Min.y <= table->Bg2ClipRectForDrawCmd.Max.y);\r\n\r\n        float row_height = table->RowPosY2 - table->RowPosY1;\r\n        table->RowPosY2 = window->DC.CursorPos.y = table->WorkRect.Min.y + table->RowPosY2 - table->OuterRect.Min.y;\r\n        table->RowPosY1 = table->RowPosY2 - row_height;\r\n        for (int column_n = 0; column_n < table->ColumnsCount; column_n++)\r\n        {\r\n            ImGuiTableColumn* column = &table->Columns[column_n];\r\n            column->DrawChannelCurrent = column->DrawChannelUnfrozen;\r\n            column->ClipRect.Min.y = table->Bg2ClipRectForDrawCmd.Min.y;\r\n        }\r\n\r\n        // Update cliprect ahead of TableBeginCell() so clipper can access to new ClipRect->Min.y\r\n        SetWindowClipRectBeforeSetChannel(window, table->Columns[0].ClipRect);\r\n        table->DrawSplitter->SetCurrentChannel(window->DrawList, table->Columns[0].DrawChannelCurrent);\r\n    }\r\n\r\n    if (!(table->RowFlags & ImGuiTableRowFlags_Headers))\r\n        table->RowBgColorCounter++;\r\n    table->IsInsideRow = false;\r\n}\r\n\r\n//-------------------------------------------------------------------------\r\n// [SECTION] Tables: Columns changes\r\n//-------------------------------------------------------------------------\r\n// - TableGetColumnIndex()\r\n// - TableSetColumnIndex()\r\n// - TableNextColumn()\r\n// - TableBeginCell() [Internal]\r\n// - TableEndCell() [Internal]\r\n//-------------------------------------------------------------------------\r\n\r\nint ImGui::TableGetColumnIndex()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiTable* table = g.CurrentTable;\r\n    if (!table)\r\n        return 0;\r\n    return table->CurrentColumn;\r\n}\r\n\r\n// [Public] Append into a specific column\r\nbool ImGui::TableSetColumnIndex(int column_n)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiTable* table = g.CurrentTable;\r\n    if (!table)\r\n        return false;\r\n\r\n    if (table->CurrentColumn != column_n)\r\n    {\r\n        if (table->CurrentColumn != -1)\r\n            TableEndCell(table);\r\n        IM_ASSERT(column_n >= 0 && table->ColumnsCount);\r\n        TableBeginCell(table, column_n);\r\n    }\r\n\r\n    // Return whether the column is visible. User may choose to skip submitting items based on this return value,\r\n    // however they shouldn't skip submitting for columns that may have the tallest contribution to row height.\r\n    return (table->RequestOutputMaskByIndex & ((ImU64)1 << column_n)) != 0;\r\n}\r\n\r\n// [Public] Append into the next column, wrap and create a new row when already on last column\r\nbool ImGui::TableNextColumn()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiTable* table = g.CurrentTable;\r\n    if (!table)\r\n        return false;\r\n\r\n    if (table->IsInsideRow && table->CurrentColumn + 1 < table->ColumnsCount)\r\n    {\r\n        if (table->CurrentColumn != -1)\r\n            TableEndCell(table);\r\n        TableBeginCell(table, table->CurrentColumn + 1);\r\n    }\r\n    else\r\n    {\r\n        TableNextRow();\r\n        TableBeginCell(table, 0);\r\n    }\r\n\r\n    // Return whether the column is visible. User may choose to skip submitting items based on this return value,\r\n    // however they shouldn't skip submitting for columns that may have the tallest contribution to row height.\r\n    int column_n = table->CurrentColumn;\r\n    return (table->RequestOutputMaskByIndex & ((ImU64)1 << column_n)) != 0;\r\n}\r\n\r\n\r\n// [Internal] Called by TableSetColumnIndex()/TableNextColumn()\r\n// This is called very frequently, so we need to be mindful of unnecessary overhead.\r\n// FIXME-TABLE FIXME-OPT: Could probably shortcut some things for non-active or clipped columns.\r\nvoid ImGui::TableBeginCell(ImGuiTable* table, int column_n)\r\n{\r\n    ImGuiTableColumn* column = &table->Columns[column_n];\r\n    ImGuiWindow* window = table->InnerWindow;\r\n    table->CurrentColumn = column_n;\r\n\r\n    // Start position is roughly ~~ CellRect.Min + CellPadding + Indent\r\n    float start_x = column->WorkMinX;\r\n    if (column->Flags & ImGuiTableColumnFlags_IndentEnable)\r\n        start_x += table->RowIndentOffsetX; // ~~ += window.DC.Indent.x - table->HostIndentX, except we locked it for the row.\r\n\r\n    window->DC.CursorPos.x = start_x;\r\n    window->DC.CursorPos.y = table->RowPosY1 + table->CellPaddingY;\r\n    window->DC.CursorMaxPos.x = window->DC.CursorPos.x;\r\n    window->DC.ColumnsOffset.x = start_x - window->Pos.x - window->DC.Indent.x; // FIXME-WORKRECT\r\n    window->DC.CurrLineTextBaseOffset = table->RowTextBaseline;\r\n    window->DC.NavLayerCurrent = (ImGuiNavLayer)column->NavLayerCurrent;\r\n\r\n    window->WorkRect.Min.y = window->DC.CursorPos.y;\r\n    window->WorkRect.Min.x = column->WorkMinX;\r\n    window->WorkRect.Max.x = column->WorkMaxX;\r\n    window->DC.ItemWidth = column->ItemWidth;\r\n\r\n    // To allow ImGuiListClipper to function we propagate our row height\r\n    if (!column->IsEnabled)\r\n        window->DC.CursorPos.y = ImMax(window->DC.CursorPos.y, table->RowPosY2);\r\n\r\n    window->SkipItems = column->IsSkipItems;\r\n    if (column->IsSkipItems)\r\n    {\r\n        ImGuiContext& g = *GImGui;\r\n        g.LastItemData.ID = 0;\r\n        g.LastItemData.StatusFlags = 0;\r\n    }\r\n\r\n    if (table->Flags & ImGuiTableFlags_NoClip)\r\n    {\r\n        // FIXME: if we end up drawing all borders/bg in EndTable, could remove this and just assert that channel hasn't changed.\r\n        table->DrawSplitter->SetCurrentChannel(window->DrawList, TABLE_DRAW_CHANNEL_NOCLIP);\r\n        //IM_ASSERT(table->DrawSplitter._Current == TABLE_DRAW_CHANNEL_NOCLIP);\r\n    }\r\n    else\r\n    {\r\n        // FIXME-TABLE: Could avoid this if draw channel is dummy channel?\r\n        SetWindowClipRectBeforeSetChannel(window, column->ClipRect);\r\n        table->DrawSplitter->SetCurrentChannel(window->DrawList, column->DrawChannelCurrent);\r\n    }\r\n\r\n    // Logging\r\n    ImGuiContext& g = *GImGui;\r\n    if (g.LogEnabled && !column->IsSkipItems)\r\n    {\r\n        LogRenderedText(&window->DC.CursorPos, \"|\");\r\n        g.LogLinePosY = FLT_MAX;\r\n    }\r\n}\r\n\r\n// [Internal] Called by TableNextRow()/TableSetColumnIndex()/TableNextColumn()\r\nvoid ImGui::TableEndCell(ImGuiTable* table)\r\n{\r\n    ImGuiTableColumn* column = &table->Columns[table->CurrentColumn];\r\n    ImGuiWindow* window = table->InnerWindow;\r\n\r\n    // Report maximum position so we can infer content size per column.\r\n    float* p_max_pos_x;\r\n    if (table->RowFlags & ImGuiTableRowFlags_Headers)\r\n        p_max_pos_x = &column->ContentMaxXHeadersUsed;  // Useful in case user submit contents in header row that is not a TableHeader() call\r\n    else\r\n        p_max_pos_x = table->IsUnfrozenRows ? &column->ContentMaxXUnfrozen : &column->ContentMaxXFrozen;\r\n    *p_max_pos_x = ImMax(*p_max_pos_x, window->DC.CursorMaxPos.x);\r\n    table->RowPosY2 = ImMax(table->RowPosY2, window->DC.CursorMaxPos.y + table->CellPaddingY);\r\n    column->ItemWidth = window->DC.ItemWidth;\r\n\r\n    // Propagate text baseline for the entire row\r\n    // FIXME-TABLE: Here we propagate text baseline from the last line of the cell.. instead of the first one.\r\n    table->RowTextBaseline = ImMax(table->RowTextBaseline, window->DC.PrevLineTextBaseOffset);\r\n}\r\n\r\n//-------------------------------------------------------------------------\r\n// [SECTION] Tables: Columns width management\r\n//-------------------------------------------------------------------------\r\n// - TableGetMaxColumnWidth() [Internal]\r\n// - TableGetColumnWidthAuto() [Internal]\r\n// - TableSetColumnWidth()\r\n// - TableSetColumnWidthAutoSingle() [Internal]\r\n// - TableSetColumnWidthAutoAll() [Internal]\r\n// - TableUpdateColumnsWeightFromWidth() [Internal]\r\n//-------------------------------------------------------------------------\r\n\r\n// Maximum column content width given current layout. Use column->MinX so this value on a per-column basis.\r\nfloat ImGui::TableGetMaxColumnWidth(const ImGuiTable* table, int column_n)\r\n{\r\n    const ImGuiTableColumn* column = &table->Columns[column_n];\r\n    float max_width = FLT_MAX;\r\n    const float min_column_distance = table->MinColumnWidth + table->CellPaddingX * 2.0f + table->CellSpacingX1 + table->CellSpacingX2;\r\n    if (table->Flags & ImGuiTableFlags_ScrollX)\r\n    {\r\n        // Frozen columns can't reach beyond visible width else scrolling will naturally break.\r\n        // (we use DisplayOrder as within a set of multiple frozen column reordering is possible)\r\n        if (column->DisplayOrder < table->FreezeColumnsRequest)\r\n        {\r\n            max_width = (table->InnerClipRect.Max.x - (table->FreezeColumnsRequest - column->DisplayOrder) * min_column_distance) - column->MinX;\r\n            max_width = max_width - table->OuterPaddingX - table->CellPaddingX - table->CellSpacingX2;\r\n        }\r\n    }\r\n    else if ((table->Flags & ImGuiTableFlags_NoKeepColumnsVisible) == 0)\r\n    {\r\n        // If horizontal scrolling if disabled, we apply a final lossless shrinking of columns in order to make\r\n        // sure they are all visible. Because of this we also know that all of the columns will always fit in\r\n        // table->WorkRect and therefore in table->InnerRect (because ScrollX is off)\r\n        // FIXME-TABLE: This is solved incorrectly but also quite a difficult problem to fix as we also want ClipRect width to match.\r\n        // See \"table_width_distrib\" and \"table_width_keep_visible\" tests\r\n        max_width = table->WorkRect.Max.x - (table->ColumnsEnabledCount - column->IndexWithinEnabledSet - 1) * min_column_distance - column->MinX;\r\n        //max_width -= table->CellSpacingX1;\r\n        max_width -= table->CellSpacingX2;\r\n        max_width -= table->CellPaddingX * 2.0f;\r\n        max_width -= table->OuterPaddingX;\r\n    }\r\n    return max_width;\r\n}\r\n\r\n// Note this is meant to be stored in column->WidthAuto, please generally use the WidthAuto field\r\nfloat ImGui::TableGetColumnWidthAuto(ImGuiTable* table, ImGuiTableColumn* column)\r\n{\r\n    const float content_width_body = ImMax(column->ContentMaxXFrozen, column->ContentMaxXUnfrozen) - column->WorkMinX;\r\n    const float content_width_headers = column->ContentMaxXHeadersIdeal - column->WorkMinX;\r\n    float width_auto = content_width_body;\r\n    if (!(column->Flags & ImGuiTableColumnFlags_NoHeaderWidth))\r\n        width_auto = ImMax(width_auto, content_width_headers);\r\n\r\n    // Non-resizable fixed columns preserve their requested width\r\n    if ((column->Flags & ImGuiTableColumnFlags_WidthFixed) && column->InitStretchWeightOrWidth > 0.0f)\r\n        if (!(table->Flags & ImGuiTableFlags_Resizable) || (column->Flags & ImGuiTableColumnFlags_NoResize))\r\n            width_auto = column->InitStretchWeightOrWidth;\r\n\r\n    return ImMax(width_auto, table->MinColumnWidth);\r\n}\r\n\r\n// 'width' = inner column width, without padding\r\nvoid ImGui::TableSetColumnWidth(int column_n, float width)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiTable* table = g.CurrentTable;\r\n    IM_ASSERT(table != NULL && table->IsLayoutLocked == false);\r\n    IM_ASSERT(column_n >= 0 && column_n < table->ColumnsCount);\r\n    ImGuiTableColumn* column_0 = &table->Columns[column_n];\r\n    float column_0_width = width;\r\n\r\n    // Apply constraints early\r\n    // Compare both requested and actual given width to avoid overwriting requested width when column is stuck (minimum size, bounded)\r\n    IM_ASSERT(table->MinColumnWidth > 0.0f);\r\n    const float min_width = table->MinColumnWidth;\r\n    const float max_width = ImMax(min_width, TableGetMaxColumnWidth(table, column_n));\r\n    column_0_width = ImClamp(column_0_width, min_width, max_width);\r\n    if (column_0->WidthGiven == column_0_width || column_0->WidthRequest == column_0_width)\r\n        return;\r\n\r\n    //IMGUI_DEBUG_LOG(\"TableSetColumnWidth(%d, %.1f->%.1f)\\n\", column_0_idx, column_0->WidthGiven, column_0_width);\r\n    ImGuiTableColumn* column_1 = (column_0->NextEnabledColumn != -1) ? &table->Columns[column_0->NextEnabledColumn] : NULL;\r\n\r\n    // In this surprisingly not simple because of how we support mixing Fixed and multiple Stretch columns.\r\n    // - All fixed: easy.\r\n    // - All stretch: easy.\r\n    // - One or more fixed + one stretch: easy.\r\n    // - One or more fixed + more than one stretch: tricky.\r\n    // Qt when manual resize is enabled only support a single _trailing_ stretch column.\r\n\r\n    // When forwarding resize from Wn| to Fn+1| we need to be considerate of the _NoResize flag on Fn+1.\r\n    // FIXME-TABLE: Find a way to rewrite all of this so interactions feel more consistent for the user.\r\n    // Scenarios:\r\n    // - F1 F2 F3  resize from F1| or F2|   --> ok: alter ->WidthRequested of Fixed column. Subsequent columns will be offset.\r\n    // - F1 F2 F3  resize from F3|          --> ok: alter ->WidthRequested of Fixed column. If active, ScrollX extent can be altered.\r\n    // - F1 F2 W3  resize from F1| or F2|   --> ok: alter ->WidthRequested of Fixed column. If active, ScrollX extent can be altered, but it doesn't make much sense as the Stretch column will always be minimal size.\r\n    // - F1 F2 W3  resize from W3|          --> ok: no-op (disabled by Resize Rule 1)\r\n    // - W1 W2 W3  resize from W1| or W2|   --> ok\r\n    // - W1 W2 W3  resize from W3|          --> ok: no-op (disabled by Resize Rule 1)\r\n    // - W1 F2 F3  resize from F3|          --> ok: no-op (disabled by Resize Rule 1)\r\n    // - W1 F2     resize from F2|          --> ok: no-op (disabled by Resize Rule 1)\r\n    // - W1 W2 F3  resize from W1| or W2|   --> ok\r\n    // - W1 F2 W3  resize from W1| or F2|   --> ok\r\n    // - F1 W2 F3  resize from W2|          --> ok\r\n    // - F1 W3 F2  resize from W3|          --> ok\r\n    // - W1 F2 F3  resize from W1|          --> ok: equivalent to resizing |F2. F3 will not move.\r\n    // - W1 F2 F3  resize from F2|          --> ok\r\n    // All resizes from a Wx columns are locking other columns.\r\n\r\n    // Possible improvements:\r\n    // - W1 W2 W3  resize W1|               --> to not be stuck, both W2 and W3 would stretch down. Seems possible to fix. Would be most beneficial to simplify resize of all-weighted columns.\r\n    // - W3 F1 F2  resize W3|               --> to not be stuck past F1|, both F1 and F2 would need to stretch down, which would be lossy or ambiguous. Seems hard to fix.\r\n\r\n    // [Resize Rule 1] Can't resize from right of right-most visible column if there is any Stretch column. Implemented in TableUpdateLayout().\r\n\r\n    // If we have all Fixed columns OR resizing a Fixed column that doesn't come after a Stretch one, we can do an offsetting resize.\r\n    // This is the preferred resize path\r\n    if (column_0->Flags & ImGuiTableColumnFlags_WidthFixed)\r\n        if (!column_1 || table->LeftMostStretchedColumn == -1 || table->Columns[table->LeftMostStretchedColumn].DisplayOrder >= column_0->DisplayOrder)\r\n        {\r\n            column_0->WidthRequest = column_0_width;\r\n            table->IsSettingsDirty = true;\r\n            return;\r\n        }\r\n\r\n    // We can also use previous column if there's no next one (this is used when doing an auto-fit on the right-most stretch column)\r\n    if (column_1 == NULL)\r\n        column_1 = (column_0->PrevEnabledColumn != -1) ? &table->Columns[column_0->PrevEnabledColumn] : NULL;\r\n    if (column_1 == NULL)\r\n        return;\r\n\r\n    // Resizing from right-side of a Stretch column before a Fixed column forward sizing to left-side of fixed column.\r\n    // (old_a + old_b == new_a + new_b) --> (new_a == old_a + old_b - new_b)\r\n    float column_1_width = ImMax(column_1->WidthRequest - (column_0_width - column_0->WidthRequest), min_width);\r\n    column_0_width = column_0->WidthRequest + column_1->WidthRequest - column_1_width;\r\n    IM_ASSERT(column_0_width > 0.0f && column_1_width > 0.0f);\r\n    column_0->WidthRequest = column_0_width;\r\n    column_1->WidthRequest = column_1_width;\r\n    if ((column_0->Flags | column_1->Flags) & ImGuiTableColumnFlags_WidthStretch)\r\n        TableUpdateColumnsWeightFromWidth(table);\r\n    table->IsSettingsDirty = true;\r\n}\r\n\r\n// Disable clipping then auto-fit, will take 2 frames\r\n// (we don't take a shortcut for unclipped columns to reduce inconsistencies when e.g. resizing multiple columns)\r\nvoid ImGui::TableSetColumnWidthAutoSingle(ImGuiTable* table, int column_n)\r\n{\r\n    // Single auto width uses auto-fit\r\n    ImGuiTableColumn* column = &table->Columns[column_n];\r\n    if (!column->IsEnabled)\r\n        return;\r\n    column->CannotSkipItemsQueue = (1 << 0);\r\n    table->AutoFitSingleColumn = (ImGuiTableColumnIdx)column_n;\r\n}\r\n\r\nvoid ImGui::TableSetColumnWidthAutoAll(ImGuiTable* table)\r\n{\r\n    for (int column_n = 0; column_n < table->ColumnsCount; column_n++)\r\n    {\r\n        ImGuiTableColumn* column = &table->Columns[column_n];\r\n        if (!column->IsEnabled && !(column->Flags & ImGuiTableColumnFlags_WidthStretch)) // Cannot reset weight of hidden stretch column\r\n            continue;\r\n        column->CannotSkipItemsQueue = (1 << 0);\r\n        column->AutoFitQueue = (1 << 1);\r\n    }\r\n}\r\n\r\nvoid ImGui::TableUpdateColumnsWeightFromWidth(ImGuiTable* table)\r\n{\r\n    IM_ASSERT(table->LeftMostStretchedColumn != -1 && table->RightMostStretchedColumn != -1);\r\n\r\n    // Measure existing quantity\r\n    float visible_weight = 0.0f;\r\n    float visible_width = 0.0f;\r\n    for (int column_n = 0; column_n < table->ColumnsCount; column_n++)\r\n    {\r\n        ImGuiTableColumn* column = &table->Columns[column_n];\r\n        if (!column->IsEnabled || !(column->Flags & ImGuiTableColumnFlags_WidthStretch))\r\n            continue;\r\n        IM_ASSERT(column->StretchWeight > 0.0f);\r\n        visible_weight += column->StretchWeight;\r\n        visible_width += column->WidthRequest;\r\n    }\r\n    IM_ASSERT(visible_weight > 0.0f && visible_width > 0.0f);\r\n\r\n    // Apply new weights\r\n    for (int column_n = 0; column_n < table->ColumnsCount; column_n++)\r\n    {\r\n        ImGuiTableColumn* column = &table->Columns[column_n];\r\n        if (!column->IsEnabled || !(column->Flags & ImGuiTableColumnFlags_WidthStretch))\r\n            continue;\r\n        column->StretchWeight = (column->WidthRequest / visible_width) * visible_weight;\r\n        IM_ASSERT(column->StretchWeight > 0.0f);\r\n    }\r\n}\r\n\r\n//-------------------------------------------------------------------------\r\n// [SECTION] Tables: Drawing\r\n//-------------------------------------------------------------------------\r\n// - TablePushBackgroundChannel() [Internal]\r\n// - TablePopBackgroundChannel() [Internal]\r\n// - TableSetupDrawChannels() [Internal]\r\n// - TableMergeDrawChannels() [Internal]\r\n// - TableDrawBorders() [Internal]\r\n//-------------------------------------------------------------------------\r\n\r\n// Bg2 is used by Selectable (and possibly other widgets) to render to the background.\r\n// Unlike our Bg0/1 channel which we uses for RowBg/CellBg/Borders and where we guarantee all shapes to be CPU-clipped, the Bg2 channel being widgets-facing will rely on regular ClipRect.\r\nvoid ImGui::TablePushBackgroundChannel()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    ImGuiTable* table = g.CurrentTable;\r\n\r\n    // Optimization: avoid SetCurrentChannel() + PushClipRect()\r\n    table->HostBackupInnerClipRect = window->ClipRect;\r\n    SetWindowClipRectBeforeSetChannel(window, table->Bg2ClipRectForDrawCmd);\r\n    table->DrawSplitter->SetCurrentChannel(window->DrawList, table->Bg2DrawChannelCurrent);\r\n}\r\n\r\nvoid ImGui::TablePopBackgroundChannel()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    ImGuiTable* table = g.CurrentTable;\r\n    ImGuiTableColumn* column = &table->Columns[table->CurrentColumn];\r\n\r\n    // Optimization: avoid PopClipRect() + SetCurrentChannel()\r\n    SetWindowClipRectBeforeSetChannel(window, table->HostBackupInnerClipRect);\r\n    table->DrawSplitter->SetCurrentChannel(window->DrawList, column->DrawChannelCurrent);\r\n}\r\n\r\n// Allocate draw channels. Called by TableUpdateLayout()\r\n// - We allocate them following storage order instead of display order so reordering columns won't needlessly\r\n//   increase overall dormant memory cost.\r\n// - We isolate headers draw commands in their own channels instead of just altering clip rects.\r\n//   This is in order to facilitate merging of draw commands.\r\n// - After crossing FreezeRowsCount, all columns see their current draw channel changed to a second set of channels.\r\n// - We only use the dummy draw channel so we can push a null clipping rectangle into it without affecting other\r\n//   channels, while simplifying per-row/per-cell overhead. It will be empty and discarded when merged.\r\n// - We allocate 1 or 2 background draw channels. This is because we know TablePushBackgroundChannel() is only used for\r\n//   horizontal spanning. If we allowed vertical spanning we'd need one background draw channel per merge group (1-4).\r\n// Draw channel allocation (before merging):\r\n// - NoClip                       --> 2+D+1 channels: bg0/1 + bg2 + foreground (same clip rect == always 1 draw call)\r\n// - Clip                         --> 2+D+N channels\r\n// - FreezeRows                   --> 2+D+N*2 (unless scrolling value is zero)\r\n// - FreezeRows || FreezeColunns  --> 3+D+N*2 (unless scrolling value is zero)\r\n// Where D is 1 if any column is clipped or hidden (dummy channel) otherwise 0.\r\nvoid ImGui::TableSetupDrawChannels(ImGuiTable* table)\r\n{\r\n    const int freeze_row_multiplier = (table->FreezeRowsCount > 0) ? 2 : 1;\r\n    const int channels_for_row = (table->Flags & ImGuiTableFlags_NoClip) ? 1 : table->ColumnsEnabledCount;\r\n    const int channels_for_bg = 1 + 1 * freeze_row_multiplier;\r\n    const int channels_for_dummy = (table->ColumnsEnabledCount < table->ColumnsCount || table->VisibleMaskByIndex != table->EnabledMaskByIndex) ? +1 : 0;\r\n    const int channels_total = channels_for_bg + (channels_for_row * freeze_row_multiplier) + channels_for_dummy;\r\n    table->DrawSplitter->Split(table->InnerWindow->DrawList, channels_total);\r\n    table->DummyDrawChannel = (ImGuiTableDrawChannelIdx)((channels_for_dummy > 0) ? channels_total - 1 : -1);\r\n    table->Bg2DrawChannelCurrent = TABLE_DRAW_CHANNEL_BG2_FROZEN;\r\n    table->Bg2DrawChannelUnfrozen = (ImGuiTableDrawChannelIdx)((table->FreezeRowsCount > 0) ? 2 + channels_for_row : TABLE_DRAW_CHANNEL_BG2_FROZEN);\r\n\r\n    int draw_channel_current = 2;\r\n    for (int column_n = 0; column_n < table->ColumnsCount; column_n++)\r\n    {\r\n        ImGuiTableColumn* column = &table->Columns[column_n];\r\n        if (column->IsVisibleX && column->IsVisibleY)\r\n        {\r\n            column->DrawChannelFrozen = (ImGuiTableDrawChannelIdx)(draw_channel_current);\r\n            column->DrawChannelUnfrozen = (ImGuiTableDrawChannelIdx)(draw_channel_current + (table->FreezeRowsCount > 0 ? channels_for_row + 1 : 0));\r\n            if (!(table->Flags & ImGuiTableFlags_NoClip))\r\n                draw_channel_current++;\r\n        }\r\n        else\r\n        {\r\n            column->DrawChannelFrozen = column->DrawChannelUnfrozen = table->DummyDrawChannel;\r\n        }\r\n        column->DrawChannelCurrent = column->DrawChannelFrozen;\r\n    }\r\n\r\n    // Initial draw cmd starts with a BgClipRect that matches the one of its host, to facilitate merge draw commands by default.\r\n    // All our cell highlight are manually clipped with BgClipRect. When unfreezing it will be made smaller to fit scrolling rect.\r\n    // (This technically isn't part of setting up draw channels, but is reasonably related to be done here)\r\n    table->BgClipRect = table->InnerClipRect;\r\n    table->Bg0ClipRectForDrawCmd = table->OuterWindow->ClipRect;\r\n    table->Bg2ClipRectForDrawCmd = table->HostClipRect;\r\n    IM_ASSERT(table->BgClipRect.Min.y <= table->BgClipRect.Max.y);\r\n}\r\n\r\n// This function reorder draw channels based on matching clip rectangle, to facilitate merging them. Called by EndTable().\r\n// For simplicity we call it TableMergeDrawChannels() but in fact it only reorder channels + overwrite ClipRect,\r\n// actual merging is done by table->DrawSplitter.Merge() which is called right after TableMergeDrawChannels().\r\n//\r\n// Columns where the contents didn't stray off their local clip rectangle can be merged. To achieve\r\n// this we merge their clip rect and make them contiguous in the channel list, so they can be merged\r\n// by the call to DrawSplitter.Merge() following to the call to this function.\r\n// We reorder draw commands by arranging them into a maximum of 4 distinct groups:\r\n//\r\n//   1 group:               2 groups:              2 groups:              4 groups:\r\n//   [ 0. ] no freeze       [ 0. ] row freeze      [ 01 ] col freeze      [ 01 ] row+col freeze\r\n//   [ .. ]  or no scroll   [ 2. ]  and v-scroll   [ .. ]  and h-scroll   [ 23 ]  and v+h-scroll\r\n//\r\n// Each column itself can use 1 channel (row freeze disabled) or 2 channels (row freeze enabled).\r\n// When the contents of a column didn't stray off its limit, we move its channels into the corresponding group\r\n// based on its position (within frozen rows/columns groups or not).\r\n// At the end of the operation our 1-4 groups will each have a ImDrawCmd using the same ClipRect.\r\n// This function assume that each column are pointing to a distinct draw channel,\r\n// otherwise merge_group->ChannelsCount will not match set bit count of merge_group->ChannelsMask.\r\n//\r\n// Column channels will not be merged into one of the 1-4 groups in the following cases:\r\n// - The contents stray off its clipping rectangle (we only compare the MaxX value, not the MinX value).\r\n//   Direct ImDrawList calls won't be taken into account by default, if you use them make sure the ImGui:: bounds\r\n//   matches, by e.g. calling SetCursorScreenPos().\r\n// - The channel uses more than one draw command itself. We drop all our attempt at merging stuff here..\r\n//   we could do better but it's going to be rare and probably not worth the hassle.\r\n// Columns for which the draw channel(s) haven't been merged with other will use their own ImDrawCmd.\r\n//\r\n// This function is particularly tricky to understand.. take a breath.\r\nvoid ImGui::TableMergeDrawChannels(ImGuiTable* table)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImDrawListSplitter* splitter = table->DrawSplitter;\r\n    const bool has_freeze_v = (table->FreezeRowsCount > 0);\r\n    const bool has_freeze_h = (table->FreezeColumnsCount > 0);\r\n    IM_ASSERT(splitter->_Current == 0);\r\n\r\n    // Track which groups we are going to attempt to merge, and which channels goes into each group.\r\n    struct MergeGroup\r\n    {\r\n        ImRect  ClipRect;\r\n        int     ChannelsCount;\r\n        ImBitArray<IMGUI_TABLE_MAX_DRAW_CHANNELS> ChannelsMask;\r\n\r\n        MergeGroup() { ChannelsCount = 0; }\r\n    };\r\n    int merge_group_mask = 0x00;\r\n    MergeGroup merge_groups[4];\r\n\r\n    // 1. Scan channels and take note of those which can be merged\r\n    for (int column_n = 0; column_n < table->ColumnsCount; column_n++)\r\n    {\r\n        if ((table->VisibleMaskByIndex & ((ImU64)1 << column_n)) == 0)\r\n            continue;\r\n        ImGuiTableColumn* column = &table->Columns[column_n];\r\n\r\n        const int merge_group_sub_count = has_freeze_v ? 2 : 1;\r\n        for (int merge_group_sub_n = 0; merge_group_sub_n < merge_group_sub_count; merge_group_sub_n++)\r\n        {\r\n            const int channel_no = (merge_group_sub_n == 0) ? column->DrawChannelFrozen : column->DrawChannelUnfrozen;\r\n\r\n            // Don't attempt to merge if there are multiple draw calls within the column\r\n            ImDrawChannel* src_channel = &splitter->_Channels[channel_no];\r\n            if (src_channel->_CmdBuffer.Size > 0 && src_channel->_CmdBuffer.back().ElemCount == 0 && src_channel->_CmdBuffer.back().UserCallback != NULL) // Equivalent of PopUnusedDrawCmd()\r\n                src_channel->_CmdBuffer.pop_back();\r\n            if (src_channel->_CmdBuffer.Size != 1)\r\n                continue;\r\n\r\n            // Find out the width of this merge group and check if it will fit in our column\r\n            // (note that we assume that rendering didn't stray on the left direction. we should need a CursorMinPos to detect it)\r\n            if (!(column->Flags & ImGuiTableColumnFlags_NoClip))\r\n            {\r\n                float content_max_x;\r\n                if (!has_freeze_v)\r\n                    content_max_x = ImMax(column->ContentMaxXUnfrozen, column->ContentMaxXHeadersUsed); // No row freeze\r\n                else if (merge_group_sub_n == 0)\r\n                    content_max_x = ImMax(column->ContentMaxXFrozen, column->ContentMaxXHeadersUsed);   // Row freeze: use width before freeze\r\n                else\r\n                    content_max_x = column->ContentMaxXUnfrozen;                                        // Row freeze: use width after freeze\r\n                if (content_max_x > column->ClipRect.Max.x)\r\n                    continue;\r\n            }\r\n\r\n            const int merge_group_n = (has_freeze_h && column_n < table->FreezeColumnsCount ? 0 : 1) + (has_freeze_v && merge_group_sub_n == 0 ? 0 : 2);\r\n            IM_ASSERT(channel_no < IMGUI_TABLE_MAX_DRAW_CHANNELS);\r\n            MergeGroup* merge_group = &merge_groups[merge_group_n];\r\n            if (merge_group->ChannelsCount == 0)\r\n                merge_group->ClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);\r\n            merge_group->ChannelsMask.SetBit(channel_no);\r\n            merge_group->ChannelsCount++;\r\n            merge_group->ClipRect.Add(src_channel->_CmdBuffer[0].ClipRect);\r\n            merge_group_mask |= (1 << merge_group_n);\r\n        }\r\n\r\n        // Invalidate current draw channel\r\n        // (we don't clear DrawChannelFrozen/DrawChannelUnfrozen solely to facilitate debugging/later inspection of data)\r\n        column->DrawChannelCurrent = (ImGuiTableDrawChannelIdx)-1;\r\n    }\r\n\r\n    // [DEBUG] Display merge groups\r\n#if 0\r\n    if (g.IO.KeyShift)\r\n        for (int merge_group_n = 0; merge_group_n < IM_ARRAYSIZE(merge_groups); merge_group_n++)\r\n        {\r\n            MergeGroup* merge_group = &merge_groups[merge_group_n];\r\n            if (merge_group->ChannelsCount == 0)\r\n                continue;\r\n            char buf[32];\r\n            ImFormatString(buf, 32, \"MG%d:%d\", merge_group_n, merge_group->ChannelsCount);\r\n            ImVec2 text_pos = merge_group->ClipRect.Min + ImVec2(4, 4);\r\n            ImVec2 text_size = CalcTextSize(buf, NULL);\r\n            GetForegroundDrawList()->AddRectFilled(text_pos, text_pos + text_size, IM_COL32(0, 0, 0, 255));\r\n            GetForegroundDrawList()->AddText(text_pos, IM_COL32(255, 255, 0, 255), buf, NULL);\r\n            GetForegroundDrawList()->AddRect(merge_group->ClipRect.Min, merge_group->ClipRect.Max, IM_COL32(255, 255, 0, 255));\r\n        }\r\n#endif\r\n\r\n    // 2. Rewrite channel list in our preferred order\r\n    if (merge_group_mask != 0)\r\n    {\r\n        // We skip channel 0 (Bg0/Bg1) and 1 (Bg2 frozen) from the shuffling since they won't move - see channels allocation in TableSetupDrawChannels().\r\n        const int LEADING_DRAW_CHANNELS = 2;\r\n        g.DrawChannelsTempMergeBuffer.resize(splitter->_Count - LEADING_DRAW_CHANNELS); // Use shared temporary storage so the allocation gets amortized\r\n        ImDrawChannel* dst_tmp = g.DrawChannelsTempMergeBuffer.Data;\r\n        ImBitArray<IMGUI_TABLE_MAX_DRAW_CHANNELS> remaining_mask;                       // We need 132-bit of storage\r\n        remaining_mask.SetBitRange(LEADING_DRAW_CHANNELS, splitter->_Count);\r\n        remaining_mask.ClearBit(table->Bg2DrawChannelUnfrozen);\r\n        IM_ASSERT(has_freeze_v == false || table->Bg2DrawChannelUnfrozen != TABLE_DRAW_CHANNEL_BG2_FROZEN);\r\n        int remaining_count = splitter->_Count - (has_freeze_v ? LEADING_DRAW_CHANNELS + 1 : LEADING_DRAW_CHANNELS);\r\n        //ImRect host_rect = (table->InnerWindow == table->OuterWindow) ? table->InnerClipRect : table->HostClipRect;\r\n        ImRect host_rect = table->HostClipRect;\r\n        for (int merge_group_n = 0; merge_group_n < IM_ARRAYSIZE(merge_groups); merge_group_n++)\r\n        {\r\n            if (int merge_channels_count = merge_groups[merge_group_n].ChannelsCount)\r\n            {\r\n                MergeGroup* merge_group = &merge_groups[merge_group_n];\r\n                ImRect merge_clip_rect = merge_group->ClipRect;\r\n\r\n                // Extend outer-most clip limits to match those of host, so draw calls can be merged even if\r\n                // outer-most columns have some outer padding offsetting them from their parent ClipRect.\r\n                // The principal cases this is dealing with are:\r\n                // - On a same-window table (not scrolling = single group), all fitting columns ClipRect -> will extend and match host ClipRect -> will merge\r\n                // - Columns can use padding and have left-most ClipRect.Min.x and right-most ClipRect.Max.x != from host ClipRect -> will extend and match host ClipRect -> will merge\r\n                // FIXME-TABLE FIXME-WORKRECT: We are wasting a merge opportunity on tables without scrolling if column doesn't fit\r\n                // within host clip rect, solely because of the half-padding difference between window->WorkRect and window->InnerClipRect.\r\n                if ((merge_group_n & 1) == 0 || !has_freeze_h)\r\n                    merge_clip_rect.Min.x = ImMin(merge_clip_rect.Min.x, host_rect.Min.x);\r\n                if ((merge_group_n & 2) == 0 || !has_freeze_v)\r\n                    merge_clip_rect.Min.y = ImMin(merge_clip_rect.Min.y, host_rect.Min.y);\r\n                if ((merge_group_n & 1) != 0)\r\n                    merge_clip_rect.Max.x = ImMax(merge_clip_rect.Max.x, host_rect.Max.x);\r\n                if ((merge_group_n & 2) != 0 && (table->Flags & ImGuiTableFlags_NoHostExtendY) == 0)\r\n                    merge_clip_rect.Max.y = ImMax(merge_clip_rect.Max.y, host_rect.Max.y);\r\n#if 0\r\n                GetOverlayDrawList()->AddRect(merge_group->ClipRect.Min, merge_group->ClipRect.Max, IM_COL32(255, 0, 0, 200), 0.0f, 0, 1.0f);\r\n                GetOverlayDrawList()->AddLine(merge_group->ClipRect.Min, merge_clip_rect.Min, IM_COL32(255, 100, 0, 200));\r\n                GetOverlayDrawList()->AddLine(merge_group->ClipRect.Max, merge_clip_rect.Max, IM_COL32(255, 100, 0, 200));\r\n#endif\r\n                remaining_count -= merge_group->ChannelsCount;\r\n                for (int n = 0; n < IM_ARRAYSIZE(remaining_mask.Storage); n++)\r\n                    remaining_mask.Storage[n] &= ~merge_group->ChannelsMask.Storage[n];\r\n                for (int n = 0; n < splitter->_Count && merge_channels_count != 0; n++)\r\n                {\r\n                    // Copy + overwrite new clip rect\r\n                    if (!merge_group->ChannelsMask.TestBit(n))\r\n                        continue;\r\n                    merge_group->ChannelsMask.ClearBit(n);\r\n                    merge_channels_count--;\r\n\r\n                    ImDrawChannel* channel = &splitter->_Channels[n];\r\n                    IM_ASSERT(channel->_CmdBuffer.Size == 1 && merge_clip_rect.Contains(ImRect(channel->_CmdBuffer[0].ClipRect)));\r\n                    channel->_CmdBuffer[0].ClipRect = merge_clip_rect.ToVec4();\r\n                    memcpy(dst_tmp++, channel, sizeof(ImDrawChannel));\r\n                }\r\n            }\r\n\r\n            // Make sure Bg2DrawChannelUnfrozen appears in the middle of our groups (whereas Bg0/Bg1 and Bg2 frozen are fixed to 0 and 1)\r\n            if (merge_group_n == 1 && has_freeze_v)\r\n                memcpy(dst_tmp++, &splitter->_Channels[table->Bg2DrawChannelUnfrozen], sizeof(ImDrawChannel));\r\n        }\r\n\r\n        // Append unmergeable channels that we didn't reorder at the end of the list\r\n        for (int n = 0; n < splitter->_Count && remaining_count != 0; n++)\r\n        {\r\n            if (!remaining_mask.TestBit(n))\r\n                continue;\r\n            ImDrawChannel* channel = &splitter->_Channels[n];\r\n            memcpy(dst_tmp++, channel, sizeof(ImDrawChannel));\r\n            remaining_count--;\r\n        }\r\n        IM_ASSERT(dst_tmp == g.DrawChannelsTempMergeBuffer.Data + g.DrawChannelsTempMergeBuffer.Size);\r\n        memcpy(splitter->_Channels.Data + LEADING_DRAW_CHANNELS, g.DrawChannelsTempMergeBuffer.Data, (splitter->_Count - LEADING_DRAW_CHANNELS) * sizeof(ImDrawChannel));\r\n    }\r\n}\r\n\r\n// FIXME-TABLE: This is a mess, need to redesign how we render borders (as some are also done in TableEndRow)\r\nvoid ImGui::TableDrawBorders(ImGuiTable* table)\r\n{\r\n    ImGuiWindow* inner_window = table->InnerWindow;\r\n    if (!table->OuterWindow->ClipRect.Overlaps(table->OuterRect))\r\n        return;\r\n\r\n    ImDrawList* inner_drawlist = inner_window->DrawList;\r\n    table->DrawSplitter->SetCurrentChannel(inner_drawlist, TABLE_DRAW_CHANNEL_BG0);\r\n    inner_drawlist->PushClipRect(table->Bg0ClipRectForDrawCmd.Min, table->Bg0ClipRectForDrawCmd.Max, false);\r\n\r\n    // Draw inner border and resizing feedback\r\n    const float border_size = TABLE_BORDER_SIZE;\r\n    const float draw_y1 = table->InnerRect.Min.y;\r\n    const float draw_y2_body = table->InnerRect.Max.y;\r\n    const float draw_y2_head = table->IsUsingHeaders ? ImMin(table->InnerRect.Max.y, (table->FreezeRowsCount >= 1 ? table->InnerRect.Min.y : table->WorkRect.Min.y) + table->LastFirstRowHeight) : draw_y1;\r\n    if (table->Flags & ImGuiTableFlags_BordersInnerV)\r\n    {\r\n        for (int order_n = 0; order_n < table->ColumnsCount; order_n++)\r\n        {\r\n            if (!(table->EnabledMaskByDisplayOrder & ((ImU64)1 << order_n)))\r\n                continue;\r\n\r\n            const int column_n = table->DisplayOrderToIndex[order_n];\r\n            ImGuiTableColumn* column = &table->Columns[column_n];\r\n            const bool is_hovered = (table->HoveredColumnBorder == column_n);\r\n            const bool is_resized = (table->ResizedColumn == column_n) && (table->InstanceInteracted == table->InstanceCurrent);\r\n            const bool is_resizable = (column->Flags & (ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_NoDirectResize_)) == 0;\r\n            const bool is_frozen_separator = (table->FreezeColumnsCount == order_n + 1);\r\n            if (column->MaxX > table->InnerClipRect.Max.x && !is_resized)\r\n                continue;\r\n\r\n            // Decide whether right-most column is visible\r\n            if (column->NextEnabledColumn == -1 && !is_resizable)\r\n                if ((table->Flags & ImGuiTableFlags_SizingMask_) != ImGuiTableFlags_SizingFixedSame || (table->Flags & ImGuiTableFlags_NoHostExtendX))\r\n                    continue;\r\n            if (column->MaxX <= column->ClipRect.Min.x) // FIXME-TABLE FIXME-STYLE: Assume BorderSize==1, this is problematic if we want to increase the border size..\r\n                continue;\r\n\r\n            // Draw in outer window so right-most column won't be clipped\r\n            // Always draw full height border when being resized/hovered, or on the delimitation of frozen column scrolling.\r\n            ImU32 col;\r\n            float draw_y2;\r\n            if (is_hovered || is_resized || is_frozen_separator)\r\n            {\r\n                draw_y2 = draw_y2_body;\r\n                col = is_resized ? GetColorU32(ImGuiCol_SeparatorActive) : is_hovered ? GetColorU32(ImGuiCol_SeparatorHovered) : table->BorderColorStrong;\r\n            }\r\n            else\r\n            {\r\n                draw_y2 = (table->Flags & (ImGuiTableFlags_NoBordersInBody | ImGuiTableFlags_NoBordersInBodyUntilResize)) ? draw_y2_head : draw_y2_body;\r\n                col = (table->Flags & (ImGuiTableFlags_NoBordersInBody | ImGuiTableFlags_NoBordersInBodyUntilResize)) ? table->BorderColorStrong : table->BorderColorLight;\r\n            }\r\n\r\n            if (draw_y2 > draw_y1)\r\n                inner_drawlist->AddLine(ImVec2(column->MaxX, draw_y1), ImVec2(column->MaxX, draw_y2), col, border_size);\r\n        }\r\n    }\r\n\r\n    // Draw outer border\r\n    // FIXME: could use AddRect or explicit VLine/HLine helper?\r\n    if (table->Flags & ImGuiTableFlags_BordersOuter)\r\n    {\r\n        // Display outer border offset by 1 which is a simple way to display it without adding an extra draw call\r\n        // (Without the offset, in outer_window it would be rendered behind cells, because child windows are above their\r\n        // parent. In inner_window, it won't reach out over scrollbars. Another weird solution would be to display part\r\n        // of it in inner window, and the part that's over scrollbars in the outer window..)\r\n        // Either solution currently won't allow us to use a larger border size: the border would clipped.\r\n        const ImRect outer_border = table->OuterRect;\r\n        const ImU32 outer_col = table->BorderColorStrong;\r\n        if ((table->Flags & ImGuiTableFlags_BordersOuter) == ImGuiTableFlags_BordersOuter)\r\n        {\r\n            inner_drawlist->AddRect(outer_border.Min, outer_border.Max, outer_col, 0.0f, 0, border_size);\r\n        }\r\n        else if (table->Flags & ImGuiTableFlags_BordersOuterV)\r\n        {\r\n            inner_drawlist->AddLine(outer_border.Min, ImVec2(outer_border.Min.x, outer_border.Max.y), outer_col, border_size);\r\n            inner_drawlist->AddLine(ImVec2(outer_border.Max.x, outer_border.Min.y), outer_border.Max, outer_col, border_size);\r\n        }\r\n        else if (table->Flags & ImGuiTableFlags_BordersOuterH)\r\n        {\r\n            inner_drawlist->AddLine(outer_border.Min, ImVec2(outer_border.Max.x, outer_border.Min.y), outer_col, border_size);\r\n            inner_drawlist->AddLine(ImVec2(outer_border.Min.x, outer_border.Max.y), outer_border.Max, outer_col, border_size);\r\n        }\r\n    }\r\n    if ((table->Flags & ImGuiTableFlags_BordersInnerH) && table->RowPosY2 < table->OuterRect.Max.y)\r\n    {\r\n        // Draw bottom-most row border\r\n        const float border_y = table->RowPosY2;\r\n        if (border_y >= table->BgClipRect.Min.y && border_y < table->BgClipRect.Max.y)\r\n            inner_drawlist->AddLine(ImVec2(table->BorderX1, border_y), ImVec2(table->BorderX2, border_y), table->BorderColorLight, border_size);\r\n    }\r\n\r\n    inner_drawlist->PopClipRect();\r\n}\r\n\r\n//-------------------------------------------------------------------------\r\n// [SECTION] Tables: Sorting\r\n//-------------------------------------------------------------------------\r\n// - TableGetSortSpecs()\r\n// - TableFixColumnSortDirection() [Internal]\r\n// - TableGetColumnNextSortDirection() [Internal]\r\n// - TableSetColumnSortDirection() [Internal]\r\n// - TableSortSpecsSanitize() [Internal]\r\n// - TableSortSpecsBuild() [Internal]\r\n//-------------------------------------------------------------------------\r\n\r\n// Return NULL if no sort specs (most often when ImGuiTableFlags_Sortable is not set)\r\n// You can sort your data again when 'SpecsChanged == true'. It will be true with sorting specs have changed since\r\n// last call, or the first time.\r\n// Lifetime: don't hold on this pointer over multiple frames or past any subsequent call to BeginTable()!\r\nImGuiTableSortSpecs* ImGui::TableGetSortSpecs()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiTable* table = g.CurrentTable;\r\n    IM_ASSERT(table != NULL);\r\n\r\n    if (!(table->Flags & ImGuiTableFlags_Sortable))\r\n        return NULL;\r\n\r\n    // Require layout (in case TableHeadersRow() hasn't been called) as it may alter IsSortSpecsDirty in some paths.\r\n    if (!table->IsLayoutLocked)\r\n        TableUpdateLayout(table);\r\n\r\n    TableSortSpecsBuild(table);\r\n\r\n    return &table->SortSpecs;\r\n}\r\n\r\nstatic inline ImGuiSortDirection TableGetColumnAvailSortDirection(ImGuiTableColumn* column, int n)\r\n{\r\n    IM_ASSERT(n < column->SortDirectionsAvailCount);\r\n    return (column->SortDirectionsAvailList >> (n << 1)) & 0x03;\r\n}\r\n\r\n// Fix sort direction if currently set on a value which is unavailable (e.g. activating NoSortAscending/NoSortDescending)\r\nvoid ImGui::TableFixColumnSortDirection(ImGuiTable* table, ImGuiTableColumn* column)\r\n{\r\n    if (column->SortOrder == -1 || (column->SortDirectionsAvailMask & (1 << column->SortDirection)) != 0)\r\n        return;\r\n    column->SortDirection = (ImU8)TableGetColumnAvailSortDirection(column, 0);\r\n    table->IsSortSpecsDirty = true;\r\n}\r\n\r\n// Calculate next sort direction that would be set after clicking the column\r\n// - If the PreferSortDescending flag is set, we will default to a Descending direction on the first click.\r\n// - Note that the PreferSortAscending flag is never checked, it is essentially the default and therefore a no-op.\r\nIM_STATIC_ASSERT(ImGuiSortDirection_None == 0 && ImGuiSortDirection_Ascending == 1 && ImGuiSortDirection_Descending == 2);\r\nImGuiSortDirection ImGui::TableGetColumnNextSortDirection(ImGuiTableColumn* column)\r\n{\r\n    IM_ASSERT(column->SortDirectionsAvailCount > 0);\r\n    if (column->SortOrder == -1)\r\n        return TableGetColumnAvailSortDirection(column, 0);\r\n    for (int n = 0; n < 3; n++)\r\n        if (column->SortDirection == TableGetColumnAvailSortDirection(column, n))\r\n            return TableGetColumnAvailSortDirection(column, (n + 1) % column->SortDirectionsAvailCount);\r\n    IM_ASSERT(0);\r\n    return ImGuiSortDirection_None;\r\n}\r\n\r\n// Note that the NoSortAscending/NoSortDescending flags are processed in TableSortSpecsSanitize(), and they may change/revert\r\n// the value of SortDirection. We could technically also do it here but it would be unnecessary and duplicate code.\r\nvoid ImGui::TableSetColumnSortDirection(int column_n, ImGuiSortDirection sort_direction, bool append_to_sort_specs)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiTable* table = g.CurrentTable;\r\n\r\n    if (!(table->Flags & ImGuiTableFlags_SortMulti))\r\n        append_to_sort_specs = false;\r\n    if (!(table->Flags & ImGuiTableFlags_SortTristate))\r\n        IM_ASSERT(sort_direction != ImGuiSortDirection_None);\r\n\r\n    ImGuiTableColumnIdx sort_order_max = 0;\r\n    if (append_to_sort_specs)\r\n        for (int other_column_n = 0; other_column_n < table->ColumnsCount; other_column_n++)\r\n            sort_order_max = ImMax(sort_order_max, table->Columns[other_column_n].SortOrder);\r\n\r\n    ImGuiTableColumn* column = &table->Columns[column_n];\r\n    column->SortDirection = (ImU8)sort_direction;\r\n    if (column->SortDirection == ImGuiSortDirection_None)\r\n        column->SortOrder = -1;\r\n    else if (column->SortOrder == -1 || !append_to_sort_specs)\r\n        column->SortOrder = append_to_sort_specs ? sort_order_max + 1 : 0;\r\n\r\n    for (int other_column_n = 0; other_column_n < table->ColumnsCount; other_column_n++)\r\n    {\r\n        ImGuiTableColumn* other_column = &table->Columns[other_column_n];\r\n        if (other_column != column && !append_to_sort_specs)\r\n            other_column->SortOrder = -1;\r\n        TableFixColumnSortDirection(table, other_column);\r\n    }\r\n    table->IsSettingsDirty = true;\r\n    table->IsSortSpecsDirty = true;\r\n}\r\n\r\nvoid ImGui::TableSortSpecsSanitize(ImGuiTable* table)\r\n{\r\n    IM_ASSERT(table->Flags & ImGuiTableFlags_Sortable);\r\n\r\n    // Clear SortOrder from hidden column and verify that there's no gap or duplicate.\r\n    int sort_order_count = 0;\r\n    ImU64 sort_order_mask = 0x00;\r\n    for (int column_n = 0; column_n < table->ColumnsCount; column_n++)\r\n    {\r\n        ImGuiTableColumn* column = &table->Columns[column_n];\r\n        if (column->SortOrder != -1 && !column->IsEnabled)\r\n            column->SortOrder = -1;\r\n        if (column->SortOrder == -1)\r\n            continue;\r\n        sort_order_count++;\r\n        sort_order_mask |= ((ImU64)1 << column->SortOrder);\r\n        IM_ASSERT(sort_order_count < (int)sizeof(sort_order_mask) * 8);\r\n    }\r\n\r\n    const bool need_fix_linearize = ((ImU64)1 << sort_order_count) != (sort_order_mask + 1);\r\n    const bool need_fix_single_sort_order = (sort_order_count > 1) && !(table->Flags & ImGuiTableFlags_SortMulti);\r\n    if (need_fix_linearize || need_fix_single_sort_order)\r\n    {\r\n        ImU64 fixed_mask = 0x00;\r\n        for (int sort_n = 0; sort_n < sort_order_count; sort_n++)\r\n        {\r\n            // Fix: Rewrite sort order fields if needed so they have no gap or duplicate.\r\n            // (e.g. SortOrder 0 disappeared, SortOrder 1..2 exists --> rewrite then as SortOrder 0..1)\r\n            int column_with_smallest_sort_order = -1;\r\n            for (int column_n = 0; column_n < table->ColumnsCount; column_n++)\r\n                if ((fixed_mask & ((ImU64)1 << (ImU64)column_n)) == 0 && table->Columns[column_n].SortOrder != -1)\r\n                    if (column_with_smallest_sort_order == -1 || table->Columns[column_n].SortOrder < table->Columns[column_with_smallest_sort_order].SortOrder)\r\n                        column_with_smallest_sort_order = column_n;\r\n            IM_ASSERT(column_with_smallest_sort_order != -1);\r\n            fixed_mask |= ((ImU64)1 << column_with_smallest_sort_order);\r\n            table->Columns[column_with_smallest_sort_order].SortOrder = (ImGuiTableColumnIdx)sort_n;\r\n\r\n            // Fix: Make sure only one column has a SortOrder if ImGuiTableFlags_MultiSortable is not set.\r\n            if (need_fix_single_sort_order)\r\n            {\r\n                sort_order_count = 1;\r\n                for (int column_n = 0; column_n < table->ColumnsCount; column_n++)\r\n                    if (column_n != column_with_smallest_sort_order)\r\n                        table->Columns[column_n].SortOrder = -1;\r\n                break;\r\n            }\r\n        }\r\n    }\r\n\r\n    // Fallback default sort order (if no column had the ImGuiTableColumnFlags_DefaultSort flag)\r\n    if (sort_order_count == 0 && !(table->Flags & ImGuiTableFlags_SortTristate))\r\n        for (int column_n = 0; column_n < table->ColumnsCount; column_n++)\r\n        {\r\n            ImGuiTableColumn* column = &table->Columns[column_n];\r\n            if (column->IsEnabled && !(column->Flags & ImGuiTableColumnFlags_NoSort))\r\n            {\r\n                sort_order_count = 1;\r\n                column->SortOrder = 0;\r\n                column->SortDirection = (ImU8)TableGetColumnAvailSortDirection(column, 0);\r\n                break;\r\n            }\r\n        }\r\n\r\n    table->SortSpecsCount = (ImGuiTableColumnIdx)sort_order_count;\r\n}\r\n\r\nvoid ImGui::TableSortSpecsBuild(ImGuiTable* table)\r\n{\r\n    bool dirty = table->IsSortSpecsDirty;\r\n    if (dirty)\r\n    {\r\n        TableSortSpecsSanitize(table);\r\n        table->SortSpecsMulti.resize(table->SortSpecsCount <= 1 ? 0 : table->SortSpecsCount);\r\n        table->SortSpecs.SpecsDirty = true; // Mark as dirty for user\r\n        table->IsSortSpecsDirty = false; // Mark as not dirty for us\r\n    }\r\n\r\n    // Write output\r\n    ImGuiTableColumnSortSpecs* sort_specs = (table->SortSpecsCount == 0) ? NULL : (table->SortSpecsCount == 1) ? &table->SortSpecsSingle : table->SortSpecsMulti.Data;\r\n    if (dirty && sort_specs != NULL)\r\n        for (int column_n = 0; column_n < table->ColumnsCount; column_n++)\r\n        {\r\n            ImGuiTableColumn* column = &table->Columns[column_n];\r\n            if (column->SortOrder == -1)\r\n                continue;\r\n            IM_ASSERT(column->SortOrder < table->SortSpecsCount);\r\n            ImGuiTableColumnSortSpecs* sort_spec = &sort_specs[column->SortOrder];\r\n            sort_spec->ColumnUserID = column->UserID;\r\n            sort_spec->ColumnIndex = (ImGuiTableColumnIdx)column_n;\r\n            sort_spec->SortOrder = (ImGuiTableColumnIdx)column->SortOrder;\r\n            sort_spec->SortDirection = column->SortDirection;\r\n        }\r\n\r\n    table->SortSpecs.Specs = sort_specs;\r\n    table->SortSpecs.SpecsCount = table->SortSpecsCount;\r\n}\r\n\r\n//-------------------------------------------------------------------------\r\n// [SECTION] Tables: Headers\r\n//-------------------------------------------------------------------------\r\n// - TableGetHeaderRowHeight() [Internal]\r\n// - TableHeadersRow()\r\n// - TableHeader()\r\n//-------------------------------------------------------------------------\r\n\r\nfloat ImGui::TableGetHeaderRowHeight()\r\n{\r\n    // Caring for a minor edge case:\r\n    // Calculate row height, for the unlikely case that some labels may be taller than others.\r\n    // If we didn't do that, uneven header height would highlight but smaller one before the tallest wouldn't catch input for all height.\r\n    // In your custom header row you may omit this all together and just call TableNextRow() without a height...\r\n    float row_height = GetTextLineHeight();\r\n    int columns_count = TableGetColumnCount();\r\n    for (int column_n = 0; column_n < columns_count; column_n++)\r\n    {\r\n        ImGuiTableColumnFlags flags = TableGetColumnFlags(column_n);\r\n        if ((flags & ImGuiTableColumnFlags_IsEnabled) && !(flags & ImGuiTableColumnFlags_NoHeaderLabel))\r\n            row_height = ImMax(row_height, CalcTextSize(TableGetColumnName(column_n)).y);\r\n    }\r\n    row_height += GetStyle().CellPadding.y * 2.0f;\r\n    return row_height;\r\n}\r\n\r\n// [Public] This is a helper to output TableHeader() calls based on the column names declared in TableSetupColumn().\r\n// The intent is that advanced users willing to create customized headers would not need to use this helper\r\n// and can create their own! For example: TableHeader() may be preceeded by Checkbox() or other custom widgets.\r\n// See 'Demo->Tables->Custom headers' for a demonstration of implementing a custom version of this.\r\n// This code is constructed to not make much use of internal functions, as it is intended to be a template to copy.\r\n// FIXME-TABLE: TableOpenContextMenu() and TableGetHeaderRowHeight() are not public.\r\nvoid ImGui::TableHeadersRow()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiTable* table = g.CurrentTable;\r\n    IM_ASSERT(table != NULL && \"Need to call TableHeadersRow() after BeginTable()!\");\r\n\r\n    // Layout if not already done (this is automatically done by TableNextRow, we do it here solely to facilitate stepping in debugger as it is frequent to step in TableUpdateLayout)\r\n    if (!table->IsLayoutLocked)\r\n        TableUpdateLayout(table);\r\n\r\n    // Open row\r\n    const float row_y1 = GetCursorScreenPos().y;\r\n    const float row_height = TableGetHeaderRowHeight();\r\n    TableNextRow(ImGuiTableRowFlags_Headers, row_height);\r\n    if (table->HostSkipItems) // Merely an optimization, you may skip in your own code.\r\n        return;\r\n\r\n    const int columns_count = TableGetColumnCount();\r\n    for (int column_n = 0; column_n < columns_count; column_n++)\r\n    {\r\n        if (!TableSetColumnIndex(column_n))\r\n            continue;\r\n\r\n        // Push an id to allow unnamed labels (generally accidental, but let's behave nicely with them)\r\n        // - in your own code you may omit the PushID/PopID all-together, provided you know they won't collide\r\n        // - table->InstanceCurrent is only >0 when we use multiple BeginTable/EndTable calls with same identifier.\r\n        const char* name = (TableGetColumnFlags(column_n) & ImGuiTableColumnFlags_NoHeaderLabel) ? \"\" : TableGetColumnName(column_n);\r\n        PushID(table->InstanceCurrent * table->ColumnsCount + column_n);\r\n        TableHeader(name);\r\n        PopID();\r\n    }\r\n\r\n    // Allow opening popup from the right-most section after the last column.\r\n    ImVec2 mouse_pos = ImGui::GetMousePos();\r\n    if (IsMouseReleased(1) && TableGetHoveredColumn() == columns_count)\r\n        if (mouse_pos.y >= row_y1 && mouse_pos.y < row_y1 + row_height)\r\n            TableOpenContextMenu(-1); // Will open a non-column-specific popup.\r\n}\r\n\r\n// Emit a column header (text + optional sort order)\r\n// We cpu-clip text here so that all columns headers can be merged into a same draw call.\r\n// Note that because of how we cpu-clip and display sorting indicators, you _cannot_ use SameLine() after a TableHeader()\r\nvoid ImGui::TableHeader(const char* label)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    if (window->SkipItems)\r\n        return;\r\n\r\n    ImGuiTable* table = g.CurrentTable;\r\n    IM_ASSERT(table != NULL && \"Need to call TableHeader() after BeginTable()!\");\r\n    IM_ASSERT(table->CurrentColumn != -1);\r\n    const int column_n = table->CurrentColumn;\r\n    ImGuiTableColumn* column = &table->Columns[column_n];\r\n\r\n    // Label\r\n    if (label == NULL)\r\n        label = \"\";\r\n    const char* label_end = FindRenderedTextEnd(label);\r\n    ImVec2 label_size = CalcTextSize(label, label_end, true);\r\n    ImVec2 label_pos = window->DC.CursorPos;\r\n\r\n    // If we already got a row height, there's use that.\r\n    // FIXME-TABLE: Padding problem if the correct outer-padding CellBgRect strays off our ClipRect?\r\n    ImRect cell_r = TableGetCellBgRect(table, column_n);\r\n    float label_height = ImMax(label_size.y, table->RowMinHeight - table->CellPaddingY * 2.0f);\r\n\r\n    // Calculate ideal size for sort order arrow\r\n    float w_arrow = 0.0f;\r\n    float w_sort_text = 0.0f;\r\n    char sort_order_suf[4] = \"\";\r\n    const float ARROW_SCALE = 0.65f;\r\n    if ((table->Flags & ImGuiTableFlags_Sortable) && !(column->Flags & ImGuiTableColumnFlags_NoSort))\r\n    {\r\n        w_arrow = ImFloor(g.FontSize * ARROW_SCALE + g.Style.FramePadding.x);\r\n        if (column->SortOrder > 0)\r\n        {\r\n            ImFormatString(sort_order_suf, IM_ARRAYSIZE(sort_order_suf), \"%d\", column->SortOrder + 1);\r\n            w_sort_text = g.Style.ItemInnerSpacing.x + CalcTextSize(sort_order_suf).x;\r\n        }\r\n    }\r\n\r\n    // We feed our unclipped width to the column without writing on CursorMaxPos, so that column is still considering for merging.\r\n    float max_pos_x = label_pos.x + label_size.x + w_sort_text + w_arrow;\r\n    column->ContentMaxXHeadersUsed = ImMax(column->ContentMaxXHeadersUsed, column->WorkMaxX);\r\n    column->ContentMaxXHeadersIdeal = ImMax(column->ContentMaxXHeadersIdeal, max_pos_x);\r\n\r\n    // Keep header highlighted when context menu is open.\r\n    const bool selected = (table->IsContextPopupOpen && table->ContextPopupColumn == column_n && table->InstanceInteracted == table->InstanceCurrent);\r\n    ImGuiID id = window->GetID(label);\r\n    ImRect bb(cell_r.Min.x, cell_r.Min.y, cell_r.Max.x, ImMax(cell_r.Max.y, cell_r.Min.y + label_height + g.Style.CellPadding.y * 2.0f));\r\n    ItemSize(ImVec2(0.0f, label_height)); // Don't declare unclipped width, it'll be fed ContentMaxPosHeadersIdeal\r\n    if (!ItemAdd(bb, id))\r\n        return;\r\n\r\n    //GetForegroundDrawList()->AddRect(cell_r.Min, cell_r.Max, IM_COL32(255, 0, 0, 255)); // [DEBUG]\r\n    //GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 0, 0, 255)); // [DEBUG]\r\n\r\n    // Using AllowItemOverlap mode because we cover the whole cell, and we want user to be able to submit subsequent items.\r\n    bool hovered, held;\r\n    bool pressed = ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_AllowItemOverlap);\r\n    if (g.ActiveId != id)\r\n        SetItemAllowOverlap();\r\n    if (held || hovered || selected)\r\n    {\r\n        const ImU32 col = GetColorU32(held ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);\r\n        //RenderFrame(bb.Min, bb.Max, col, false, 0.0f);\r\n        TableSetBgColor(ImGuiTableBgTarget_CellBg, col, table->CurrentColumn);\r\n    }\r\n    else\r\n    {\r\n        // Submit single cell bg color in the case we didn't submit a full header row\r\n        if ((table->RowFlags & ImGuiTableRowFlags_Headers) == 0)\r\n            TableSetBgColor(ImGuiTableBgTarget_CellBg, GetColorU32(ImGuiCol_TableHeaderBg), table->CurrentColumn);\r\n    }\r\n    RenderNavHighlight(bb, id, ImGuiNavHighlightFlags_TypeThin | ImGuiNavHighlightFlags_NoRounding);\r\n    if (held)\r\n        table->HeldHeaderColumn = (ImGuiTableColumnIdx)column_n;\r\n    window->DC.CursorPos.y -= g.Style.ItemSpacing.y * 0.5f;\r\n\r\n    // Drag and drop to re-order columns.\r\n    // FIXME-TABLE: Scroll request while reordering a column and it lands out of the scrolling zone.\r\n    if (held && (table->Flags & ImGuiTableFlags_Reorderable) && IsMouseDragging(0) && !g.DragDropActive)\r\n    {\r\n        // While moving a column it will jump on the other side of the mouse, so we also test for MouseDelta.x\r\n        table->ReorderColumn = (ImGuiTableColumnIdx)column_n;\r\n        table->InstanceInteracted = table->InstanceCurrent;\r\n\r\n        // We don't reorder: through the frozen<>unfrozen line, or through a column that is marked with ImGuiTableColumnFlags_NoReorder.\r\n        if (g.IO.MouseDelta.x < 0.0f && g.IO.MousePos.x < cell_r.Min.x)\r\n            if (ImGuiTableColumn* prev_column = (column->PrevEnabledColumn != -1) ? &table->Columns[column->PrevEnabledColumn] : NULL)\r\n                if (!((column->Flags | prev_column->Flags) & ImGuiTableColumnFlags_NoReorder))\r\n                    if ((column->IndexWithinEnabledSet < table->FreezeColumnsRequest) == (prev_column->IndexWithinEnabledSet < table->FreezeColumnsRequest))\r\n                        table->ReorderColumnDir = -1;\r\n        if (g.IO.MouseDelta.x > 0.0f && g.IO.MousePos.x > cell_r.Max.x)\r\n            if (ImGuiTableColumn* next_column = (column->NextEnabledColumn != -1) ? &table->Columns[column->NextEnabledColumn] : NULL)\r\n                if (!((column->Flags | next_column->Flags) & ImGuiTableColumnFlags_NoReorder))\r\n                    if ((column->IndexWithinEnabledSet < table->FreezeColumnsRequest) == (next_column->IndexWithinEnabledSet < table->FreezeColumnsRequest))\r\n                        table->ReorderColumnDir = +1;\r\n    }\r\n\r\n    // Sort order arrow\r\n    const float ellipsis_max = cell_r.Max.x - w_arrow - w_sort_text;\r\n    if ((table->Flags & ImGuiTableFlags_Sortable) && !(column->Flags & ImGuiTableColumnFlags_NoSort))\r\n    {\r\n        if (column->SortOrder != -1)\r\n        {\r\n            float x = ImMax(cell_r.Min.x, cell_r.Max.x - w_arrow - w_sort_text);\r\n            float y = label_pos.y;\r\n            if (column->SortOrder > 0)\r\n            {\r\n                PushStyleColor(ImGuiCol_Text, GetColorU32(ImGuiCol_Text, 0.70f));\r\n                RenderText(ImVec2(x + g.Style.ItemInnerSpacing.x, y), sort_order_suf);\r\n                PopStyleColor();\r\n                x += w_sort_text;\r\n            }\r\n            RenderArrow(window->DrawList, ImVec2(x, y), GetColorU32(ImGuiCol_Text), column->SortDirection == ImGuiSortDirection_Ascending ? ImGuiDir_Up : ImGuiDir_Down, ARROW_SCALE);\r\n        }\r\n\r\n        // Handle clicking on column header to adjust Sort Order\r\n        if (pressed && table->ReorderColumn != column_n)\r\n        {\r\n            ImGuiSortDirection sort_direction = TableGetColumnNextSortDirection(column);\r\n            TableSetColumnSortDirection(column_n, sort_direction, g.IO.KeyShift);\r\n        }\r\n    }\r\n\r\n    // Render clipped label. Clipping here ensure that in the majority of situations, all our header cells will\r\n    // be merged into a single draw call.\r\n    //window->DrawList->AddCircleFilled(ImVec2(ellipsis_max, label_pos.y), 40, IM_COL32_WHITE);\r\n    RenderTextEllipsis(window->DrawList, label_pos, ImVec2(ellipsis_max, label_pos.y + label_height + g.Style.FramePadding.y), ellipsis_max, ellipsis_max, label, label_end, &label_size);\r\n\r\n    const bool text_clipped = label_size.x > (ellipsis_max - label_pos.x);\r\n    if (text_clipped && hovered && g.HoveredIdNotActiveTimer > g.TooltipSlowDelay)\r\n        SetTooltip(\"%.*s\", (int)(label_end - label), label);\r\n\r\n    // We don't use BeginPopupContextItem() because we want the popup to stay up even after the column is hidden\r\n    if (IsMouseReleased(1) && IsItemHovered())\r\n        TableOpenContextMenu(column_n);\r\n}\r\n\r\n//-------------------------------------------------------------------------\r\n// [SECTION] Tables: Context Menu\r\n//-------------------------------------------------------------------------\r\n// - TableOpenContextMenu() [Internal]\r\n// - TableDrawContextMenu() [Internal]\r\n//-------------------------------------------------------------------------\r\n\r\n// Use -1 to open menu not specific to a given column.\r\nvoid ImGui::TableOpenContextMenu(int column_n)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiTable* table = g.CurrentTable;\r\n    if (column_n == -1 && table->CurrentColumn != -1)   // When called within a column automatically use this one (for consistency)\r\n        column_n = table->CurrentColumn;\r\n    if (column_n == table->ColumnsCount)                // To facilitate using with TableGetHoveredColumn()\r\n        column_n = -1;\r\n    IM_ASSERT(column_n >= -1 && column_n < table->ColumnsCount);\r\n    if (table->Flags & (ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable))\r\n    {\r\n        table->IsContextPopupOpen = true;\r\n        table->ContextPopupColumn = (ImGuiTableColumnIdx)column_n;\r\n        table->InstanceInteracted = table->InstanceCurrent;\r\n        const ImGuiID context_menu_id = ImHashStr(\"##ContextMenu\", 0, table->ID);\r\n        OpenPopupEx(context_menu_id, ImGuiPopupFlags_None);\r\n    }\r\n}\r\n\r\n// Output context menu into current window (generally a popup)\r\n// FIXME-TABLE: Ideally this should be writable by the user. Full programmatic access to that data?\r\nvoid ImGui::TableDrawContextMenu(ImGuiTable* table)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    if (window->SkipItems)\r\n        return;\r\n\r\n    bool want_separator = false;\r\n    const int column_n = (table->ContextPopupColumn >= 0 && table->ContextPopupColumn < table->ColumnsCount) ? table->ContextPopupColumn : -1;\r\n    ImGuiTableColumn* column = (column_n != -1) ? &table->Columns[column_n] : NULL;\r\n\r\n    // Sizing\r\n    if (table->Flags & ImGuiTableFlags_Resizable)\r\n    {\r\n        if (column != NULL)\r\n        {\r\n            const bool can_resize = !(column->Flags & ImGuiTableColumnFlags_NoResize) && column->IsEnabled;\r\n            if (MenuItem(\"Size column to fit###SizeOne\", NULL, false, can_resize))\r\n                TableSetColumnWidthAutoSingle(table, column_n);\r\n        }\r\n\r\n        const char* size_all_desc;\r\n        if (table->ColumnsEnabledFixedCount == table->ColumnsEnabledCount && (table->Flags & ImGuiTableFlags_SizingMask_) != ImGuiTableFlags_SizingFixedSame)\r\n            size_all_desc = \"Size all columns to fit###SizeAll\";        // All fixed\r\n        else\r\n            size_all_desc = \"Size all columns to default###SizeAll\";    // All stretch or mixed\r\n        if (MenuItem(size_all_desc, NULL))\r\n            TableSetColumnWidthAutoAll(table);\r\n        want_separator = true;\r\n    }\r\n\r\n    // Ordering\r\n    if (table->Flags & ImGuiTableFlags_Reorderable)\r\n    {\r\n        if (MenuItem(\"Reset order\", NULL, false, !table->IsDefaultDisplayOrder))\r\n            table->IsResetDisplayOrderRequest = true;\r\n        want_separator = true;\r\n    }\r\n\r\n    // Reset all (should work but seems unnecessary/noisy to expose?)\r\n    //if (MenuItem(\"Reset all\"))\r\n    //    table->IsResetAllRequest = true;\r\n\r\n    // Sorting\r\n    // (modify TableOpenContextMenu() to add _Sortable flag if enabling this)\r\n#if 0\r\n    if ((table->Flags & ImGuiTableFlags_Sortable) && column != NULL && (column->Flags & ImGuiTableColumnFlags_NoSort) == 0)\r\n    {\r\n        if (want_separator)\r\n            Separator();\r\n        want_separator = true;\r\n\r\n        bool append_to_sort_specs = g.IO.KeyShift;\r\n        if (MenuItem(\"Sort in Ascending Order\", NULL, column->SortOrder != -1 && column->SortDirection == ImGuiSortDirection_Ascending, (column->Flags & ImGuiTableColumnFlags_NoSortAscending) == 0))\r\n            TableSetColumnSortDirection(table, column_n, ImGuiSortDirection_Ascending, append_to_sort_specs);\r\n        if (MenuItem(\"Sort in Descending Order\", NULL, column->SortOrder != -1 && column->SortDirection == ImGuiSortDirection_Descending, (column->Flags & ImGuiTableColumnFlags_NoSortDescending) == 0))\r\n            TableSetColumnSortDirection(table, column_n, ImGuiSortDirection_Descending, append_to_sort_specs);\r\n    }\r\n#endif\r\n\r\n    // Hiding / Visibility\r\n    if (table->Flags & ImGuiTableFlags_Hideable)\r\n    {\r\n        if (want_separator)\r\n            Separator();\r\n        want_separator = true;\r\n\r\n        PushItemFlag(ImGuiItemFlags_SelectableDontClosePopup, true);\r\n        for (int other_column_n = 0; other_column_n < table->ColumnsCount; other_column_n++)\r\n        {\r\n            ImGuiTableColumn* other_column = &table->Columns[other_column_n];\r\n            if (other_column->Flags & ImGuiTableColumnFlags_Disabled)\r\n                continue;\r\n\r\n            const char* name = TableGetColumnName(table, other_column_n);\r\n            if (name == NULL || name[0] == 0)\r\n                name = \"<Unknown>\";\r\n\r\n            // Make sure we can't hide the last active column\r\n            bool menu_item_active = (other_column->Flags & ImGuiTableColumnFlags_NoHide) ? false : true;\r\n            if (other_column->IsUserEnabled && table->ColumnsEnabledCount <= 1)\r\n                menu_item_active = false;\r\n            if (MenuItem(name, NULL, other_column->IsUserEnabled, menu_item_active))\r\n                other_column->IsUserEnabledNextFrame = !other_column->IsUserEnabled;\r\n        }\r\n        PopItemFlag();\r\n    }\r\n}\r\n\r\n//-------------------------------------------------------------------------\r\n// [SECTION] Tables: Settings (.ini data)\r\n//-------------------------------------------------------------------------\r\n// FIXME: The binding/finding/creating flow are too confusing.\r\n//-------------------------------------------------------------------------\r\n// - TableSettingsInit() [Internal]\r\n// - TableSettingsCalcChunkSize() [Internal]\r\n// - TableSettingsCreate() [Internal]\r\n// - TableSettingsFindByID() [Internal]\r\n// - TableGetBoundSettings() [Internal]\r\n// - TableResetSettings()\r\n// - TableSaveSettings() [Internal]\r\n// - TableLoadSettings() [Internal]\r\n// - TableSettingsHandler_ClearAll() [Internal]\r\n// - TableSettingsHandler_ApplyAll() [Internal]\r\n// - TableSettingsHandler_ReadOpen() [Internal]\r\n// - TableSettingsHandler_ReadLine() [Internal]\r\n// - TableSettingsHandler_WriteAll() [Internal]\r\n// - TableSettingsInstallHandler() [Internal]\r\n//-------------------------------------------------------------------------\r\n// [Init] 1: TableSettingsHandler_ReadXXXX()   Load and parse .ini file into TableSettings.\r\n// [Main] 2: TableLoadSettings()               When table is created, bind Table to TableSettings, serialize TableSettings data into Table.\r\n// [Main] 3: TableSaveSettings()               When table properties are modified, serialize Table data into bound or new TableSettings, mark .ini as dirty.\r\n// [Main] 4: TableSettingsHandler_WriteAll()   When .ini file is dirty (which can come from other source), save TableSettings into .ini file.\r\n//-------------------------------------------------------------------------\r\n\r\n// Clear and initialize empty settings instance\r\nstatic void TableSettingsInit(ImGuiTableSettings* settings, ImGuiID id, int columns_count, int columns_count_max)\r\n{\r\n    IM_PLACEMENT_NEW(settings) ImGuiTableSettings();\r\n    ImGuiTableColumnSettings* settings_column = settings->GetColumnSettings();\r\n    for (int n = 0; n < columns_count_max; n++, settings_column++)\r\n        IM_PLACEMENT_NEW(settings_column) ImGuiTableColumnSettings();\r\n    settings->ID = id;\r\n    settings->ColumnsCount = (ImGuiTableColumnIdx)columns_count;\r\n    settings->ColumnsCountMax = (ImGuiTableColumnIdx)columns_count_max;\r\n    settings->WantApply = true;\r\n}\r\n\r\nstatic size_t TableSettingsCalcChunkSize(int columns_count)\r\n{\r\n    return sizeof(ImGuiTableSettings) + (size_t)columns_count * sizeof(ImGuiTableColumnSettings);\r\n}\r\n\r\nImGuiTableSettings* ImGui::TableSettingsCreate(ImGuiID id, int columns_count)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiTableSettings* settings = g.SettingsTables.alloc_chunk(TableSettingsCalcChunkSize(columns_count));\r\n    TableSettingsInit(settings, id, columns_count, columns_count);\r\n    return settings;\r\n}\r\n\r\n// Find existing settings\r\nImGuiTableSettings* ImGui::TableSettingsFindByID(ImGuiID id)\r\n{\r\n    // FIXME-OPT: Might want to store a lookup map for this?\r\n    ImGuiContext& g = *GImGui;\r\n    for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))\r\n        if (settings->ID == id)\r\n            return settings;\r\n    return NULL;\r\n}\r\n\r\n// Get settings for a given table, NULL if none\r\nImGuiTableSettings* ImGui::TableGetBoundSettings(ImGuiTable* table)\r\n{\r\n    if (table->SettingsOffset != -1)\r\n    {\r\n        ImGuiContext& g = *GImGui;\r\n        ImGuiTableSettings* settings = g.SettingsTables.ptr_from_offset(table->SettingsOffset);\r\n        IM_ASSERT(settings->ID == table->ID);\r\n        if (settings->ColumnsCountMax >= table->ColumnsCount)\r\n            return settings; // OK\r\n        settings->ID = 0; // Invalidate storage, we won't fit because of a count change\r\n    }\r\n    return NULL;\r\n}\r\n\r\n// Restore initial state of table (with or without saved settings)\r\nvoid ImGui::TableResetSettings(ImGuiTable* table)\r\n{\r\n    table->IsInitializing = table->IsSettingsDirty = true;\r\n    table->IsResetAllRequest = false;\r\n    table->IsSettingsRequestLoad = false;                   // Don't reload from ini\r\n    table->SettingsLoadedFlags = ImGuiTableFlags_None;      // Mark as nothing loaded so our initialized data becomes authoritative\r\n}\r\n\r\nvoid ImGui::TableSaveSettings(ImGuiTable* table)\r\n{\r\n    table->IsSettingsDirty = false;\r\n    if (table->Flags & ImGuiTableFlags_NoSavedSettings)\r\n        return;\r\n\r\n    // Bind or create settings data\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiTableSettings* settings = TableGetBoundSettings(table);\r\n    if (settings == NULL)\r\n    {\r\n        settings = TableSettingsCreate(table->ID, table->ColumnsCount);\r\n        table->SettingsOffset = g.SettingsTables.offset_from_ptr(settings);\r\n    }\r\n    settings->ColumnsCount = (ImGuiTableColumnIdx)table->ColumnsCount;\r\n\r\n    // Serialize ImGuiTable/ImGuiTableColumn into ImGuiTableSettings/ImGuiTableColumnSettings\r\n    IM_ASSERT(settings->ID == table->ID);\r\n    IM_ASSERT(settings->ColumnsCount == table->ColumnsCount && settings->ColumnsCountMax >= settings->ColumnsCount);\r\n    ImGuiTableColumn* column = table->Columns.Data;\r\n    ImGuiTableColumnSettings* column_settings = settings->GetColumnSettings();\r\n\r\n    bool save_ref_scale = false;\r\n    settings->SaveFlags = ImGuiTableFlags_None;\r\n    for (int n = 0; n < table->ColumnsCount; n++, column++, column_settings++)\r\n    {\r\n        const float width_or_weight = (column->Flags & ImGuiTableColumnFlags_WidthStretch) ? column->StretchWeight : column->WidthRequest;\r\n        column_settings->WidthOrWeight = width_or_weight;\r\n        column_settings->Index = (ImGuiTableColumnIdx)n;\r\n        column_settings->DisplayOrder = column->DisplayOrder;\r\n        column_settings->SortOrder = column->SortOrder;\r\n        column_settings->SortDirection = column->SortDirection;\r\n        column_settings->IsEnabled = column->IsUserEnabled;\r\n        column_settings->IsStretch = (column->Flags & ImGuiTableColumnFlags_WidthStretch) ? 1 : 0;\r\n        if ((column->Flags & ImGuiTableColumnFlags_WidthStretch) == 0)\r\n            save_ref_scale = true;\r\n\r\n        // We skip saving some data in the .ini file when they are unnecessary to restore our state.\r\n        // Note that fixed width where initial width was derived from auto-fit will always be saved as InitStretchWeightOrWidth will be 0.0f.\r\n        // FIXME-TABLE: We don't have logic to easily compare SortOrder to DefaultSortOrder yet so it's always saved when present.\r\n        if (width_or_weight != column->InitStretchWeightOrWidth)\r\n            settings->SaveFlags |= ImGuiTableFlags_Resizable;\r\n        if (column->DisplayOrder != n)\r\n            settings->SaveFlags |= ImGuiTableFlags_Reorderable;\r\n        if (column->SortOrder != -1)\r\n            settings->SaveFlags |= ImGuiTableFlags_Sortable;\r\n        if (column->IsUserEnabled != ((column->Flags & ImGuiTableColumnFlags_DefaultHide) == 0))\r\n            settings->SaveFlags |= ImGuiTableFlags_Hideable;\r\n    }\r\n    settings->SaveFlags &= table->Flags;\r\n    settings->RefScale = save_ref_scale ? table->RefScale : 0.0f;\r\n\r\n    MarkIniSettingsDirty();\r\n}\r\n\r\nvoid ImGui::TableLoadSettings(ImGuiTable* table)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    table->IsSettingsRequestLoad = false;\r\n    if (table->Flags & ImGuiTableFlags_NoSavedSettings)\r\n        return;\r\n\r\n    // Bind settings\r\n    ImGuiTableSettings* settings;\r\n    if (table->SettingsOffset == -1)\r\n    {\r\n        settings = TableSettingsFindByID(table->ID);\r\n        if (settings == NULL)\r\n            return;\r\n        if (settings->ColumnsCount != table->ColumnsCount) // Allow settings if columns count changed. We could otherwise decide to return...\r\n            table->IsSettingsDirty = true;\r\n        table->SettingsOffset = g.SettingsTables.offset_from_ptr(settings);\r\n    }\r\n    else\r\n    {\r\n        settings = TableGetBoundSettings(table);\r\n    }\r\n\r\n    table->SettingsLoadedFlags = settings->SaveFlags;\r\n    table->RefScale = settings->RefScale;\r\n\r\n    // Serialize ImGuiTableSettings/ImGuiTableColumnSettings into ImGuiTable/ImGuiTableColumn\r\n    ImGuiTableColumnSettings* column_settings = settings->GetColumnSettings();\r\n    ImU64 display_order_mask = 0;\r\n    for (int data_n = 0; data_n < settings->ColumnsCount; data_n++, column_settings++)\r\n    {\r\n        int column_n = column_settings->Index;\r\n        if (column_n < 0 || column_n >= table->ColumnsCount)\r\n            continue;\r\n\r\n        ImGuiTableColumn* column = &table->Columns[column_n];\r\n        if (settings->SaveFlags & ImGuiTableFlags_Resizable)\r\n        {\r\n            if (column_settings->IsStretch)\r\n                column->StretchWeight = column_settings->WidthOrWeight;\r\n            else\r\n                column->WidthRequest = column_settings->WidthOrWeight;\r\n            column->AutoFitQueue = 0x00;\r\n        }\r\n        if (settings->SaveFlags & ImGuiTableFlags_Reorderable)\r\n            column->DisplayOrder = column_settings->DisplayOrder;\r\n        else\r\n            column->DisplayOrder = (ImGuiTableColumnIdx)column_n;\r\n        display_order_mask |= (ImU64)1 << column->DisplayOrder;\r\n        column->IsUserEnabled = column->IsUserEnabledNextFrame = column_settings->IsEnabled;\r\n        column->SortOrder = column_settings->SortOrder;\r\n        column->SortDirection = column_settings->SortDirection;\r\n    }\r\n\r\n    // Validate and fix invalid display order data\r\n    const ImU64 expected_display_order_mask = (settings->ColumnsCount == 64) ? ~0 : ((ImU64)1 << settings->ColumnsCount) - 1;\r\n    if (display_order_mask != expected_display_order_mask)\r\n        for (int column_n = 0; column_n < table->ColumnsCount; column_n++)\r\n            table->Columns[column_n].DisplayOrder = (ImGuiTableColumnIdx)column_n;\r\n\r\n    // Rebuild index\r\n    for (int column_n = 0; column_n < table->ColumnsCount; column_n++)\r\n        table->DisplayOrderToIndex[table->Columns[column_n].DisplayOrder] = (ImGuiTableColumnIdx)column_n;\r\n}\r\n\r\nstatic void TableSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)\r\n{\r\n    ImGuiContext& g = *ctx;\r\n    for (int i = 0; i != g.Tables.GetMapSize(); i++)\r\n        if (ImGuiTable* table = g.Tables.TryGetMapData(i))\r\n            table->SettingsOffset = -1;\r\n    g.SettingsTables.clear();\r\n}\r\n\r\n// Apply to existing windows (if any)\r\nstatic void TableSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)\r\n{\r\n    ImGuiContext& g = *ctx;\r\n    for (int i = 0; i != g.Tables.GetMapSize(); i++)\r\n        if (ImGuiTable* table = g.Tables.TryGetMapData(i))\r\n        {\r\n            table->IsSettingsRequestLoad = true;\r\n            table->SettingsOffset = -1;\r\n        }\r\n}\r\n\r\nstatic void* TableSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)\r\n{\r\n    ImGuiID id = 0;\r\n    int columns_count = 0;\r\n    if (sscanf(name, \"0x%08X,%d\", &id, &columns_count) < 2)\r\n        return NULL;\r\n\r\n    if (ImGuiTableSettings* settings = ImGui::TableSettingsFindByID(id))\r\n    {\r\n        if (settings->ColumnsCountMax >= columns_count)\r\n        {\r\n            TableSettingsInit(settings, id, columns_count, settings->ColumnsCountMax); // Recycle\r\n            return settings;\r\n        }\r\n        settings->ID = 0; // Invalidate storage, we won't fit because of a count change\r\n    }\r\n    return ImGui::TableSettingsCreate(id, columns_count);\r\n}\r\n\r\nstatic void TableSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)\r\n{\r\n    // \"Column 0  UserID=0x42AD2D21 Width=100 Visible=1 Order=0 Sort=0v\"\r\n    ImGuiTableSettings* settings = (ImGuiTableSettings*)entry;\r\n    float f = 0.0f;\r\n    int column_n = 0, r = 0, n = 0;\r\n\r\n    if (sscanf(line, \"RefScale=%f\", &f) == 1) { settings->RefScale = f; return; }\r\n\r\n    if (sscanf(line, \"Column %d%n\", &column_n, &r) == 1)\r\n    {\r\n        if (column_n < 0 || column_n >= settings->ColumnsCount)\r\n            return;\r\n        line = ImStrSkipBlank(line + r);\r\n        char c = 0;\r\n        ImGuiTableColumnSettings* column = settings->GetColumnSettings() + column_n;\r\n        column->Index = (ImGuiTableColumnIdx)column_n;\r\n        if (sscanf(line, \"UserID=0x%08X%n\", (ImU32*)&n, &r)==1) { line = ImStrSkipBlank(line + r); column->UserID = (ImGuiID)n; }\r\n        if (sscanf(line, \"Width=%d%n\", &n, &r) == 1)            { line = ImStrSkipBlank(line + r); column->WidthOrWeight = (float)n; column->IsStretch = 0; settings->SaveFlags |= ImGuiTableFlags_Resizable; }\r\n        if (sscanf(line, \"Weight=%f%n\", &f, &r) == 1)           { line = ImStrSkipBlank(line + r); column->WidthOrWeight = f; column->IsStretch = 1; settings->SaveFlags |= ImGuiTableFlags_Resizable; }\r\n        if (sscanf(line, \"Visible=%d%n\", &n, &r) == 1)          { line = ImStrSkipBlank(line + r); column->IsEnabled = (ImU8)n; settings->SaveFlags |= ImGuiTableFlags_Hideable; }\r\n        if (sscanf(line, \"Order=%d%n\", &n, &r) == 1)            { line = ImStrSkipBlank(line + r); column->DisplayOrder = (ImGuiTableColumnIdx)n; settings->SaveFlags |= ImGuiTableFlags_Reorderable; }\r\n        if (sscanf(line, \"Sort=%d%c%n\", &n, &c, &r) == 2)       { line = ImStrSkipBlank(line + r); column->SortOrder = (ImGuiTableColumnIdx)n; column->SortDirection = (c == '^') ? ImGuiSortDirection_Descending : ImGuiSortDirection_Ascending; settings->SaveFlags |= ImGuiTableFlags_Sortable; }\r\n    }\r\n}\r\n\r\nstatic void TableSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)\r\n{\r\n    ImGuiContext& g = *ctx;\r\n    for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))\r\n    {\r\n        if (settings->ID == 0) // Skip ditched settings\r\n            continue;\r\n\r\n        // TableSaveSettings() may clear some of those flags when we establish that the data can be stripped\r\n        // (e.g. Order was unchanged)\r\n        const bool save_size    = (settings->SaveFlags & ImGuiTableFlags_Resizable) != 0;\r\n        const bool save_visible = (settings->SaveFlags & ImGuiTableFlags_Hideable) != 0;\r\n        const bool save_order   = (settings->SaveFlags & ImGuiTableFlags_Reorderable) != 0;\r\n        const bool save_sort    = (settings->SaveFlags & ImGuiTableFlags_Sortable) != 0;\r\n        if (!save_size && !save_visible && !save_order && !save_sort)\r\n            continue;\r\n\r\n        buf->reserve(buf->size() + 30 + settings->ColumnsCount * 50); // ballpark reserve\r\n        buf->appendf(\"[%s][0x%08X,%d]\\n\", handler->TypeName, settings->ID, settings->ColumnsCount);\r\n        if (settings->RefScale != 0.0f)\r\n            buf->appendf(\"RefScale=%g\\n\", settings->RefScale);\r\n        ImGuiTableColumnSettings* column = settings->GetColumnSettings();\r\n        for (int column_n = 0; column_n < settings->ColumnsCount; column_n++, column++)\r\n        {\r\n            // \"Column 0  UserID=0x42AD2D21 Width=100 Visible=1 Order=0 Sort=0v\"\r\n            bool save_column = column->UserID != 0 || save_size || save_visible || save_order || (save_sort && column->SortOrder != -1);\r\n            if (!save_column)\r\n                continue;\r\n            buf->appendf(\"Column %-2d\", column_n);\r\n            if (column->UserID != 0)                    buf->appendf(\" UserID=%08X\", column->UserID);\r\n            if (save_size && column->IsStretch)         buf->appendf(\" Weight=%.4f\", column->WidthOrWeight);\r\n            if (save_size && !column->IsStretch)        buf->appendf(\" Width=%d\", (int)column->WidthOrWeight);\r\n            if (save_visible)                           buf->appendf(\" Visible=%d\", column->IsEnabled);\r\n            if (save_order)                             buf->appendf(\" Order=%d\", column->DisplayOrder);\r\n            if (save_sort && column->SortOrder != -1)   buf->appendf(\" Sort=%d%c\", column->SortOrder, (column->SortDirection == ImGuiSortDirection_Ascending) ? 'v' : '^');\r\n            buf->append(\"\\n\");\r\n        }\r\n        buf->append(\"\\n\");\r\n    }\r\n}\r\n\r\nvoid ImGui::TableSettingsInstallHandler(ImGuiContext* context)\r\n{\r\n    ImGuiContext& g = *context;\r\n    ImGuiSettingsHandler ini_handler;\r\n    ini_handler.TypeName = \"Table\";\r\n    ini_handler.TypeHash = ImHashStr(\"Table\");\r\n    ini_handler.ClearAllFn = TableSettingsHandler_ClearAll;\r\n    ini_handler.ReadOpenFn = TableSettingsHandler_ReadOpen;\r\n    ini_handler.ReadLineFn = TableSettingsHandler_ReadLine;\r\n    ini_handler.ApplyAllFn = TableSettingsHandler_ApplyAll;\r\n    ini_handler.WriteAllFn = TableSettingsHandler_WriteAll;\r\n    g.SettingsHandlers.push_back(ini_handler);\r\n}\r\n\r\n//-------------------------------------------------------------------------\r\n// [SECTION] Tables: Garbage Collection\r\n//-------------------------------------------------------------------------\r\n// - TableRemove() [Internal]\r\n// - TableGcCompactTransientBuffers() [Internal]\r\n// - TableGcCompactSettings() [Internal]\r\n//-------------------------------------------------------------------------\r\n\r\n// Remove Table (currently only used by TestEngine)\r\nvoid ImGui::TableRemove(ImGuiTable* table)\r\n{\r\n    //IMGUI_DEBUG_LOG(\"TableRemove() id=0x%08X\\n\", table->ID);\r\n    ImGuiContext& g = *GImGui;\r\n    int table_idx = g.Tables.GetIndex(table);\r\n    //memset(table->RawData.Data, 0, table->RawData.size_in_bytes());\r\n    //memset(table, 0, sizeof(ImGuiTable));\r\n    g.Tables.Remove(table->ID, table);\r\n    g.TablesLastTimeActive[table_idx] = -1.0f;\r\n}\r\n\r\n// Free up/compact internal Table buffers for when it gets unused\r\nvoid ImGui::TableGcCompactTransientBuffers(ImGuiTable* table)\r\n{\r\n    //IMGUI_DEBUG_LOG(\"TableGcCompactTransientBuffers() id=0x%08X\\n\", table->ID);\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(table->MemoryCompacted == false);\r\n    table->SortSpecs.Specs = NULL;\r\n    table->SortSpecsMulti.clear();\r\n    table->IsSortSpecsDirty = true; // FIXME: shouldn't have to leak into user performing a sort\r\n    table->ColumnsNames.clear();\r\n    table->MemoryCompacted = true;\r\n    for (int n = 0; n < table->ColumnsCount; n++)\r\n        table->Columns[n].NameOffset = -1;\r\n    g.TablesLastTimeActive[g.Tables.GetIndex(table)] = -1.0f;\r\n}\r\n\r\nvoid ImGui::TableGcCompactTransientBuffers(ImGuiTableTempData* temp_data)\r\n{\r\n    temp_data->DrawSplitter.ClearFreeMemory();\r\n    temp_data->LastTimeActive = -1.0f;\r\n}\r\n\r\n// Compact and remove unused settings data (currently only used by TestEngine)\r\nvoid ImGui::TableGcCompactSettings()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    int required_memory = 0;\r\n    for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))\r\n        if (settings->ID != 0)\r\n            required_memory += (int)TableSettingsCalcChunkSize(settings->ColumnsCount);\r\n    if (required_memory == g.SettingsTables.Buf.Size)\r\n        return;\r\n    ImChunkStream<ImGuiTableSettings> new_chunk_stream;\r\n    new_chunk_stream.Buf.reserve(required_memory);\r\n    for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))\r\n        if (settings->ID != 0)\r\n            memcpy(new_chunk_stream.alloc_chunk(TableSettingsCalcChunkSize(settings->ColumnsCount)), settings, TableSettingsCalcChunkSize(settings->ColumnsCount));\r\n    g.SettingsTables.swap(new_chunk_stream);\r\n}\r\n\r\n\r\n//-------------------------------------------------------------------------\r\n// [SECTION] Tables: Debugging\r\n//-------------------------------------------------------------------------\r\n// - DebugNodeTable() [Internal]\r\n//-------------------------------------------------------------------------\r\n\r\n#ifndef IMGUI_DISABLE_METRICS_WINDOW\r\n\r\nstatic const char* DebugNodeTableGetSizingPolicyDesc(ImGuiTableFlags sizing_policy)\r\n{\r\n    sizing_policy &= ImGuiTableFlags_SizingMask_;\r\n    if (sizing_policy == ImGuiTableFlags_SizingFixedFit)    { return \"FixedFit\"; }\r\n    if (sizing_policy == ImGuiTableFlags_SizingFixedSame)   { return \"FixedSame\"; }\r\n    if (sizing_policy == ImGuiTableFlags_SizingStretchProp) { return \"StretchProp\"; }\r\n    if (sizing_policy == ImGuiTableFlags_SizingStretchSame) { return \"StretchSame\"; }\r\n    return \"N/A\";\r\n}\r\n\r\nvoid ImGui::DebugNodeTable(ImGuiTable* table)\r\n{\r\n    char buf[512];\r\n    char* p = buf;\r\n    const char* buf_end = buf + IM_ARRAYSIZE(buf);\r\n    const bool is_active = (table->LastFrameActive >= ImGui::GetFrameCount() - 2); // Note that fully clipped early out scrolling tables will appear as inactive here.\r\n    ImFormatString(p, buf_end - p, \"Table 0x%08X (%d columns, in '%s')%s\", table->ID, table->ColumnsCount, table->OuterWindow->Name, is_active ? \"\" : \" *Inactive*\");\r\n    if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }\r\n    bool open = TreeNode(table, \"%s\", buf);\r\n    if (!is_active) { PopStyleColor(); }\r\n    if (IsItemHovered())\r\n        GetForegroundDrawList()->AddRect(table->OuterRect.Min, table->OuterRect.Max, IM_COL32(255, 255, 0, 255));\r\n    if (IsItemVisible() && table->HoveredColumnBody != -1)\r\n        GetForegroundDrawList()->AddRect(GetItemRectMin(), GetItemRectMax(), IM_COL32(255, 255, 0, 255));\r\n    if (!open)\r\n        return;\r\n    bool clear_settings = SmallButton(\"Clear settings\");\r\n    BulletText(\"OuterRect: Pos: (%.1f,%.1f) Size: (%.1f,%.1f) Sizing: '%s'\", table->OuterRect.Min.x, table->OuterRect.Min.y, table->OuterRect.GetWidth(), table->OuterRect.GetHeight(), DebugNodeTableGetSizingPolicyDesc(table->Flags));\r\n    BulletText(\"ColumnsGivenWidth: %.1f, ColumnsAutoFitWidth: %.1f, InnerWidth: %.1f%s\", table->ColumnsGivenWidth, table->ColumnsAutoFitWidth, table->InnerWidth, table->InnerWidth == 0.0f ? \" (auto)\" : \"\");\r\n    BulletText(\"CellPaddingX: %.1f, CellSpacingX: %.1f/%.1f, OuterPaddingX: %.1f\", table->CellPaddingX, table->CellSpacingX1, table->CellSpacingX2, table->OuterPaddingX);\r\n    BulletText(\"HoveredColumnBody: %d, HoveredColumnBorder: %d\", table->HoveredColumnBody, table->HoveredColumnBorder);\r\n    BulletText(\"ResizedColumn: %d, ReorderColumn: %d, HeldHeaderColumn: %d\", table->ResizedColumn, table->ReorderColumn, table->HeldHeaderColumn);\r\n    //BulletText(\"BgDrawChannels: %d/%d\", 0, table->BgDrawChannelUnfrozen);\r\n    float sum_weights = 0.0f;\r\n    for (int n = 0; n < table->ColumnsCount; n++)\r\n        if (table->Columns[n].Flags & ImGuiTableColumnFlags_WidthStretch)\r\n            sum_weights += table->Columns[n].StretchWeight;\r\n    for (int n = 0; n < table->ColumnsCount; n++)\r\n    {\r\n        ImGuiTableColumn* column = &table->Columns[n];\r\n        const char* name = TableGetColumnName(table, n);\r\n        ImFormatString(buf, IM_ARRAYSIZE(buf),\r\n            \"Column %d order %d '%s': offset %+.2f to %+.2f%s\\n\"\r\n            \"Enabled: %d, VisibleX/Y: %d/%d, RequestOutput: %d, SkipItems: %d, DrawChannels: %d,%d\\n\"\r\n            \"WidthGiven: %.1f, Request/Auto: %.1f/%.1f, StretchWeight: %.3f (%.1f%%)\\n\"\r\n            \"MinX: %.1f, MaxX: %.1f (%+.1f), ClipRect: %.1f to %.1f (+%.1f)\\n\"\r\n            \"ContentWidth: %.1f,%.1f, HeadersUsed/Ideal %.1f/%.1f\\n\"\r\n            \"Sort: %d%s, UserID: 0x%08X, Flags: 0x%04X: %s%s%s..\",\r\n            n, column->DisplayOrder, name, column->MinX - table->WorkRect.Min.x, column->MaxX - table->WorkRect.Min.x, (n < table->FreezeColumnsRequest) ? \" (Frozen)\" : \"\",\r\n            column->IsEnabled, column->IsVisibleX, column->IsVisibleY, column->IsRequestOutput, column->IsSkipItems, column->DrawChannelFrozen, column->DrawChannelUnfrozen,\r\n            column->WidthGiven, column->WidthRequest, column->WidthAuto, column->StretchWeight, column->StretchWeight > 0.0f ? (column->StretchWeight / sum_weights) * 100.0f : 0.0f,\r\n            column->MinX, column->MaxX, column->MaxX - column->MinX, column->ClipRect.Min.x, column->ClipRect.Max.x, column->ClipRect.Max.x - column->ClipRect.Min.x,\r\n            column->ContentMaxXFrozen - column->WorkMinX, column->ContentMaxXUnfrozen - column->WorkMinX, column->ContentMaxXHeadersUsed - column->WorkMinX, column->ContentMaxXHeadersIdeal - column->WorkMinX,\r\n            column->SortOrder, (column->SortDirection == ImGuiSortDirection_Ascending) ? \" (Asc)\" : (column->SortDirection == ImGuiSortDirection_Descending) ? \" (Des)\" : \"\", column->UserID, column->Flags,\r\n            (column->Flags & ImGuiTableColumnFlags_WidthStretch) ? \"WidthStretch \" : \"\",\r\n            (column->Flags & ImGuiTableColumnFlags_WidthFixed) ? \"WidthFixed \" : \"\",\r\n            (column->Flags & ImGuiTableColumnFlags_NoResize) ? \"NoResize \" : \"\");\r\n        Bullet();\r\n        Selectable(buf);\r\n        if (IsItemHovered())\r\n        {\r\n            ImRect r(column->MinX, table->OuterRect.Min.y, column->MaxX, table->OuterRect.Max.y);\r\n            GetForegroundDrawList()->AddRect(r.Min, r.Max, IM_COL32(255, 255, 0, 255));\r\n        }\r\n    }\r\n    if (ImGuiTableSettings* settings = TableGetBoundSettings(table))\r\n        DebugNodeTableSettings(settings);\r\n    if (clear_settings)\r\n        table->IsResetAllRequest = true;\r\n    TreePop();\r\n}\r\n\r\nvoid ImGui::DebugNodeTableSettings(ImGuiTableSettings* settings)\r\n{\r\n    if (!TreeNode((void*)(intptr_t)settings->ID, \"Settings 0x%08X (%d columns)\", settings->ID, settings->ColumnsCount))\r\n        return;\r\n    BulletText(\"SaveFlags: 0x%08X\", settings->SaveFlags);\r\n    BulletText(\"ColumnsCount: %d (max %d)\", settings->ColumnsCount, settings->ColumnsCountMax);\r\n    for (int n = 0; n < settings->ColumnsCount; n++)\r\n    {\r\n        ImGuiTableColumnSettings* column_settings = &settings->GetColumnSettings()[n];\r\n        ImGuiSortDirection sort_dir = (column_settings->SortOrder != -1) ? (ImGuiSortDirection)column_settings->SortDirection : ImGuiSortDirection_None;\r\n        BulletText(\"Column %d Order %d SortOrder %d %s Vis %d %s %7.3f UserID 0x%08X\",\r\n            n, column_settings->DisplayOrder, column_settings->SortOrder,\r\n            (sort_dir == ImGuiSortDirection_Ascending) ? \"Asc\" : (sort_dir == ImGuiSortDirection_Descending) ? \"Des\" : \"---\",\r\n            column_settings->IsEnabled, column_settings->IsStretch ? \"Weight\" : \"Width \", column_settings->WidthOrWeight, column_settings->UserID);\r\n    }\r\n    TreePop();\r\n}\r\n\r\n#else // #ifndef IMGUI_DISABLE_METRICS_WINDOW\r\n\r\nvoid ImGui::DebugNodeTable(ImGuiTable*) {}\r\nvoid ImGui::DebugNodeTableSettings(ImGuiTableSettings*) {}\r\n\r\n#endif\r\n\r\n\r\n//-------------------------------------------------------------------------\r\n// [SECTION] Columns, BeginColumns, EndColumns, etc.\r\n// (This is a legacy API, prefer using BeginTable/EndTable!)\r\n//-------------------------------------------------------------------------\r\n// FIXME: sizing is lossy when columns width is very small (default width may turn negative etc.)\r\n//-------------------------------------------------------------------------\r\n// - SetWindowClipRectBeforeSetChannel() [Internal]\r\n// - GetColumnIndex()\r\n// - GetColumnsCount()\r\n// - GetColumnOffset()\r\n// - GetColumnWidth()\r\n// - SetColumnOffset()\r\n// - SetColumnWidth()\r\n// - PushColumnClipRect() [Internal]\r\n// - PushColumnsBackground() [Internal]\r\n// - PopColumnsBackground() [Internal]\r\n// - FindOrCreateColumns() [Internal]\r\n// - GetColumnsID() [Internal]\r\n// - BeginColumns()\r\n// - NextColumn()\r\n// - EndColumns()\r\n// - Columns()\r\n//-------------------------------------------------------------------------\r\n\r\n// [Internal] Small optimization to avoid calls to PopClipRect/SetCurrentChannel/PushClipRect in sequences,\r\n// they would meddle many times with the underlying ImDrawCmd.\r\n// Instead, we do a preemptive overwrite of clipping rectangle _without_ altering the command-buffer and let\r\n// the subsequent single call to SetCurrentChannel() does it things once.\r\nvoid ImGui::SetWindowClipRectBeforeSetChannel(ImGuiWindow* window, const ImRect& clip_rect)\r\n{\r\n    ImVec4 clip_rect_vec4 = clip_rect.ToVec4();\r\n    window->ClipRect = clip_rect;\r\n    window->DrawList->_CmdHeader.ClipRect = clip_rect_vec4;\r\n    window->DrawList->_ClipRectStack.Data[window->DrawList->_ClipRectStack.Size - 1] = clip_rect_vec4;\r\n}\r\n\r\nint ImGui::GetColumnIndex()\r\n{\r\n    ImGuiWindow* window = GetCurrentWindowRead();\r\n    return window->DC.CurrentColumns ? window->DC.CurrentColumns->Current : 0;\r\n}\r\n\r\nint ImGui::GetColumnsCount()\r\n{\r\n    ImGuiWindow* window = GetCurrentWindowRead();\r\n    return window->DC.CurrentColumns ? window->DC.CurrentColumns->Count : 1;\r\n}\r\n\r\nfloat ImGui::GetColumnOffsetFromNorm(const ImGuiOldColumns* columns, float offset_norm)\r\n{\r\n    return offset_norm * (columns->OffMaxX - columns->OffMinX);\r\n}\r\n\r\nfloat ImGui::GetColumnNormFromOffset(const ImGuiOldColumns* columns, float offset)\r\n{\r\n    return offset / (columns->OffMaxX - columns->OffMinX);\r\n}\r\n\r\nstatic const float COLUMNS_HIT_RECT_HALF_WIDTH = 4.0f;\r\n\r\nstatic float GetDraggedColumnOffset(ImGuiOldColumns* columns, int column_index)\r\n{\r\n    // Active (dragged) column always follow mouse. The reason we need this is that dragging a column to the right edge of an auto-resizing\r\n    // window creates a feedback loop because we store normalized positions. So while dragging we enforce absolute positioning.\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    IM_ASSERT(column_index > 0); // We are not supposed to drag column 0.\r\n    IM_ASSERT(g.ActiveId == columns->ID + ImGuiID(column_index));\r\n\r\n    float x = g.IO.MousePos.x - g.ActiveIdClickOffset.x + COLUMNS_HIT_RECT_HALF_WIDTH - window->Pos.x;\r\n    x = ImMax(x, ImGui::GetColumnOffset(column_index - 1) + g.Style.ColumnsMinSpacing);\r\n    if ((columns->Flags & ImGuiOldColumnFlags_NoPreserveWidths))\r\n        x = ImMin(x, ImGui::GetColumnOffset(column_index + 1) - g.Style.ColumnsMinSpacing);\r\n\r\n    return x;\r\n}\r\n\r\nfloat ImGui::GetColumnOffset(int column_index)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindowRead();\r\n    ImGuiOldColumns* columns = window->DC.CurrentColumns;\r\n    if (columns == NULL)\r\n        return 0.0f;\r\n\r\n    if (column_index < 0)\r\n        column_index = columns->Current;\r\n    IM_ASSERT(column_index < columns->Columns.Size);\r\n\r\n    const float t = columns->Columns[column_index].OffsetNorm;\r\n    const float x_offset = ImLerp(columns->OffMinX, columns->OffMaxX, t);\r\n    return x_offset;\r\n}\r\n\r\nstatic float GetColumnWidthEx(ImGuiOldColumns* columns, int column_index, bool before_resize = false)\r\n{\r\n    if (column_index < 0)\r\n        column_index = columns->Current;\r\n\r\n    float offset_norm;\r\n    if (before_resize)\r\n        offset_norm = columns->Columns[column_index + 1].OffsetNormBeforeResize - columns->Columns[column_index].OffsetNormBeforeResize;\r\n    else\r\n        offset_norm = columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm;\r\n    return ImGui::GetColumnOffsetFromNorm(columns, offset_norm);\r\n}\r\n\r\nfloat ImGui::GetColumnWidth(int column_index)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    ImGuiOldColumns* columns = window->DC.CurrentColumns;\r\n    if (columns == NULL)\r\n        return GetContentRegionAvail().x;\r\n\r\n    if (column_index < 0)\r\n        column_index = columns->Current;\r\n    return GetColumnOffsetFromNorm(columns, columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm);\r\n}\r\n\r\nvoid ImGui::SetColumnOffset(int column_index, float offset)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    ImGuiOldColumns* columns = window->DC.CurrentColumns;\r\n    IM_ASSERT(columns != NULL);\r\n\r\n    if (column_index < 0)\r\n        column_index = columns->Current;\r\n    IM_ASSERT(column_index < columns->Columns.Size);\r\n\r\n    const bool preserve_width = !(columns->Flags & ImGuiOldColumnFlags_NoPreserveWidths) && (column_index < columns->Count - 1);\r\n    const float width = preserve_width ? GetColumnWidthEx(columns, column_index, columns->IsBeingResized) : 0.0f;\r\n\r\n    if (!(columns->Flags & ImGuiOldColumnFlags_NoForceWithinWindow))\r\n        offset = ImMin(offset, columns->OffMaxX - g.Style.ColumnsMinSpacing * (columns->Count - column_index));\r\n    columns->Columns[column_index].OffsetNorm = GetColumnNormFromOffset(columns, offset - columns->OffMinX);\r\n\r\n    if (preserve_width)\r\n        SetColumnOffset(column_index + 1, offset + ImMax(g.Style.ColumnsMinSpacing, width));\r\n}\r\n\r\nvoid ImGui::SetColumnWidth(int column_index, float width)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindowRead();\r\n    ImGuiOldColumns* columns = window->DC.CurrentColumns;\r\n    IM_ASSERT(columns != NULL);\r\n\r\n    if (column_index < 0)\r\n        column_index = columns->Current;\r\n    SetColumnOffset(column_index + 1, GetColumnOffset(column_index) + width);\r\n}\r\n\r\nvoid ImGui::PushColumnClipRect(int column_index)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindowRead();\r\n    ImGuiOldColumns* columns = window->DC.CurrentColumns;\r\n    if (column_index < 0)\r\n        column_index = columns->Current;\r\n\r\n    ImGuiOldColumnData* column = &columns->Columns[column_index];\r\n    PushClipRect(column->ClipRect.Min, column->ClipRect.Max, false);\r\n}\r\n\r\n// Get into the columns background draw command (which is generally the same draw command as before we called BeginColumns)\r\nvoid ImGui::PushColumnsBackground()\r\n{\r\n    ImGuiWindow* window = GetCurrentWindowRead();\r\n    ImGuiOldColumns* columns = window->DC.CurrentColumns;\r\n    if (columns->Count == 1)\r\n        return;\r\n\r\n    // Optimization: avoid SetCurrentChannel() + PushClipRect()\r\n    columns->HostBackupClipRect = window->ClipRect;\r\n    SetWindowClipRectBeforeSetChannel(window, columns->HostInitialClipRect);\r\n    columns->Splitter.SetCurrentChannel(window->DrawList, 0);\r\n}\r\n\r\nvoid ImGui::PopColumnsBackground()\r\n{\r\n    ImGuiWindow* window = GetCurrentWindowRead();\r\n    ImGuiOldColumns* columns = window->DC.CurrentColumns;\r\n    if (columns->Count == 1)\r\n        return;\r\n\r\n    // Optimization: avoid PopClipRect() + SetCurrentChannel()\r\n    SetWindowClipRectBeforeSetChannel(window, columns->HostBackupClipRect);\r\n    columns->Splitter.SetCurrentChannel(window->DrawList, columns->Current + 1);\r\n}\r\n\r\nImGuiOldColumns* ImGui::FindOrCreateColumns(ImGuiWindow* window, ImGuiID id)\r\n{\r\n    // We have few columns per window so for now we don't need bother much with turning this into a faster lookup.\r\n    for (int n = 0; n < window->ColumnsStorage.Size; n++)\r\n        if (window->ColumnsStorage[n].ID == id)\r\n            return &window->ColumnsStorage[n];\r\n\r\n    window->ColumnsStorage.push_back(ImGuiOldColumns());\r\n    ImGuiOldColumns* columns = &window->ColumnsStorage.back();\r\n    columns->ID = id;\r\n    return columns;\r\n}\r\n\r\nImGuiID ImGui::GetColumnsID(const char* str_id, int columns_count)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n\r\n    // Differentiate column ID with an arbitrary prefix for cases where users name their columns set the same as another widget.\r\n    // In addition, when an identifier isn't explicitly provided we include the number of columns in the hash to make it uniquer.\r\n    PushID(0x11223347 + (str_id ? 0 : columns_count));\r\n    ImGuiID id = window->GetID(str_id ? str_id : \"columns\");\r\n    PopID();\r\n\r\n    return id;\r\n}\r\n\r\nvoid ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiOldColumnFlags flags)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n\r\n    IM_ASSERT(columns_count >= 1);\r\n    IM_ASSERT(window->DC.CurrentColumns == NULL);   // Nested columns are currently not supported\r\n\r\n    // Acquire storage for the columns set\r\n    ImGuiID id = GetColumnsID(str_id, columns_count);\r\n    ImGuiOldColumns* columns = FindOrCreateColumns(window, id);\r\n    IM_ASSERT(columns->ID == id);\r\n    columns->Current = 0;\r\n    columns->Count = columns_count;\r\n    columns->Flags = flags;\r\n    window->DC.CurrentColumns = columns;\r\n\r\n    columns->HostCursorPosY = window->DC.CursorPos.y;\r\n    columns->HostCursorMaxPosX = window->DC.CursorMaxPos.x;\r\n    columns->HostInitialClipRect = window->ClipRect;\r\n    columns->HostBackupParentWorkRect = window->ParentWorkRect;\r\n    window->ParentWorkRect = window->WorkRect;\r\n\r\n    // Set state for first column\r\n    // We aim so that the right-most column will have the same clipping width as other after being clipped by parent ClipRect\r\n    const float column_padding = g.Style.ItemSpacing.x;\r\n    const float half_clip_extend_x = ImFloor(ImMax(window->WindowPadding.x * 0.5f, window->WindowBorderSize));\r\n    const float max_1 = window->WorkRect.Max.x + column_padding - ImMax(column_padding - window->WindowPadding.x, 0.0f);\r\n    const float max_2 = window->WorkRect.Max.x + half_clip_extend_x;\r\n    columns->OffMinX = window->DC.Indent.x - column_padding + ImMax(column_padding - window->WindowPadding.x, 0.0f);\r\n    columns->OffMaxX = ImMax(ImMin(max_1, max_2) - window->Pos.x, columns->OffMinX + 1.0f);\r\n    columns->LineMinY = columns->LineMaxY = window->DC.CursorPos.y;\r\n\r\n    // Clear data if columns count changed\r\n    if (columns->Columns.Size != 0 && columns->Columns.Size != columns_count + 1)\r\n        columns->Columns.resize(0);\r\n\r\n    // Initialize default widths\r\n    columns->IsFirstFrame = (columns->Columns.Size == 0);\r\n    if (columns->Columns.Size == 0)\r\n    {\r\n        columns->Columns.reserve(columns_count + 1);\r\n        for (int n = 0; n < columns_count + 1; n++)\r\n        {\r\n            ImGuiOldColumnData column;\r\n            column.OffsetNorm = n / (float)columns_count;\r\n            columns->Columns.push_back(column);\r\n        }\r\n    }\r\n\r\n    for (int n = 0; n < columns_count; n++)\r\n    {\r\n        // Compute clipping rectangle\r\n        ImGuiOldColumnData* column = &columns->Columns[n];\r\n        float clip_x1 = IM_ROUND(window->Pos.x + GetColumnOffset(n));\r\n        float clip_x2 = IM_ROUND(window->Pos.x + GetColumnOffset(n + 1) - 1.0f);\r\n        column->ClipRect = ImRect(clip_x1, -FLT_MAX, clip_x2, +FLT_MAX);\r\n        column->ClipRect.ClipWithFull(window->ClipRect);\r\n    }\r\n\r\n    if (columns->Count > 1)\r\n    {\r\n        columns->Splitter.Split(window->DrawList, 1 + columns->Count);\r\n        columns->Splitter.SetCurrentChannel(window->DrawList, 1);\r\n        PushColumnClipRect(0);\r\n    }\r\n\r\n    // We don't generally store Indent.x inside ColumnsOffset because it may be manipulated by the user.\r\n    float offset_0 = GetColumnOffset(columns->Current);\r\n    float offset_1 = GetColumnOffset(columns->Current + 1);\r\n    float width = offset_1 - offset_0;\r\n    PushItemWidth(width * 0.65f);\r\n    window->DC.ColumnsOffset.x = ImMax(column_padding - window->WindowPadding.x, 0.0f);\r\n    window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);\r\n    window->WorkRect.Max.x = window->Pos.x + offset_1 - column_padding;\r\n}\r\n\r\nvoid ImGui::NextColumn()\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems || window->DC.CurrentColumns == NULL)\r\n        return;\r\n\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiOldColumns* columns = window->DC.CurrentColumns;\r\n\r\n    if (columns->Count == 1)\r\n    {\r\n        window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);\r\n        IM_ASSERT(columns->Current == 0);\r\n        return;\r\n    }\r\n\r\n    // Next column\r\n    if (++columns->Current == columns->Count)\r\n        columns->Current = 0;\r\n\r\n    PopItemWidth();\r\n\r\n    // Optimization: avoid PopClipRect() + SetCurrentChannel() + PushClipRect()\r\n    // (which would needlessly attempt to update commands in the wrong channel, then pop or overwrite them),\r\n    ImGuiOldColumnData* column = &columns->Columns[columns->Current];\r\n    SetWindowClipRectBeforeSetChannel(window, column->ClipRect);\r\n    columns->Splitter.SetCurrentChannel(window->DrawList, columns->Current + 1);\r\n\r\n    const float column_padding = g.Style.ItemSpacing.x;\r\n    columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y);\r\n    if (columns->Current > 0)\r\n    {\r\n        // Columns 1+ ignore IndentX (by canceling it out)\r\n        // FIXME-COLUMNS: Unnecessary, could be locked?\r\n        window->DC.ColumnsOffset.x = GetColumnOffset(columns->Current) - window->DC.Indent.x + column_padding;\r\n    }\r\n    else\r\n    {\r\n        // New row/line: column 0 honor IndentX.\r\n        window->DC.ColumnsOffset.x = ImMax(column_padding - window->WindowPadding.x, 0.0f);\r\n        columns->LineMinY = columns->LineMaxY;\r\n    }\r\n    window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);\r\n    window->DC.CursorPos.y = columns->LineMinY;\r\n    window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);\r\n    window->DC.CurrLineTextBaseOffset = 0.0f;\r\n\r\n    // FIXME-COLUMNS: Share code with BeginColumns() - move code on columns setup.\r\n    float offset_0 = GetColumnOffset(columns->Current);\r\n    float offset_1 = GetColumnOffset(columns->Current + 1);\r\n    float width = offset_1 - offset_0;\r\n    PushItemWidth(width * 0.65f);\r\n    window->WorkRect.Max.x = window->Pos.x + offset_1 - column_padding;\r\n}\r\n\r\nvoid ImGui::EndColumns()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    ImGuiOldColumns* columns = window->DC.CurrentColumns;\r\n    IM_ASSERT(columns != NULL);\r\n\r\n    PopItemWidth();\r\n    if (columns->Count > 1)\r\n    {\r\n        PopClipRect();\r\n        columns->Splitter.Merge(window->DrawList);\r\n    }\r\n\r\n    const ImGuiOldColumnFlags flags = columns->Flags;\r\n    columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y);\r\n    window->DC.CursorPos.y = columns->LineMaxY;\r\n    if (!(flags & ImGuiOldColumnFlags_GrowParentContentsSize))\r\n        window->DC.CursorMaxPos.x = columns->HostCursorMaxPosX;  // Restore cursor max pos, as columns don't grow parent\r\n\r\n    // Draw columns borders and handle resize\r\n    // The IsBeingResized flag ensure we preserve pre-resize columns width so back-and-forth are not lossy\r\n    bool is_being_resized = false;\r\n    if (!(flags & ImGuiOldColumnFlags_NoBorder) && !window->SkipItems)\r\n    {\r\n        // We clip Y boundaries CPU side because very long triangles are mishandled by some GPU drivers.\r\n        const float y1 = ImMax(columns->HostCursorPosY, window->ClipRect.Min.y);\r\n        const float y2 = ImMin(window->DC.CursorPos.y, window->ClipRect.Max.y);\r\n        int dragging_column = -1;\r\n        for (int n = 1; n < columns->Count; n++)\r\n        {\r\n            ImGuiOldColumnData* column = &columns->Columns[n];\r\n            float x = window->Pos.x + GetColumnOffset(n);\r\n            const ImGuiID column_id = columns->ID + ImGuiID(n);\r\n            const float column_hit_hw = COLUMNS_HIT_RECT_HALF_WIDTH;\r\n            const ImRect column_hit_rect(ImVec2(x - column_hit_hw, y1), ImVec2(x + column_hit_hw, y2));\r\n            KeepAliveID(column_id);\r\n            if (IsClippedEx(column_hit_rect, column_id)) // FIXME: Can be removed or replaced with a lower-level test\r\n                continue;\r\n\r\n            bool hovered = false, held = false;\r\n            if (!(flags & ImGuiOldColumnFlags_NoResize))\r\n            {\r\n                ButtonBehavior(column_hit_rect, column_id, &hovered, &held);\r\n                if (hovered || held)\r\n                    g.MouseCursor = ImGuiMouseCursor_ResizeEW;\r\n                if (held && !(column->Flags & ImGuiOldColumnFlags_NoResize))\r\n                    dragging_column = n;\r\n            }\r\n\r\n            // Draw column\r\n            const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : hovered ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator);\r\n            const float xi = IM_FLOOR(x);\r\n            window->DrawList->AddLine(ImVec2(xi, y1 + 1.0f), ImVec2(xi, y2), col);\r\n        }\r\n\r\n        // Apply dragging after drawing the column lines, so our rendered lines are in sync with how items were displayed during the frame.\r\n        if (dragging_column != -1)\r\n        {\r\n            if (!columns->IsBeingResized)\r\n                for (int n = 0; n < columns->Count + 1; n++)\r\n                    columns->Columns[n].OffsetNormBeforeResize = columns->Columns[n].OffsetNorm;\r\n            columns->IsBeingResized = is_being_resized = true;\r\n            float x = GetDraggedColumnOffset(columns, dragging_column);\r\n            SetColumnOffset(dragging_column, x);\r\n        }\r\n    }\r\n    columns->IsBeingResized = is_being_resized;\r\n\r\n    window->WorkRect = window->ParentWorkRect;\r\n    window->ParentWorkRect = columns->HostBackupParentWorkRect;\r\n    window->DC.CurrentColumns = NULL;\r\n    window->DC.ColumnsOffset.x = 0.0f;\r\n    window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);\r\n}\r\n\r\nvoid ImGui::Columns(int columns_count, const char* id, bool border)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    IM_ASSERT(columns_count >= 1);\r\n\r\n    ImGuiOldColumnFlags flags = (border ? 0 : ImGuiOldColumnFlags_NoBorder);\r\n    //flags |= ImGuiOldColumnFlags_NoPreserveWidths; // NB: Legacy behavior\r\n    ImGuiOldColumns* columns = window->DC.CurrentColumns;\r\n    if (columns != NULL && columns->Count == columns_count && columns->Flags == flags)\r\n        return;\r\n\r\n    if (columns != NULL)\r\n        EndColumns();\r\n\r\n    if (columns_count != 1)\r\n        BeginColumns(id, columns_count, flags);\r\n}\r\n\r\n//-------------------------------------------------------------------------\r\n\r\n#endif // #ifndef IMGUI_DISABLE\r\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/imgui/imgui_widgets.cpp",
    "content": "// dear imgui, v1.87 WIP\r\n// (widgets code)\r\n\r\n/*\r\n\r\nIndex of this file:\r\n\r\n// [SECTION] Forward Declarations\r\n// [SECTION] Widgets: Text, etc.\r\n// [SECTION] Widgets: Main (Button, Image, Checkbox, RadioButton, ProgressBar, Bullet, etc.)\r\n// [SECTION] Widgets: Low-level Layout helpers (Spacing, Dummy, NewLine, Separator, etc.)\r\n// [SECTION] Widgets: ComboBox\r\n// [SECTION] Data Type and Data Formatting Helpers\r\n// [SECTION] Widgets: DragScalar, DragFloat, DragInt, etc.\r\n// [SECTION] Widgets: SliderScalar, SliderFloat, SliderInt, etc.\r\n// [SECTION] Widgets: InputScalar, InputFloat, InputInt, etc.\r\n// [SECTION] Widgets: InputText, InputTextMultiline\r\n// [SECTION] Widgets: ColorEdit, ColorPicker, ColorButton, etc.\r\n// [SECTION] Widgets: TreeNode, CollapsingHeader, etc.\r\n// [SECTION] Widgets: Selectable\r\n// [SECTION] Widgets: ListBox\r\n// [SECTION] Widgets: PlotLines, PlotHistogram\r\n// [SECTION] Widgets: Value helpers\r\n// [SECTION] Widgets: MenuItem, BeginMenu, EndMenu, etc.\r\n// [SECTION] Widgets: BeginTabBar, EndTabBar, etc.\r\n// [SECTION] Widgets: BeginTabItem, EndTabItem, etc.\r\n// [SECTION] Widgets: Columns, BeginColumns, EndColumns, etc.\r\n\r\n*/\r\n\r\n#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)\r\n#define _CRT_SECURE_NO_WARNINGS\r\n#endif\r\n\r\n#include \"imgui.h\"\r\n#ifndef IMGUI_DISABLE\r\n\r\n#ifndef IMGUI_DEFINE_MATH_OPERATORS\r\n#define IMGUI_DEFINE_MATH_OPERATORS\r\n#endif\r\n#include \"imgui_internal.h\"\r\n\r\n// System includes\r\n#include <ctype.h>      // toupper\r\n#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier\r\n#include <stddef.h>     // intptr_t\r\n#else\r\n#include <stdint.h>     // intptr_t\r\n#endif\r\n\r\n//-------------------------------------------------------------------------\r\n// Warnings\r\n//-------------------------------------------------------------------------\r\n\r\n// Visual Studio warnings\r\n#ifdef _MSC_VER\r\n#pragma warning (disable: 4127)     // condition expression is constant\r\n#pragma warning (disable: 4996)     // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen\r\n#if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later\r\n#pragma warning (disable: 5054)     // operator '|': deprecated between enumerations of different types\r\n#endif\r\n#pragma warning (disable: 26451)    // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to a 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2).\r\n#pragma warning (disable: 26812)    // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).\r\n#endif\r\n\r\n// Clang/GCC warnings with -Weverything\r\n#if defined(__clang__)\r\n#if __has_warning(\"-Wunknown-warning-option\")\r\n#pragma clang diagnostic ignored \"-Wunknown-warning-option\"         // warning: unknown warning group 'xxx'                      // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great!\r\n#endif\r\n#pragma clang diagnostic ignored \"-Wunknown-pragmas\"                // warning: unknown warning group 'xxx'\r\n#pragma clang diagnostic ignored \"-Wold-style-cast\"                 // warning: use of old-style cast                            // yes, they are more terse.\r\n#pragma clang diagnostic ignored \"-Wfloat-equal\"                    // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok.\r\n#pragma clang diagnostic ignored \"-Wformat-nonliteral\"              // warning: format string is not a string literal            // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code.\r\n#pragma clang diagnostic ignored \"-Wsign-conversion\"                // warning: implicit conversion changes signedness\r\n#pragma clang diagnostic ignored \"-Wzero-as-null-pointer-constant\"  // warning: zero as null pointer constant                    // some standard header variations use #define NULL 0\r\n#pragma clang diagnostic ignored \"-Wdouble-promotion\"               // warning: implicit conversion from 'float' to 'double' when passing argument to function  // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.\r\n#pragma clang diagnostic ignored \"-Wenum-enum-conversion\"           // warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_')\r\n#pragma clang diagnostic ignored \"-Wdeprecated-enum-enum-conversion\"// warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated\r\n#pragma clang diagnostic ignored \"-Wimplicit-int-float-conversion\"  // warning: implicit conversion from 'xxx' to 'float' may lose precision\r\n#elif defined(__GNUC__)\r\n#pragma GCC diagnostic ignored \"-Wpragmas\"                          // warning: unknown option after '#pragma GCC diagnostic' kind\r\n#pragma GCC diagnostic ignored \"-Wformat-nonliteral\"                // warning: format not a string literal, format string not checked\r\n#pragma GCC diagnostic ignored \"-Wclass-memaccess\"                  // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead\r\n#endif\r\n\r\n//-------------------------------------------------------------------------\r\n// Data\r\n//-------------------------------------------------------------------------\r\n\r\n// Widgets\r\nstatic const float          DRAGDROP_HOLD_TO_OPEN_TIMER = 0.70f;    // Time for drag-hold to activate items accepting the ImGuiButtonFlags_PressedOnDragDropHold button behavior.\r\nstatic const float          DRAG_MOUSE_THRESHOLD_FACTOR = 0.50f;    // Multiplier for the default value of io.MouseDragThreshold to make DragFloat/DragInt react faster to mouse drags.\r\n\r\n// Those MIN/MAX values are not define because we need to point to them\r\nstatic const signed char    IM_S8_MIN  = -128;\r\nstatic const signed char    IM_S8_MAX  = 127;\r\nstatic const unsigned char  IM_U8_MIN  = 0;\r\nstatic const unsigned char  IM_U8_MAX  = 0xFF;\r\nstatic const signed short   IM_S16_MIN = -32768;\r\nstatic const signed short   IM_S16_MAX = 32767;\r\nstatic const unsigned short IM_U16_MIN = 0;\r\nstatic const unsigned short IM_U16_MAX = 0xFFFF;\r\nstatic const ImS32          IM_S32_MIN = INT_MIN;    // (-2147483647 - 1), (0x80000000);\r\nstatic const ImS32          IM_S32_MAX = INT_MAX;    // (2147483647), (0x7FFFFFFF)\r\nstatic const ImU32          IM_U32_MIN = 0;\r\nstatic const ImU32          IM_U32_MAX = UINT_MAX;   // (0xFFFFFFFF)\r\n#ifdef LLONG_MIN\r\nstatic const ImS64          IM_S64_MIN = LLONG_MIN;  // (-9223372036854775807ll - 1ll);\r\nstatic const ImS64          IM_S64_MAX = LLONG_MAX;  // (9223372036854775807ll);\r\n#else\r\nstatic const ImS64          IM_S64_MIN = -9223372036854775807LL - 1;\r\nstatic const ImS64          IM_S64_MAX = 9223372036854775807LL;\r\n#endif\r\nstatic const ImU64          IM_U64_MIN = 0;\r\n#ifdef ULLONG_MAX\r\nstatic const ImU64          IM_U64_MAX = ULLONG_MAX; // (0xFFFFFFFFFFFFFFFFull);\r\n#else\r\nstatic const ImU64          IM_U64_MAX = (2ULL * 9223372036854775807LL + 1);\r\n#endif\r\n\r\n//-------------------------------------------------------------------------\r\n// [SECTION] Forward Declarations\r\n//-------------------------------------------------------------------------\r\n\r\n// For InputTextEx()\r\nstatic bool             InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data, ImGuiInputSource input_source);\r\nstatic int              InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end);\r\nstatic ImVec2           InputTextCalcTextSizeW(const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining = NULL, ImVec2* out_offset = NULL, bool stop_on_new_line = false);\r\n\r\n//-------------------------------------------------------------------------\r\n// [SECTION] Widgets: Text, etc.\r\n//-------------------------------------------------------------------------\r\n// - TextEx() [Internal]\r\n// - TextUnformatted()\r\n// - Text()\r\n// - TextV()\r\n// - TextColored()\r\n// - TextColoredV()\r\n// - TextDisabled()\r\n// - TextDisabledV()\r\n// - TextWrapped()\r\n// - TextWrappedV()\r\n// - LabelText()\r\n// - LabelTextV()\r\n// - BulletText()\r\n// - BulletTextV()\r\n//-------------------------------------------------------------------------\r\n\r\nvoid ImGui::TextEx(const char* text, const char* text_end, ImGuiTextFlags flags)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return;\r\n    ImGuiContext& g = *GImGui;\r\n\r\n    // Accept null ranges\r\n    if (text == text_end)\r\n        text = text_end = \"\";\r\n\r\n    // Calculate length\r\n    const char* text_begin = text;\r\n    if (text_end == NULL)\r\n        text_end = text + strlen(text); // FIXME-OPT\r\n\r\n    const ImVec2 text_pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset);\r\n    const float wrap_pos_x = window->DC.TextWrapPos;\r\n    const bool wrap_enabled = (wrap_pos_x >= 0.0f);\r\n    if (text_end - text > 2000 && !wrap_enabled)\r\n    {\r\n        // Long text!\r\n        // Perform manual coarse clipping to optimize for long multi-line text\r\n        // - From this point we will only compute the width of lines that are visible. Optimization only available when word-wrapping is disabled.\r\n        // - We also don't vertically center the text within the line full height, which is unlikely to matter because we are likely the biggest and only item on the line.\r\n        // - We use memchr(), pay attention that well optimized versions of those str/mem functions are much faster than a casually written loop.\r\n        const char* line = text;\r\n        const float line_height = GetTextLineHeight();\r\n        ImVec2 text_size(0, 0);\r\n\r\n        // Lines to skip (can't skip when logging text)\r\n        ImVec2 pos = text_pos;\r\n        if (!g.LogEnabled)\r\n        {\r\n            int lines_skippable = (int)((window->ClipRect.Min.y - text_pos.y) / line_height);\r\n            if (lines_skippable > 0)\r\n            {\r\n                int lines_skipped = 0;\r\n                while (line < text_end && lines_skipped < lines_skippable)\r\n                {\r\n                    const char* line_end = (const char*)memchr(line, '\\n', text_end - line);\r\n                    if (!line_end)\r\n                        line_end = text_end;\r\n                    if ((flags & ImGuiTextFlags_NoWidthForLargeClippedText) == 0)\r\n                        text_size.x = ImMax(text_size.x, CalcTextSize(line, line_end).x);\r\n                    line = line_end + 1;\r\n                    lines_skipped++;\r\n                }\r\n                pos.y += lines_skipped * line_height;\r\n            }\r\n        }\r\n\r\n        // Lines to render\r\n        if (line < text_end)\r\n        {\r\n            ImRect line_rect(pos, pos + ImVec2(FLT_MAX, line_height));\r\n            while (line < text_end)\r\n            {\r\n                if (IsClippedEx(line_rect, 0))\r\n                    break;\r\n\r\n                const char* line_end = (const char*)memchr(line, '\\n', text_end - line);\r\n                if (!line_end)\r\n                    line_end = text_end;\r\n                text_size.x = ImMax(text_size.x, CalcTextSize(line, line_end).x);\r\n                RenderText(pos, line, line_end, false);\r\n                line = line_end + 1;\r\n                line_rect.Min.y += line_height;\r\n                line_rect.Max.y += line_height;\r\n                pos.y += line_height;\r\n            }\r\n\r\n            // Count remaining lines\r\n            int lines_skipped = 0;\r\n            while (line < text_end)\r\n            {\r\n                const char* line_end = (const char*)memchr(line, '\\n', text_end - line);\r\n                if (!line_end)\r\n                    line_end = text_end;\r\n                if ((flags & ImGuiTextFlags_NoWidthForLargeClippedText) == 0)\r\n                    text_size.x = ImMax(text_size.x, CalcTextSize(line, line_end).x);\r\n                line = line_end + 1;\r\n                lines_skipped++;\r\n            }\r\n            pos.y += lines_skipped * line_height;\r\n        }\r\n        text_size.y = (pos - text_pos).y;\r\n\r\n        ImRect bb(text_pos, text_pos + text_size);\r\n        ItemSize(text_size, 0.0f);\r\n        ItemAdd(bb, 0);\r\n    }\r\n    else\r\n    {\r\n        const float wrap_width = wrap_enabled ? CalcWrapWidthForPos(window->DC.CursorPos, wrap_pos_x) : 0.0f;\r\n        const ImVec2 text_size = CalcTextSize(text_begin, text_end, false, wrap_width);\r\n\r\n        ImRect bb(text_pos, text_pos + text_size);\r\n        ItemSize(text_size, 0.0f);\r\n        if (!ItemAdd(bb, 0))\r\n            return;\r\n\r\n        // Render (we don't hide text after ## in this end-user function)\r\n        RenderTextWrapped(bb.Min, text_begin, text_end, wrap_width);\r\n    }\r\n}\r\n\r\nvoid ImGui::TextUnformatted(const char* text, const char* text_end)\r\n{\r\n    TextEx(text, text_end, ImGuiTextFlags_NoWidthForLargeClippedText);\r\n}\r\n\r\nvoid ImGui::Text(const char* fmt, ...)\r\n{\r\n    va_list args;\r\n    va_start(args, fmt);\r\n    TextV(fmt, args);\r\n    va_end(args);\r\n}\r\n\r\nvoid ImGui::TextV(const char* fmt, va_list args)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return;\r\n\r\n    // FIXME-OPT: Handle the %s shortcut?\r\n    ImGuiContext& g = *GImGui;\r\n    const char* text_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);\r\n    TextEx(g.TempBuffer, text_end, ImGuiTextFlags_NoWidthForLargeClippedText);\r\n}\r\n\r\nvoid ImGui::TextColored(const ImVec4& col, const char* fmt, ...)\r\n{\r\n    va_list args;\r\n    va_start(args, fmt);\r\n    TextColoredV(col, fmt, args);\r\n    va_end(args);\r\n}\r\n\r\nvoid ImGui::TextColoredV(const ImVec4& col, const char* fmt, va_list args)\r\n{\r\n    PushStyleColor(ImGuiCol_Text, col);\r\n    if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0)\r\n        TextEx(va_arg(args, const char*), NULL, ImGuiTextFlags_NoWidthForLargeClippedText); // Skip formatting\r\n    else\r\n        TextV(fmt, args);\r\n    PopStyleColor();\r\n}\r\n\r\nvoid ImGui::TextDisabled(const char* fmt, ...)\r\n{\r\n    va_list args;\r\n    va_start(args, fmt);\r\n    TextDisabledV(fmt, args);\r\n    va_end(args);\r\n}\r\n\r\nvoid ImGui::TextDisabledV(const char* fmt, va_list args)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]);\r\n    if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0)\r\n        TextEx(va_arg(args, const char*), NULL, ImGuiTextFlags_NoWidthForLargeClippedText); // Skip formatting\r\n    else\r\n        TextV(fmt, args);\r\n    PopStyleColor();\r\n}\r\n\r\nvoid ImGui::TextWrapped(const char* fmt, ...)\r\n{\r\n    va_list args;\r\n    va_start(args, fmt);\r\n    TextWrappedV(fmt, args);\r\n    va_end(args);\r\n}\r\n\r\nvoid ImGui::TextWrappedV(const char* fmt, va_list args)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    bool need_backup = (g.CurrentWindow->DC.TextWrapPos < 0.0f);  // Keep existing wrap position if one is already set\r\n    if (need_backup)\r\n        PushTextWrapPos(0.0f);\r\n    if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0)\r\n        TextEx(va_arg(args, const char*), NULL, ImGuiTextFlags_NoWidthForLargeClippedText); // Skip formatting\r\n    else\r\n        TextV(fmt, args);\r\n    if (need_backup)\r\n        PopTextWrapPos();\r\n}\r\n\r\nvoid ImGui::LabelText(const char* label, const char* fmt, ...)\r\n{\r\n    va_list args;\r\n    va_start(args, fmt);\r\n    LabelTextV(label, fmt, args);\r\n    va_end(args);\r\n}\r\n\r\n// Add a label+text combo aligned to other label+value widgets\r\nvoid ImGui::LabelTextV(const char* label, const char* fmt, va_list args)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return;\r\n\r\n    ImGuiContext& g = *GImGui;\r\n    const ImGuiStyle& style = g.Style;\r\n    const float w = CalcItemWidth();\r\n\r\n    const char* value_text_begin = &g.TempBuffer[0];\r\n    const char* value_text_end = value_text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);\r\n    const ImVec2 value_size = CalcTextSize(value_text_begin, value_text_end, false);\r\n    const ImVec2 label_size = CalcTextSize(label, NULL, true);\r\n\r\n    const ImVec2 pos = window->DC.CursorPos;\r\n    const ImRect value_bb(pos, pos + ImVec2(w, value_size.y + style.FramePadding.y * 2));\r\n    const ImRect total_bb(pos, pos + ImVec2(w + (label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f), ImMax(value_size.y, label_size.y) + style.FramePadding.y * 2));\r\n    ItemSize(total_bb, style.FramePadding.y);\r\n    if (!ItemAdd(total_bb, 0))\r\n        return;\r\n\r\n    // Render\r\n    RenderTextClipped(value_bb.Min + style.FramePadding, value_bb.Max, value_text_begin, value_text_end, &value_size, ImVec2(0.0f, 0.0f));\r\n    if (label_size.x > 0.0f)\r\n        RenderText(ImVec2(value_bb.Max.x + style.ItemInnerSpacing.x, value_bb.Min.y + style.FramePadding.y), label);\r\n}\r\n\r\nvoid ImGui::BulletText(const char* fmt, ...)\r\n{\r\n    va_list args;\r\n    va_start(args, fmt);\r\n    BulletTextV(fmt, args);\r\n    va_end(args);\r\n}\r\n\r\n// Text with a little bullet aligned to the typical tree node.\r\nvoid ImGui::BulletTextV(const char* fmt, va_list args)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return;\r\n\r\n    ImGuiContext& g = *GImGui;\r\n    const ImGuiStyle& style = g.Style;\r\n\r\n    const char* text_begin = g.TempBuffer;\r\n    const char* text_end = text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);\r\n    const ImVec2 label_size = CalcTextSize(text_begin, text_end, false);\r\n    const ImVec2 total_size = ImVec2(g.FontSize + (label_size.x > 0.0f ? (label_size.x + style.FramePadding.x * 2) : 0.0f), label_size.y);  // Empty text doesn't add padding\r\n    ImVec2 pos = window->DC.CursorPos;\r\n    pos.y += window->DC.CurrLineTextBaseOffset;\r\n    ItemSize(total_size, 0.0f);\r\n    const ImRect bb(pos, pos + total_size);\r\n    if (!ItemAdd(bb, 0))\r\n        return;\r\n\r\n    // Render\r\n    ImU32 text_col = GetColorU32(ImGuiCol_Text);\r\n    RenderBullet(window->DrawList, bb.Min + ImVec2(style.FramePadding.x + g.FontSize * 0.5f, g.FontSize * 0.5f), text_col);\r\n    RenderText(bb.Min + ImVec2(g.FontSize + style.FramePadding.x * 2, 0.0f), text_begin, text_end, false);\r\n}\r\n\r\n//-------------------------------------------------------------------------\r\n// [SECTION] Widgets: Main\r\n//-------------------------------------------------------------------------\r\n// - ButtonBehavior() [Internal]\r\n// - Button()\r\n// - SmallButton()\r\n// - InvisibleButton()\r\n// - ArrowButton()\r\n// - CloseButton() [Internal]\r\n// - CollapseButton() [Internal]\r\n// - GetWindowScrollbarID() [Internal]\r\n// - GetWindowScrollbarRect() [Internal]\r\n// - Scrollbar() [Internal]\r\n// - ScrollbarEx() [Internal]\r\n// - Image()\r\n// - ImageButton()\r\n// - Checkbox()\r\n// - CheckboxFlagsT() [Internal]\r\n// - CheckboxFlags()\r\n// - RadioButton()\r\n// - ProgressBar()\r\n// - Bullet()\r\n//-------------------------------------------------------------------------\r\n\r\n// The ButtonBehavior() function is key to many interactions and used by many/most widgets.\r\n// Because we handle so many cases (keyboard/gamepad navigation, drag and drop) and many specific behavior (via ImGuiButtonFlags_),\r\n// this code is a little complex.\r\n// By far the most common path is interacting with the Mouse using the default ImGuiButtonFlags_PressedOnClickRelease button behavior.\r\n// See the series of events below and the corresponding state reported by dear imgui:\r\n//------------------------------------------------------------------------------------------------------------------------------------------------\r\n// with PressedOnClickRelease:             return-value  IsItemHovered()  IsItemActive()  IsItemActivated()  IsItemDeactivated()  IsItemClicked()\r\n//   Frame N+0 (mouse is outside bb)        -             -                -               -                  -                    -\r\n//   Frame N+1 (mouse moves inside bb)      -             true             -               -                  -                    -\r\n//   Frame N+2 (mouse button is down)       -             true             true            true               -                    true\r\n//   Frame N+3 (mouse button is down)       -             true             true            -                  -                    -\r\n//   Frame N+4 (mouse moves outside bb)     -             -                true            -                  -                    -\r\n//   Frame N+5 (mouse moves inside bb)      -             true             true            -                  -                    -\r\n//   Frame N+6 (mouse button is released)   true          true             -               -                  true                 -\r\n//   Frame N+7 (mouse button is released)   -             true             -               -                  -                    -\r\n//   Frame N+8 (mouse moves outside bb)     -             -                -               -                  -                    -\r\n//------------------------------------------------------------------------------------------------------------------------------------------------\r\n// with PressedOnClick:                    return-value  IsItemHovered()  IsItemActive()  IsItemActivated()  IsItemDeactivated()  IsItemClicked()\r\n//   Frame N+2 (mouse button is down)       true          true             true            true               -                    true\r\n//   Frame N+3 (mouse button is down)       -             true             true            -                  -                    -\r\n//   Frame N+6 (mouse button is released)   -             true             -               -                  true                 -\r\n//   Frame N+7 (mouse button is released)   -             true             -               -                  -                    -\r\n//------------------------------------------------------------------------------------------------------------------------------------------------\r\n// with PressedOnRelease:                  return-value  IsItemHovered()  IsItemActive()  IsItemActivated()  IsItemDeactivated()  IsItemClicked()\r\n//   Frame N+2 (mouse button is down)       -             true             -               -                  -                    true\r\n//   Frame N+3 (mouse button is down)       -             true             -               -                  -                    -\r\n//   Frame N+6 (mouse button is released)   true          true             -               -                  -                    -\r\n//   Frame N+7 (mouse button is released)   -             true             -               -                  -                    -\r\n//------------------------------------------------------------------------------------------------------------------------------------------------\r\n// with PressedOnDoubleClick:              return-value  IsItemHovered()  IsItemActive()  IsItemActivated()  IsItemDeactivated()  IsItemClicked()\r\n//   Frame N+0 (mouse button is down)       -             true             -               -                  -                    true\r\n//   Frame N+1 (mouse button is down)       -             true             -               -                  -                    -\r\n//   Frame N+2 (mouse button is released)   -             true             -               -                  -                    -\r\n//   Frame N+3 (mouse button is released)   -             true             -               -                  -                    -\r\n//   Frame N+4 (mouse button is down)       true          true             true            true               -                    true\r\n//   Frame N+5 (mouse button is down)       -             true             true            -                  -                    -\r\n//   Frame N+6 (mouse button is released)   -             true             -               -                  true                 -\r\n//   Frame N+7 (mouse button is released)   -             true             -               -                  -                    -\r\n//------------------------------------------------------------------------------------------------------------------------------------------------\r\n// Note that some combinations are supported,\r\n// - PressedOnDragDropHold can generally be associated with any flag.\r\n// - PressedOnDoubleClick can be associated by PressedOnClickRelease/PressedOnRelease, in which case the second release event won't be reported.\r\n//------------------------------------------------------------------------------------------------------------------------------------------------\r\n// The behavior of the return-value changes when ImGuiButtonFlags_Repeat is set:\r\n//                                         Repeat+                  Repeat+           Repeat+             Repeat+\r\n//                                         PressedOnClickRelease    PressedOnClick    PressedOnRelease    PressedOnDoubleClick\r\n//-------------------------------------------------------------------------------------------------------------------------------------------------\r\n//   Frame N+0 (mouse button is down)       -                        true              -                   true\r\n//   ...                                    -                        -                 -                   -\r\n//   Frame N + RepeatDelay                  true                     true              -                   true\r\n//   ...                                    -                        -                 -                   -\r\n//   Frame N + RepeatDelay + RepeatRate*N   true                     true              -                   true\r\n//-------------------------------------------------------------------------------------------------------------------------------------------------\r\n\r\nbool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n\r\n    // Default only reacts to left mouse button\r\n    if ((flags & ImGuiButtonFlags_MouseButtonMask_) == 0)\r\n        flags |= ImGuiButtonFlags_MouseButtonDefault_;\r\n\r\n    // Default behavior requires click + release inside bounding box\r\n    if ((flags & ImGuiButtonFlags_PressedOnMask_) == 0)\r\n        flags |= ImGuiButtonFlags_PressedOnDefault_;\r\n\r\n    ImGuiWindow* backup_hovered_window = g.HoveredWindow;\r\n    const bool flatten_hovered_children = (flags & ImGuiButtonFlags_FlattenChildren) && g.HoveredWindow && g.HoveredWindow->RootWindow == window;\r\n    if (flatten_hovered_children)\r\n        g.HoveredWindow = window;\r\n\r\n#ifdef IMGUI_ENABLE_TEST_ENGINE\r\n    if (id != 0 && g.LastItemData.ID != id)\r\n        IMGUI_TEST_ENGINE_ITEM_ADD(bb, id);\r\n#endif\r\n\r\n    bool pressed = false;\r\n    bool hovered = ItemHoverable(bb, id);\r\n\r\n    // Drag source doesn't report as hovered\r\n    if (hovered && g.DragDropActive && g.DragDropPayload.SourceId == id && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoDisableHover))\r\n        hovered = false;\r\n\r\n    // Special mode for Drag and Drop where holding button pressed for a long time while dragging another item triggers the button\r\n    if (g.DragDropActive && (flags & ImGuiButtonFlags_PressedOnDragDropHold) && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoHoldToOpenOthers))\r\n        if (IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))\r\n        {\r\n            hovered = true;\r\n            SetHoveredID(id);\r\n            if (g.HoveredIdTimer - g.IO.DeltaTime <= DRAGDROP_HOLD_TO_OPEN_TIMER && g.HoveredIdTimer >= DRAGDROP_HOLD_TO_OPEN_TIMER)\r\n            {\r\n                pressed = true;\r\n                g.DragDropHoldJustPressedId = id;\r\n                FocusWindow(window);\r\n            }\r\n        }\r\n\r\n    if (flatten_hovered_children)\r\n        g.HoveredWindow = backup_hovered_window;\r\n\r\n    // AllowOverlap mode (rarely used) requires previous frame HoveredId to be null or to match. This allows using patterns where a later submitted widget overlaps a previous one.\r\n    if (hovered && (flags & ImGuiButtonFlags_AllowItemOverlap) && (g.HoveredIdPreviousFrame != id && g.HoveredIdPreviousFrame != 0))\r\n        hovered = false;\r\n\r\n    // Mouse handling\r\n    if (hovered)\r\n    {\r\n        if (!(flags & ImGuiButtonFlags_NoKeyModifiers) || (!g.IO.KeyCtrl && !g.IO.KeyShift && !g.IO.KeyAlt))\r\n        {\r\n            // Poll buttons\r\n            int mouse_button_clicked = -1;\r\n            int mouse_button_released = -1;\r\n            if ((flags & ImGuiButtonFlags_MouseButtonLeft) && g.IO.MouseClicked[0])         { mouse_button_clicked = 0; }\r\n            else if ((flags & ImGuiButtonFlags_MouseButtonRight) && g.IO.MouseClicked[1])   { mouse_button_clicked = 1; }\r\n            else if ((flags & ImGuiButtonFlags_MouseButtonMiddle) && g.IO.MouseClicked[2])  { mouse_button_clicked = 2; }\r\n            if ((flags & ImGuiButtonFlags_MouseButtonLeft) && g.IO.MouseReleased[0])        { mouse_button_released = 0; }\r\n            else if ((flags & ImGuiButtonFlags_MouseButtonRight) && g.IO.MouseReleased[1])  { mouse_button_released = 1; }\r\n            else if ((flags & ImGuiButtonFlags_MouseButtonMiddle) && g.IO.MouseReleased[2]) { mouse_button_released = 2; }\r\n\r\n            if (mouse_button_clicked != -1 && g.ActiveId != id)\r\n            {\r\n                if (flags & (ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClickReleaseAnywhere))\r\n                {\r\n                    SetActiveID(id, window);\r\n                    g.ActiveIdMouseButton = mouse_button_clicked;\r\n                    if (!(flags & ImGuiButtonFlags_NoNavFocus))\r\n                        SetFocusID(id, window);\r\n                    FocusWindow(window);\r\n                }\r\n                if ((flags & ImGuiButtonFlags_PressedOnClick) || ((flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseClickedCount[mouse_button_clicked] == 2))\r\n                {\r\n                    pressed = true;\r\n                    if (flags & ImGuiButtonFlags_NoHoldingActiveId)\r\n                        ClearActiveID();\r\n                    else\r\n                        SetActiveID(id, window); // Hold on ID\r\n                    if (!(flags & ImGuiButtonFlags_NoNavFocus))\r\n                        SetFocusID(id, window);\r\n                    g.ActiveIdMouseButton = mouse_button_clicked;\r\n                    FocusWindow(window);\r\n                }\r\n            }\r\n            if ((flags & ImGuiButtonFlags_PressedOnRelease) && mouse_button_released != -1)\r\n            {\r\n                // Repeat mode trumps on release behavior\r\n                const bool has_repeated_at_least_once = (flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[mouse_button_released] >= g.IO.KeyRepeatDelay;\r\n                if (!has_repeated_at_least_once)\r\n                    pressed = true;\r\n                if (!(flags & ImGuiButtonFlags_NoNavFocus))\r\n                    SetFocusID(id, window);\r\n                ClearActiveID();\r\n            }\r\n\r\n            // 'Repeat' mode acts when held regardless of _PressedOn flags (see table above).\r\n            // Relies on repeat logic of IsMouseClicked() but we may as well do it ourselves if we end up exposing finer RepeatDelay/RepeatRate settings.\r\n            if (g.ActiveId == id && (flags & ImGuiButtonFlags_Repeat))\r\n                if (g.IO.MouseDownDuration[g.ActiveIdMouseButton] > 0.0f && IsMouseClicked(g.ActiveIdMouseButton, true))\r\n                    pressed = true;\r\n        }\r\n\r\n        if (pressed)\r\n            g.NavDisableHighlight = true;\r\n    }\r\n\r\n    // Gamepad/Keyboard navigation\r\n    // We report navigated item as hovered but we don't set g.HoveredId to not interfere with mouse.\r\n    if (g.NavId == id && !g.NavDisableHighlight && g.NavDisableMouseHover && (g.ActiveId == 0 || g.ActiveId == id || g.ActiveId == window->MoveId))\r\n        if (!(flags & ImGuiButtonFlags_NoHoveredOnFocus))\r\n            hovered = true;\r\n    if (g.NavActivateDownId == id)\r\n    {\r\n        bool nav_activated_by_code = (g.NavActivateId == id);\r\n        bool nav_activated_by_inputs = IsNavInputTest(ImGuiNavInput_Activate, (flags & ImGuiButtonFlags_Repeat) ? ImGuiInputReadMode_Repeat : ImGuiInputReadMode_Pressed);\r\n        if (nav_activated_by_code || nav_activated_by_inputs)\r\n        {\r\n            // Set active id so it can be queried by user via IsItemActive(), equivalent of holding the mouse button.\r\n            pressed = true;\r\n            SetActiveID(id, window);\r\n            g.ActiveIdSource = ImGuiInputSource_Nav;\r\n            if (!(flags & ImGuiButtonFlags_NoNavFocus))\r\n                SetFocusID(id, window);\r\n        }\r\n    }\r\n\r\n    // Process while held\r\n    bool held = false;\r\n    if (g.ActiveId == id)\r\n    {\r\n        if (g.ActiveIdSource == ImGuiInputSource_Mouse)\r\n        {\r\n            if (g.ActiveIdIsJustActivated)\r\n                g.ActiveIdClickOffset = g.IO.MousePos - bb.Min;\r\n\r\n            const int mouse_button = g.ActiveIdMouseButton;\r\n            IM_ASSERT(mouse_button >= 0 && mouse_button < ImGuiMouseButton_COUNT);\r\n            if (g.IO.MouseDown[mouse_button])\r\n            {\r\n                held = true;\r\n            }\r\n            else\r\n            {\r\n                bool release_in = hovered && (flags & ImGuiButtonFlags_PressedOnClickRelease) != 0;\r\n                bool release_anywhere = (flags & ImGuiButtonFlags_PressedOnClickReleaseAnywhere) != 0;\r\n                if ((release_in || release_anywhere) && !g.DragDropActive)\r\n                {\r\n                    // Report as pressed when releasing the mouse (this is the most common path)\r\n                    bool is_double_click_release = (flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseReleased[mouse_button] && g.IO.MouseClickedLastCount[mouse_button] == 2;\r\n                    bool is_repeating_already = (flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[mouse_button] >= g.IO.KeyRepeatDelay; // Repeat mode trumps <on release>\r\n                    if (!is_double_click_release && !is_repeating_already)\r\n                        pressed = true;\r\n                }\r\n                ClearActiveID();\r\n            }\r\n            if (!(flags & ImGuiButtonFlags_NoNavFocus))\r\n                g.NavDisableHighlight = true;\r\n        }\r\n        else if (g.ActiveIdSource == ImGuiInputSource_Nav)\r\n        {\r\n            // When activated using Nav, we hold on the ActiveID until activation button is released\r\n            if (g.NavActivateDownId != id)\r\n                ClearActiveID();\r\n        }\r\n        if (pressed)\r\n            g.ActiveIdHasBeenPressedBefore = true;\r\n    }\r\n\r\n    if (out_hovered) *out_hovered = hovered;\r\n    if (out_held) *out_held = held;\r\n\r\n    return pressed;\r\n}\r\n\r\nbool ImGui::ButtonEx(const char* label, const ImVec2& size_arg, ImGuiButtonFlags flags)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return false;\r\n\r\n    ImGuiContext& g = *GImGui;\r\n    const ImGuiStyle& style = g.Style;\r\n    const ImGuiID id = window->GetID(label);\r\n    const ImVec2 label_size = CalcTextSize(label, NULL, true);\r\n\r\n    ImVec2 pos = window->DC.CursorPos;\r\n    if ((flags & ImGuiButtonFlags_AlignTextBaseLine) && style.FramePadding.y < window->DC.CurrLineTextBaseOffset) // Try to vertically align buttons that are smaller/have no padding so that text baseline matches (bit hacky, since it shouldn't be a flag)\r\n        pos.y += window->DC.CurrLineTextBaseOffset - style.FramePadding.y;\r\n    ImVec2 size = CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0f, label_size.y + style.FramePadding.y * 2.0f);\r\n\r\n    const ImRect bb(pos, pos + size);\r\n    ItemSize(size, style.FramePadding.y);\r\n    if (!ItemAdd(bb, id))\r\n        return false;\r\n\r\n    if (g.LastItemData.InFlags & ImGuiItemFlags_ButtonRepeat)\r\n        flags |= ImGuiButtonFlags_Repeat;\r\n\r\n    bool hovered, held;\r\n    bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);\r\n\r\n    // Render\r\n    const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);\r\n    RenderNavHighlight(bb, id);\r\n    RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding);\r\n\r\n    if (g.LogEnabled)\r\n        LogSetNextTextDecoration(\"[\", \"]\");\r\n    RenderTextClipped(bb.Min + style.FramePadding, bb.Max - style.FramePadding, label, NULL, &label_size, style.ButtonTextAlign, &bb);\r\n\r\n    // Automatically close popups\r\n    //if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup))\r\n    //    CloseCurrentPopup();\r\n\r\n    IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags);\r\n    return pressed;\r\n}\r\n\r\nbool ImGui::Button(const char* label, const ImVec2& size_arg)\r\n{\r\n    return ButtonEx(label, size_arg, ImGuiButtonFlags_None);\r\n}\r\n\r\n// Small buttons fits within text without additional vertical spacing.\r\nbool ImGui::SmallButton(const char* label)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    float backup_padding_y = g.Style.FramePadding.y;\r\n    g.Style.FramePadding.y = 0.0f;\r\n    bool pressed = ButtonEx(label, ImVec2(0, 0), ImGuiButtonFlags_AlignTextBaseLine);\r\n    g.Style.FramePadding.y = backup_padding_y;\r\n    return pressed;\r\n}\r\n\r\n// Tip: use ImGui::PushID()/PopID() to push indices or pointers in the ID stack.\r\n// Then you can keep 'str_id' empty or the same for all your buttons (instead of creating a string based on a non-string id)\r\nbool ImGui::InvisibleButton(const char* str_id, const ImVec2& size_arg, ImGuiButtonFlags flags)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return false;\r\n\r\n    // Cannot use zero-size for InvisibleButton(). Unlike Button() there is not way to fallback using the label size.\r\n    IM_ASSERT(size_arg.x != 0.0f && size_arg.y != 0.0f);\r\n\r\n    const ImGuiID id = window->GetID(str_id);\r\n    ImVec2 size = CalcItemSize(size_arg, 0.0f, 0.0f);\r\n    const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);\r\n    ItemSize(size);\r\n    if (!ItemAdd(bb, id))\r\n        return false;\r\n\r\n    bool hovered, held;\r\n    bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);\r\n\r\n    IMGUI_TEST_ENGINE_ITEM_INFO(id, str_id, g.LastItemData.StatusFlags);\r\n    return pressed;\r\n}\r\n\r\nbool ImGui::ArrowButtonEx(const char* str_id, ImGuiDir dir, ImVec2 size, ImGuiButtonFlags flags)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return false;\r\n\r\n    const ImGuiID id = window->GetID(str_id);\r\n    const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);\r\n    const float default_size = GetFrameHeight();\r\n    ItemSize(size, (size.y >= default_size) ? g.Style.FramePadding.y : -1.0f);\r\n    if (!ItemAdd(bb, id))\r\n        return false;\r\n\r\n    if (g.LastItemData.InFlags & ImGuiItemFlags_ButtonRepeat)\r\n        flags |= ImGuiButtonFlags_Repeat;\r\n\r\n    bool hovered, held;\r\n    bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);\r\n\r\n    // Render\r\n    const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);\r\n    const ImU32 text_col = GetColorU32(ImGuiCol_Text);\r\n    RenderNavHighlight(bb, id);\r\n    RenderFrame(bb.Min, bb.Max, bg_col, true, g.Style.FrameRounding);\r\n    RenderArrow(window->DrawList, bb.Min + ImVec2(ImMax(0.0f, (size.x - g.FontSize) * 0.5f), ImMax(0.0f, (size.y - g.FontSize) * 0.5f)), text_col, dir);\r\n\r\n    IMGUI_TEST_ENGINE_ITEM_INFO(id, str_id, g.LastItemData.StatusFlags);\r\n    return pressed;\r\n}\r\n\r\nbool ImGui::ArrowButton(const char* str_id, ImGuiDir dir)\r\n{\r\n    float sz = GetFrameHeight();\r\n    return ArrowButtonEx(str_id, dir, ImVec2(sz, sz), ImGuiButtonFlags_None);\r\n}\r\n\r\n// Button to close a window\r\nbool ImGui::CloseButton(ImGuiID id, const ImVec2& pos)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n\r\n    // Tweak 1: Shrink hit-testing area if button covers an abnormally large proportion of the visible region. That's in order to facilitate moving the window away. (#3825)\r\n    // This may better be applied as a general hit-rect reduction mechanism for all widgets to ensure the area to move window is always accessible?\r\n    const ImRect bb(pos, pos + ImVec2(g.FontSize, g.FontSize) + g.Style.FramePadding * 2.0f);\r\n    ImRect bb_interact = bb;\r\n    const float area_to_visible_ratio = window->OuterRectClipped.GetArea() / bb.GetArea();\r\n    if (area_to_visible_ratio < 1.5f)\r\n        bb_interact.Expand(ImFloor(bb_interact.GetSize() * -0.25f));\r\n\r\n    // Tweak 2: We intentionally allow interaction when clipped so that a mechanical Alt,Right,Activate sequence can always close a window.\r\n    // (this isn't the regular behavior of buttons, but it doesn't affect the user much because navigation tends to keep items visible).\r\n    bool is_clipped = !ItemAdd(bb_interact, id);\r\n\r\n    bool hovered, held;\r\n    bool pressed = ButtonBehavior(bb_interact, id, &hovered, &held);\r\n    if (is_clipped)\r\n        return pressed;\r\n\r\n    // Render\r\n    // FIXME: Clarify this mess\r\n    ImU32 col = GetColorU32(held ? ImGuiCol_ButtonActive : ImGuiCol_ButtonHovered);\r\n    ImVec2 center = bb.GetCenter();\r\n    if (hovered)\r\n        window->DrawList->AddCircleFilled(center, ImMax(2.0f, g.FontSize * 0.5f + 1.0f), col, 12);\r\n\r\n    float cross_extent = g.FontSize * 0.5f * 0.7071f - 1.0f;\r\n    ImU32 cross_col = GetColorU32(ImGuiCol_Text);\r\n    center -= ImVec2(0.5f, 0.5f);\r\n    window->DrawList->AddLine(center + ImVec2(+cross_extent, +cross_extent), center + ImVec2(-cross_extent, -cross_extent), cross_col, 1.0f);\r\n    window->DrawList->AddLine(center + ImVec2(+cross_extent, -cross_extent), center + ImVec2(-cross_extent, +cross_extent), cross_col, 1.0f);\r\n\r\n    return pressed;\r\n}\r\n\r\nbool ImGui::CollapseButton(ImGuiID id, const ImVec2& pos)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n\r\n    ImRect bb(pos, pos + ImVec2(g.FontSize, g.FontSize) + g.Style.FramePadding * 2.0f);\r\n    ItemAdd(bb, id);\r\n    bool hovered, held;\r\n    bool pressed = ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_None);\r\n\r\n    // Render\r\n    ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);\r\n    ImU32 text_col = GetColorU32(ImGuiCol_Text);\r\n    ImVec2 center = bb.GetCenter();\r\n    if (hovered || held)\r\n        window->DrawList->AddCircleFilled(center/*+ ImVec2(0.0f, -0.5f)*/, g.FontSize * 0.5f + 1.0f, bg_col, 12);\r\n    RenderArrow(window->DrawList, bb.Min + g.Style.FramePadding, text_col, window->Collapsed ? ImGuiDir_Right : ImGuiDir_Down, 1.0f);\r\n\r\n    // Switch to moving the window after mouse is moved beyond the initial drag threshold\r\n    if (IsItemActive() && IsMouseDragging(0))\r\n        StartMouseMovingWindow(window);\r\n\r\n    return pressed;\r\n}\r\n\r\nImGuiID ImGui::GetWindowScrollbarID(ImGuiWindow* window, ImGuiAxis axis)\r\n{\r\n    return window->GetIDNoKeepAlive(axis == ImGuiAxis_X ? \"#SCROLLX\" : \"#SCROLLY\");\r\n}\r\n\r\n// Return scrollbar rectangle, must only be called for corresponding axis if window->ScrollbarX/Y is set.\r\nImRect ImGui::GetWindowScrollbarRect(ImGuiWindow* window, ImGuiAxis axis)\r\n{\r\n    const ImRect outer_rect = window->Rect();\r\n    const ImRect inner_rect = window->InnerRect;\r\n    const float border_size = window->WindowBorderSize;\r\n    const float scrollbar_size = window->ScrollbarSizes[axis ^ 1]; // (ScrollbarSizes.x = width of Y scrollbar; ScrollbarSizes.y = height of X scrollbar)\r\n    IM_ASSERT(scrollbar_size > 0.0f);\r\n    if (axis == ImGuiAxis_X)\r\n        return ImRect(inner_rect.Min.x, ImMax(outer_rect.Min.y, outer_rect.Max.y - border_size - scrollbar_size), inner_rect.Max.x, outer_rect.Max.y);\r\n    else\r\n        return ImRect(ImMax(outer_rect.Min.x, outer_rect.Max.x - border_size - scrollbar_size), inner_rect.Min.y, outer_rect.Max.x, inner_rect.Max.y);\r\n}\r\n\r\nvoid ImGui::Scrollbar(ImGuiAxis axis)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n\r\n    const ImGuiID id = GetWindowScrollbarID(window, axis);\r\n    KeepAliveID(id);\r\n\r\n    // Calculate scrollbar bounding box\r\n    ImRect bb = GetWindowScrollbarRect(window, axis);\r\n    ImDrawFlags rounding_corners = ImDrawFlags_RoundCornersNone;\r\n    if (axis == ImGuiAxis_X)\r\n    {\r\n        rounding_corners |= ImDrawFlags_RoundCornersBottomLeft;\r\n        if (!window->ScrollbarY)\r\n            rounding_corners |= ImDrawFlags_RoundCornersBottomRight;\r\n    }\r\n    else\r\n    {\r\n        if ((window->Flags & ImGuiWindowFlags_NoTitleBar) && !(window->Flags & ImGuiWindowFlags_MenuBar))\r\n            rounding_corners |= ImDrawFlags_RoundCornersTopRight;\r\n        if (!window->ScrollbarX)\r\n            rounding_corners |= ImDrawFlags_RoundCornersBottomRight;\r\n    }\r\n    float size_avail = window->InnerRect.Max[axis] - window->InnerRect.Min[axis];\r\n    float size_contents = window->ContentSize[axis] + window->WindowPadding[axis] * 2.0f;\r\n    ImS64 scroll = (ImS64)window->Scroll[axis];\r\n    ScrollbarEx(bb, id, axis, &scroll, (ImS64)size_avail, (ImS64)size_contents, rounding_corners);\r\n    window->Scroll[axis] = (float)scroll;\r\n}\r\n\r\n// Vertical/Horizontal scrollbar\r\n// The entire piece of code below is rather confusing because:\r\n// - We handle absolute seeking (when first clicking outside the grab) and relative manipulation (afterward or when clicking inside the grab)\r\n// - We store values as normalized ratio and in a form that allows the window content to change while we are holding on a scrollbar\r\n// - We handle both horizontal and vertical scrollbars, which makes the terminology not ideal.\r\n// Still, the code should probably be made simpler..\r\nbool ImGui::ScrollbarEx(const ImRect& bb_frame, ImGuiID id, ImGuiAxis axis, ImS64* p_scroll_v, ImS64 size_avail_v, ImS64 size_contents_v, ImDrawFlags flags)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    if (window->SkipItems)\r\n        return false;\r\n\r\n    const float bb_frame_width = bb_frame.GetWidth();\r\n    const float bb_frame_height = bb_frame.GetHeight();\r\n    if (bb_frame_width <= 0.0f || bb_frame_height <= 0.0f)\r\n        return false;\r\n\r\n    // When we are too small, start hiding and disabling the grab (this reduce visual noise on very small window and facilitate using the window resize grab)\r\n    float alpha = 1.0f;\r\n    if ((axis == ImGuiAxis_Y) && bb_frame_height < g.FontSize + g.Style.FramePadding.y * 2.0f)\r\n        alpha = ImSaturate((bb_frame_height - g.FontSize) / (g.Style.FramePadding.y * 2.0f));\r\n    if (alpha <= 0.0f)\r\n        return false;\r\n\r\n    const ImGuiStyle& style = g.Style;\r\n    const bool allow_interaction = (alpha >= 1.0f);\r\n\r\n    ImRect bb = bb_frame;\r\n    bb.Expand(ImVec2(-ImClamp(IM_FLOOR((bb_frame_width - 2.0f) * 0.5f), 0.0f, 3.0f), -ImClamp(IM_FLOOR((bb_frame_height - 2.0f) * 0.5f), 0.0f, 3.0f)));\r\n\r\n    // V denote the main, longer axis of the scrollbar (= height for a vertical scrollbar)\r\n    const float scrollbar_size_v = (axis == ImGuiAxis_X) ? bb.GetWidth() : bb.GetHeight();\r\n\r\n    // Calculate the height of our grabbable box. It generally represent the amount visible (vs the total scrollable amount)\r\n    // But we maintain a minimum size in pixel to allow for the user to still aim inside.\r\n    IM_ASSERT(ImMax(size_contents_v, size_avail_v) > 0.0f); // Adding this assert to check if the ImMax(XXX,1.0f) is still needed. PLEASE CONTACT ME if this triggers.\r\n    const ImS64 win_size_v = ImMax(ImMax(size_contents_v, size_avail_v), (ImS64)1);\r\n    const float grab_h_pixels = ImClamp(scrollbar_size_v * ((float)size_avail_v / (float)win_size_v), style.GrabMinSize, scrollbar_size_v);\r\n    const float grab_h_norm = grab_h_pixels / scrollbar_size_v;\r\n\r\n    // Handle input right away. None of the code of Begin() is relying on scrolling position before calling Scrollbar().\r\n    bool held = false;\r\n    bool hovered = false;\r\n    ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_NoNavFocus);\r\n\r\n    const ImS64 scroll_max = ImMax((ImS64)1, size_contents_v - size_avail_v);\r\n    float scroll_ratio = ImSaturate((float)*p_scroll_v / (float)scroll_max);\r\n    float grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v; // Grab position in normalized space\r\n    if (held && allow_interaction && grab_h_norm < 1.0f)\r\n    {\r\n        const float scrollbar_pos_v = bb.Min[axis];\r\n        const float mouse_pos_v = g.IO.MousePos[axis];\r\n\r\n        // Click position in scrollbar normalized space (0.0f->1.0f)\r\n        const float clicked_v_norm = ImSaturate((mouse_pos_v - scrollbar_pos_v) / scrollbar_size_v);\r\n        SetHoveredID(id);\r\n\r\n        bool seek_absolute = false;\r\n        if (g.ActiveIdIsJustActivated)\r\n        {\r\n            // On initial click calculate the distance between mouse and the center of the grab\r\n            seek_absolute = (clicked_v_norm < grab_v_norm || clicked_v_norm > grab_v_norm + grab_h_norm);\r\n            if (seek_absolute)\r\n                g.ScrollbarClickDeltaToGrabCenter = 0.0f;\r\n            else\r\n                g.ScrollbarClickDeltaToGrabCenter = clicked_v_norm - grab_v_norm - grab_h_norm * 0.5f;\r\n        }\r\n\r\n        // Apply scroll (p_scroll_v will generally point on one member of window->Scroll)\r\n        // It is ok to modify Scroll here because we are being called in Begin() after the calculation of ContentSize and before setting up our starting position\r\n        const float scroll_v_norm = ImSaturate((clicked_v_norm - g.ScrollbarClickDeltaToGrabCenter - grab_h_norm * 0.5f) / (1.0f - grab_h_norm));\r\n        *p_scroll_v = (ImS64)(scroll_v_norm * scroll_max);\r\n\r\n        // Update values for rendering\r\n        scroll_ratio = ImSaturate((float)*p_scroll_v / (float)scroll_max);\r\n        grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v;\r\n\r\n        // Update distance to grab now that we have seeked and saturated\r\n        if (seek_absolute)\r\n            g.ScrollbarClickDeltaToGrabCenter = clicked_v_norm - grab_v_norm - grab_h_norm * 0.5f;\r\n    }\r\n\r\n    // Render\r\n    const ImU32 bg_col = GetColorU32(ImGuiCol_ScrollbarBg);\r\n    const ImU32 grab_col = GetColorU32(held ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_ScrollbarGrab, alpha);\r\n    window->DrawList->AddRectFilled(bb_frame.Min, bb_frame.Max, bg_col, window->WindowRounding, flags);\r\n    ImRect grab_rect;\r\n    if (axis == ImGuiAxis_X)\r\n        grab_rect = ImRect(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm), bb.Min.y, ImLerp(bb.Min.x, bb.Max.x, grab_v_norm) + grab_h_pixels, bb.Max.y);\r\n    else\r\n        grab_rect = ImRect(bb.Min.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm), bb.Max.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm) + grab_h_pixels);\r\n    window->DrawList->AddRectFilled(grab_rect.Min, grab_rect.Max, grab_col, style.ScrollbarRounding);\r\n\r\n    return held;\r\n}\r\n\r\nvoid ImGui::Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return;\r\n\r\n    ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);\r\n    if (border_col.w > 0.0f)\r\n        bb.Max += ImVec2(2, 2);\r\n    ItemSize(bb);\r\n    if (!ItemAdd(bb, 0))\r\n        return;\r\n\r\n    if (border_col.w > 0.0f)\r\n    {\r\n        window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(border_col), 0.0f);\r\n        window->DrawList->AddImage(user_texture_id, bb.Min + ImVec2(1, 1), bb.Max - ImVec2(1, 1), uv0, uv1, GetColorU32(tint_col));\r\n    }\r\n    else\r\n    {\r\n        window->DrawList->AddImage(user_texture_id, bb.Min, bb.Max, uv0, uv1, GetColorU32(tint_col));\r\n    }\r\n}\r\n\r\n// ImageButton() is flawed as 'id' is always derived from 'texture_id' (see #2464 #1390)\r\n// We provide this internal helper to write your own variant while we figure out how to redesign the public ImageButton() API.\r\nbool ImGui::ImageButtonEx(ImGuiID id, ImTextureID texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec2& padding, const ImVec4& bg_col, const ImVec4& tint_col)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return false;\r\n\r\n    const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size + padding * 2);\r\n    ItemSize(bb);\r\n    if (!ItemAdd(bb, id))\r\n        return false;\r\n\r\n    bool hovered, held;\r\n    bool pressed = ButtonBehavior(bb, id, &hovered, &held);\r\n\r\n    // Render\r\n    const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);\r\n    RenderNavHighlight(bb, id);\r\n    RenderFrame(bb.Min, bb.Max, col, true, ImClamp((float)ImMin(padding.x, padding.y), 0.0f, g.Style.FrameRounding));\r\n    if (bg_col.w > 0.0f)\r\n        window->DrawList->AddRectFilled(bb.Min + padding, bb.Max - padding, GetColorU32(bg_col));\r\n    window->DrawList->AddImage(texture_id, bb.Min + padding, bb.Max - padding, uv0, uv1, GetColorU32(tint_col));\r\n\r\n    return pressed;\r\n}\r\n\r\n// frame_padding < 0: uses FramePadding from style (default)\r\n// frame_padding = 0: no framing\r\n// frame_padding > 0: set framing size\r\nbool ImGui::ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, int frame_padding, const ImVec4& bg_col, const ImVec4& tint_col)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    if (window->SkipItems)\r\n        return false;\r\n\r\n    // Default to using texture ID as ID. User can still push string/integer prefixes.\r\n    PushID((void*)(intptr_t)user_texture_id);\r\n    const ImGuiID id = window->GetID(\"#image\");\r\n    PopID();\r\n\r\n    const ImVec2 padding = (frame_padding >= 0) ? ImVec2((float)frame_padding, (float)frame_padding) : g.Style.FramePadding;\r\n    return ImageButtonEx(id, user_texture_id, size, uv0, uv1, padding, bg_col, tint_col);\r\n}\r\n\r\nbool ImGui::Checkbox(const char* label, bool* v)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return false;\r\n\r\n    ImGuiContext& g = *GImGui;\r\n    const ImGuiStyle& style = g.Style;\r\n    const ImGuiID id = window->GetID(label);\r\n    const ImVec2 label_size = CalcTextSize(label, NULL, true);\r\n\r\n    const float square_sz = GetFrameHeight();\r\n    const ImVec2 pos = window->DC.CursorPos;\r\n    const ImRect total_bb(pos, pos + ImVec2(square_sz + (label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f), label_size.y + style.FramePadding.y * 2.0f));\r\n    ItemSize(total_bb, style.FramePadding.y);\r\n    if (!ItemAdd(total_bb, id))\r\n    {\r\n        IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Checkable | (*v ? ImGuiItemStatusFlags_Checked : 0));\r\n        return false;\r\n    }\r\n\r\n    bool hovered, held;\r\n    bool pressed = ButtonBehavior(total_bb, id, &hovered, &held);\r\n    if (pressed)\r\n    {\r\n        *v = !(*v);\r\n        MarkItemEdited(id);\r\n    }\r\n\r\n    const ImRect check_bb(pos, pos + ImVec2(square_sz, square_sz));\r\n    RenderNavHighlight(total_bb, id);\r\n    RenderFrame(check_bb.Min, check_bb.Max, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), true, style.FrameRounding);\r\n    ImU32 check_col = GetColorU32(ImGuiCol_CheckMark);\r\n    bool mixed_value = (g.LastItemData.InFlags & ImGuiItemFlags_MixedValue) != 0;\r\n    if (mixed_value)\r\n    {\r\n        // Undocumented tristate/mixed/indeterminate checkbox (#2644)\r\n        // This may seem awkwardly designed because the aim is to make ImGuiItemFlags_MixedValue supported by all widgets (not just checkbox)\r\n        ImVec2 pad(ImMax(1.0f, IM_FLOOR(square_sz / 3.6f)), ImMax(1.0f, IM_FLOOR(square_sz / 3.6f)));\r\n        window->DrawList->AddRectFilled(check_bb.Min + pad, check_bb.Max - pad, check_col, style.FrameRounding);\r\n    }\r\n    else if (*v)\r\n    {\r\n        const float pad = ImMax(1.0f, IM_FLOOR(square_sz / 6.0f));\r\n        RenderCheckMark(window->DrawList, check_bb.Min + ImVec2(pad, pad), check_col, square_sz - pad * 2.0f);\r\n    }\r\n\r\n    ImVec2 label_pos = ImVec2(check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y);\r\n    if (g.LogEnabled)\r\n        LogRenderedText(&label_pos, mixed_value ? \"[~]\" : *v ? \"[x]\" : \"[ ]\");\r\n    if (label_size.x > 0.0f)\r\n        RenderText(label_pos, label);\r\n\r\n    IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Checkable | (*v ? ImGuiItemStatusFlags_Checked : 0));\r\n    return pressed;\r\n}\r\n\r\ntemplate<typename T>\r\nbool ImGui::CheckboxFlagsT(const char* label, T* flags, T flags_value)\r\n{\r\n    bool all_on = (*flags & flags_value) == flags_value;\r\n    bool any_on = (*flags & flags_value) != 0;\r\n    bool pressed;\r\n    if (!all_on && any_on)\r\n    {\r\n        ImGuiContext& g = *GImGui;\r\n        ImGuiItemFlags backup_item_flags = g.CurrentItemFlags;\r\n        g.CurrentItemFlags |= ImGuiItemFlags_MixedValue;\r\n        pressed = Checkbox(label, &all_on);\r\n        g.CurrentItemFlags = backup_item_flags;\r\n    }\r\n    else\r\n    {\r\n        pressed = Checkbox(label, &all_on);\r\n\r\n    }\r\n    if (pressed)\r\n    {\r\n        if (all_on)\r\n            *flags |= flags_value;\r\n        else\r\n            *flags &= ~flags_value;\r\n    }\r\n    return pressed;\r\n}\r\n\r\nbool ImGui::CheckboxFlags(const char* label, int* flags, int flags_value)\r\n{\r\n    return CheckboxFlagsT(label, flags, flags_value);\r\n}\r\n\r\nbool ImGui::CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value)\r\n{\r\n    return CheckboxFlagsT(label, flags, flags_value);\r\n}\r\n\r\nbool ImGui::CheckboxFlags(const char* label, ImS64* flags, ImS64 flags_value)\r\n{\r\n    return CheckboxFlagsT(label, flags, flags_value);\r\n}\r\n\r\nbool ImGui::CheckboxFlags(const char* label, ImU64* flags, ImU64 flags_value)\r\n{\r\n    return CheckboxFlagsT(label, flags, flags_value);\r\n}\r\n\r\nbool ImGui::RadioButton(const char* label, bool active)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return false;\r\n\r\n    ImGuiContext& g = *GImGui;\r\n    const ImGuiStyle& style = g.Style;\r\n    const ImGuiID id = window->GetID(label);\r\n    const ImVec2 label_size = CalcTextSize(label, NULL, true);\r\n\r\n    const float square_sz = GetFrameHeight();\r\n    const ImVec2 pos = window->DC.CursorPos;\r\n    const ImRect check_bb(pos, pos + ImVec2(square_sz, square_sz));\r\n    const ImRect total_bb(pos, pos + ImVec2(square_sz + (label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f), label_size.y + style.FramePadding.y * 2.0f));\r\n    ItemSize(total_bb, style.FramePadding.y);\r\n    if (!ItemAdd(total_bb, id))\r\n        return false;\r\n\r\n    ImVec2 center = check_bb.GetCenter();\r\n    center.x = IM_ROUND(center.x);\r\n    center.y = IM_ROUND(center.y);\r\n    const float radius = (square_sz - 1.0f) * 0.5f;\r\n\r\n    bool hovered, held;\r\n    bool pressed = ButtonBehavior(total_bb, id, &hovered, &held);\r\n    if (pressed)\r\n        MarkItemEdited(id);\r\n\r\n    RenderNavHighlight(total_bb, id);\r\n    window->DrawList->AddCircleFilled(center, radius, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), 16);\r\n    if (active)\r\n    {\r\n        const float pad = ImMax(1.0f, IM_FLOOR(square_sz / 6.0f));\r\n        window->DrawList->AddCircleFilled(center, radius - pad, GetColorU32(ImGuiCol_CheckMark), 16);\r\n    }\r\n\r\n    if (style.FrameBorderSize > 0.0f)\r\n    {\r\n        window->DrawList->AddCircle(center + ImVec2(1, 1), radius, GetColorU32(ImGuiCol_BorderShadow), 16, style.FrameBorderSize);\r\n        window->DrawList->AddCircle(center, radius, GetColorU32(ImGuiCol_Border), 16, style.FrameBorderSize);\r\n    }\r\n\r\n    ImVec2 label_pos = ImVec2(check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y);\r\n    if (g.LogEnabled)\r\n        LogRenderedText(&label_pos, active ? \"(x)\" : \"( )\");\r\n    if (label_size.x > 0.0f)\r\n        RenderText(label_pos, label);\r\n\r\n    IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags);\r\n    return pressed;\r\n}\r\n\r\n// FIXME: This would work nicely if it was a public template, e.g. 'template<T> RadioButton(const char* label, T* v, T v_button)', but I'm not sure how we would expose it..\r\nbool ImGui::RadioButton(const char* label, int* v, int v_button)\r\n{\r\n    const bool pressed = RadioButton(label, *v == v_button);\r\n    if (pressed)\r\n        *v = v_button;\r\n    return pressed;\r\n}\r\n\r\n// size_arg (for each axis) < 0.0f: align to end, 0.0f: auto, > 0.0f: specified size\r\nvoid ImGui::ProgressBar(float fraction, const ImVec2& size_arg, const char* overlay)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return;\r\n\r\n    ImGuiContext& g = *GImGui;\r\n    const ImGuiStyle& style = g.Style;\r\n\r\n    ImVec2 pos = window->DC.CursorPos;\r\n    ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), g.FontSize + style.FramePadding.y * 2.0f);\r\n    ImRect bb(pos, pos + size);\r\n    ItemSize(size, style.FramePadding.y);\r\n    if (!ItemAdd(bb, 0))\r\n        return;\r\n\r\n    // Render\r\n    fraction = ImSaturate(fraction);\r\n    RenderFrame(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);\r\n    bb.Expand(ImVec2(-style.FrameBorderSize, -style.FrameBorderSize));\r\n    const ImVec2 fill_br = ImVec2(ImLerp(bb.Min.x, bb.Max.x, fraction), bb.Max.y);\r\n    RenderRectFilledRangeH(window->DrawList, bb, GetColorU32(ImGuiCol_PlotHistogram), 0.0f, fraction, style.FrameRounding);\r\n\r\n    // Default displaying the fraction as percentage string, but user can override it\r\n    char overlay_buf[32];\r\n    if (!overlay)\r\n    {\r\n        ImFormatString(overlay_buf, IM_ARRAYSIZE(overlay_buf), \"%.0f%%\", fraction * 100 + 0.01f);\r\n        overlay = overlay_buf;\r\n    }\r\n\r\n    ImVec2 overlay_size = CalcTextSize(overlay, NULL);\r\n    if (overlay_size.x > 0.0f)\r\n        RenderTextClipped(ImVec2(ImClamp(fill_br.x + style.ItemSpacing.x, bb.Min.x, bb.Max.x - overlay_size.x - style.ItemInnerSpacing.x), bb.Min.y), bb.Max, overlay, NULL, &overlay_size, ImVec2(0.0f, 0.5f), &bb);\r\n}\r\n\r\nvoid ImGui::Bullet()\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return;\r\n\r\n    ImGuiContext& g = *GImGui;\r\n    const ImGuiStyle& style = g.Style;\r\n    const float line_height = ImMax(ImMin(window->DC.CurrLineSize.y, g.FontSize + g.Style.FramePadding.y * 2), g.FontSize);\r\n    const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize, line_height));\r\n    ItemSize(bb);\r\n    if (!ItemAdd(bb, 0))\r\n    {\r\n        SameLine(0, style.FramePadding.x * 2);\r\n        return;\r\n    }\r\n\r\n    // Render and stay on same line\r\n    ImU32 text_col = GetColorU32(ImGuiCol_Text);\r\n    RenderBullet(window->DrawList, bb.Min + ImVec2(style.FramePadding.x + g.FontSize * 0.5f, line_height * 0.5f), text_col);\r\n    SameLine(0, style.FramePadding.x * 2.0f);\r\n}\r\n\r\n//-------------------------------------------------------------------------\r\n// [SECTION] Widgets: Low-level Layout helpers\r\n//-------------------------------------------------------------------------\r\n// - Spacing()\r\n// - Dummy()\r\n// - NewLine()\r\n// - AlignTextToFramePadding()\r\n// - SeparatorEx() [Internal]\r\n// - Separator()\r\n// - SplitterBehavior() [Internal]\r\n// - ShrinkWidths() [Internal]\r\n//-------------------------------------------------------------------------\r\n\r\nvoid ImGui::Spacing()\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return;\r\n    ItemSize(ImVec2(0, 0));\r\n}\r\n\r\nvoid ImGui::Dummy(const ImVec2& size)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return;\r\n\r\n    const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);\r\n    ItemSize(size);\r\n    ItemAdd(bb, 0);\r\n}\r\n\r\nvoid ImGui::NewLine()\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return;\r\n\r\n    ImGuiContext& g = *GImGui;\r\n    const ImGuiLayoutType backup_layout_type = window->DC.LayoutType;\r\n    window->DC.LayoutType = ImGuiLayoutType_Vertical;\r\n    if (window->DC.CurrLineSize.y > 0.0f)     // In the event that we are on a line with items that is smaller that FontSize high, we will preserve its height.\r\n        ItemSize(ImVec2(0, 0));\r\n    else\r\n        ItemSize(ImVec2(0.0f, g.FontSize));\r\n    window->DC.LayoutType = backup_layout_type;\r\n}\r\n\r\nvoid ImGui::AlignTextToFramePadding()\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return;\r\n\r\n    ImGuiContext& g = *GImGui;\r\n    window->DC.CurrLineSize.y = ImMax(window->DC.CurrLineSize.y, g.FontSize + g.Style.FramePadding.y * 2);\r\n    window->DC.CurrLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, g.Style.FramePadding.y);\r\n}\r\n\r\n// Horizontal/vertical separating line\r\nvoid ImGui::SeparatorEx(ImGuiSeparatorFlags flags)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return;\r\n\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(ImIsPowerOfTwo(flags & (ImGuiSeparatorFlags_Horizontal | ImGuiSeparatorFlags_Vertical)));   // Check that only 1 option is selected\r\n\r\n    float thickness_draw = 1.0f;\r\n    float thickness_layout = 0.0f;\r\n    if (flags & ImGuiSeparatorFlags_Vertical)\r\n    {\r\n        // Vertical separator, for menu bars (use current line height). Not exposed because it is misleading and it doesn't have an effect on regular layout.\r\n        float y1 = window->DC.CursorPos.y;\r\n        float y2 = window->DC.CursorPos.y + window->DC.CurrLineSize.y;\r\n        const ImRect bb(ImVec2(window->DC.CursorPos.x, y1), ImVec2(window->DC.CursorPos.x + thickness_draw, y2));\r\n        ItemSize(ImVec2(thickness_layout, 0.0f));\r\n        if (!ItemAdd(bb, 0))\r\n            return;\r\n\r\n        // Draw\r\n        window->DrawList->AddLine(ImVec2(bb.Min.x, bb.Min.y), ImVec2(bb.Min.x, bb.Max.y), GetColorU32(ImGuiCol_Separator));\r\n        if (g.LogEnabled)\r\n            LogText(\" |\");\r\n    }\r\n    else if (flags & ImGuiSeparatorFlags_Horizontal)\r\n    {\r\n        // Horizontal Separator\r\n        float x1 = window->Pos.x;\r\n        float x2 = window->Pos.x + window->Size.x;\r\n\r\n        // FIXME-WORKRECT: old hack (#205) until we decide of consistent behavior with WorkRect/Indent and Separator\r\n        if (g.GroupStack.Size > 0 && g.GroupStack.back().WindowID == window->ID)\r\n            x1 += window->DC.Indent.x;\r\n\r\n        // FIXME-WORKRECT: In theory we should simply be using WorkRect.Min.x/Max.x everywhere but it isn't aesthetically what we want,\r\n        // need to introduce a variant of WorkRect for that purpose. (#4787)\r\n        if (ImGuiTable* table = g.CurrentTable)\r\n        {\r\n            x1 = table->Columns[table->CurrentColumn].MinX;\r\n            x2 = table->Columns[table->CurrentColumn].MaxX;\r\n        }\r\n\r\n        ImGuiOldColumns* columns = (flags & ImGuiSeparatorFlags_SpanAllColumns) ? window->DC.CurrentColumns : NULL;\r\n        if (columns)\r\n            PushColumnsBackground();\r\n\r\n        // We don't provide our width to the layout so that it doesn't get feed back into AutoFit\r\n        // FIXME: This prevents ->CursorMaxPos based bounding box evaluation from working (e.g. TableEndCell)\r\n        const ImRect bb(ImVec2(x1, window->DC.CursorPos.y), ImVec2(x2, window->DC.CursorPos.y + thickness_draw));\r\n        ItemSize(ImVec2(0.0f, thickness_layout));\r\n        const bool item_visible = ItemAdd(bb, 0);\r\n        if (item_visible)\r\n        {\r\n            // Draw\r\n            window->DrawList->AddLine(bb.Min, ImVec2(bb.Max.x, bb.Min.y), GetColorU32(ImGuiCol_Separator));\r\n            if (g.LogEnabled)\r\n                LogRenderedText(&bb.Min, \"--------------------------------\\n\");\r\n\r\n        }\r\n        if (columns)\r\n        {\r\n            PopColumnsBackground();\r\n            columns->LineMinY = window->DC.CursorPos.y;\r\n        }\r\n    }\r\n}\r\n\r\nvoid ImGui::Separator()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    if (window->SkipItems)\r\n        return;\r\n\r\n    // Those flags should eventually be overridable by the user\r\n    ImGuiSeparatorFlags flags = (window->DC.LayoutType == ImGuiLayoutType_Horizontal) ? ImGuiSeparatorFlags_Vertical : ImGuiSeparatorFlags_Horizontal;\r\n    flags |= ImGuiSeparatorFlags_SpanAllColumns; // NB: this only applies to legacy Columns() api as they relied on Separator() a lot.\r\n    SeparatorEx(flags);\r\n}\r\n\r\n// Using 'hover_visibility_delay' allows us to hide the highlight and mouse cursor for a short time, which can be convenient to reduce visual noise.\r\nbool ImGui::SplitterBehavior(const ImRect& bb, ImGuiID id, ImGuiAxis axis, float* size1, float* size2, float min_size1, float min_size2, float hover_extend, float hover_visibility_delay)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n\r\n    const ImGuiItemFlags item_flags_backup = g.CurrentItemFlags;\r\n    g.CurrentItemFlags |= ImGuiItemFlags_NoNav | ImGuiItemFlags_NoNavDefaultFocus;\r\n    bool item_add = ItemAdd(bb, id);\r\n    g.CurrentItemFlags = item_flags_backup;\r\n    if (!item_add)\r\n        return false;\r\n\r\n    bool hovered, held;\r\n    ImRect bb_interact = bb;\r\n    bb_interact.Expand(axis == ImGuiAxis_Y ? ImVec2(0.0f, hover_extend) : ImVec2(hover_extend, 0.0f));\r\n    ButtonBehavior(bb_interact, id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_AllowItemOverlap);\r\n    if (hovered)\r\n        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredRect; // for IsItemHovered(), because bb_interact is larger than bb\r\n    if (g.ActiveId != id)\r\n        SetItemAllowOverlap();\r\n\r\n    if (held || (hovered && g.HoveredIdPreviousFrame == id && g.HoveredIdTimer >= hover_visibility_delay))\r\n        SetMouseCursor(axis == ImGuiAxis_Y ? ImGuiMouseCursor_ResizeNS : ImGuiMouseCursor_ResizeEW);\r\n\r\n    ImRect bb_render = bb;\r\n    if (held)\r\n    {\r\n        ImVec2 mouse_delta_2d = g.IO.MousePos - g.ActiveIdClickOffset - bb_interact.Min;\r\n        float mouse_delta = (axis == ImGuiAxis_Y) ? mouse_delta_2d.y : mouse_delta_2d.x;\r\n\r\n        // Minimum pane size\r\n        float size_1_maximum_delta = ImMax(0.0f, *size1 - min_size1);\r\n        float size_2_maximum_delta = ImMax(0.0f, *size2 - min_size2);\r\n        if (mouse_delta < -size_1_maximum_delta)\r\n            mouse_delta = -size_1_maximum_delta;\r\n        if (mouse_delta > size_2_maximum_delta)\r\n            mouse_delta = size_2_maximum_delta;\r\n\r\n        // Apply resize\r\n        if (mouse_delta != 0.0f)\r\n        {\r\n            if (mouse_delta < 0.0f)\r\n                IM_ASSERT(*size1 + mouse_delta >= min_size1);\r\n            if (mouse_delta > 0.0f)\r\n                IM_ASSERT(*size2 - mouse_delta >= min_size2);\r\n            *size1 += mouse_delta;\r\n            *size2 -= mouse_delta;\r\n            bb_render.Translate((axis == ImGuiAxis_X) ? ImVec2(mouse_delta, 0.0f) : ImVec2(0.0f, mouse_delta));\r\n            MarkItemEdited(id);\r\n        }\r\n    }\r\n\r\n    // Render\r\n    const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : (hovered && g.HoveredIdTimer >= hover_visibility_delay) ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator);\r\n    window->DrawList->AddRectFilled(bb_render.Min, bb_render.Max, col, 0.0f);\r\n\r\n    return held;\r\n}\r\n\r\nstatic int IMGUI_CDECL ShrinkWidthItemComparer(const void* lhs, const void* rhs)\r\n{\r\n    const ImGuiShrinkWidthItem* a = (const ImGuiShrinkWidthItem*)lhs;\r\n    const ImGuiShrinkWidthItem* b = (const ImGuiShrinkWidthItem*)rhs;\r\n    if (int d = (int)(b->Width - a->Width))\r\n        return d;\r\n    return (b->Index - a->Index);\r\n}\r\n\r\n// Shrink excess width from a set of item, by removing width from the larger items first.\r\n// Set items Width to -1.0f to disable shrinking this item.\r\nvoid ImGui::ShrinkWidths(ImGuiShrinkWidthItem* items, int count, float width_excess)\r\n{\r\n    if (count == 1)\r\n    {\r\n        if (items[0].Width >= 0.0f)\r\n            items[0].Width = ImMax(items[0].Width - width_excess, 1.0f);\r\n        return;\r\n    }\r\n    ImQsort(items, (size_t)count, sizeof(ImGuiShrinkWidthItem), ShrinkWidthItemComparer);\r\n    int count_same_width = 1;\r\n    while (width_excess > 0.0f && count_same_width < count)\r\n    {\r\n        while (count_same_width < count && items[0].Width <= items[count_same_width].Width)\r\n            count_same_width++;\r\n        float max_width_to_remove_per_item = (count_same_width < count && items[count_same_width].Width >= 0.0f) ? (items[0].Width - items[count_same_width].Width) : (items[0].Width - 1.0f);\r\n        if (max_width_to_remove_per_item <= 0.0f)\r\n            break;\r\n        float width_to_remove_per_item = ImMin(width_excess / count_same_width, max_width_to_remove_per_item);\r\n        for (int item_n = 0; item_n < count_same_width; item_n++)\r\n            items[item_n].Width -= width_to_remove_per_item;\r\n        width_excess -= width_to_remove_per_item * count_same_width;\r\n    }\r\n\r\n    // Round width and redistribute remainder left-to-right (could make it an option of the function?)\r\n    // Ensure that e.g. the right-most tab of a shrunk tab-bar always reaches exactly at the same distance from the right-most edge of the tab bar separator.\r\n    width_excess = 0.0f;\r\n    for (int n = 0; n < count; n++)\r\n    {\r\n        float width_rounded = ImFloor(items[n].Width);\r\n        width_excess += items[n].Width - width_rounded;\r\n        items[n].Width = width_rounded;\r\n    }\r\n    if (width_excess > 0.0f)\r\n        for (int n = 0; n < count; n++)\r\n            if (items[n].Index < (int)(width_excess + 0.01f))\r\n                items[n].Width += 1.0f;\r\n}\r\n\r\n//-------------------------------------------------------------------------\r\n// [SECTION] Widgets: ComboBox\r\n//-------------------------------------------------------------------------\r\n// - CalcMaxPopupHeightFromItemCount() [Internal]\r\n// - BeginCombo()\r\n// - BeginComboPopup() [Internal]\r\n// - EndCombo()\r\n// - BeginComboPreview() [Internal]\r\n// - EndComboPreview() [Internal]\r\n// - Combo()\r\n//-------------------------------------------------------------------------\r\n\r\nstatic float CalcMaxPopupHeightFromItemCount(int items_count)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    if (items_count <= 0)\r\n        return FLT_MAX;\r\n    return (g.FontSize + g.Style.ItemSpacing.y) * items_count - g.Style.ItemSpacing.y + (g.Style.WindowPadding.y * 2);\r\n}\r\n\r\nbool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboFlags flags)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n\r\n    ImGuiNextWindowDataFlags backup_next_window_data_flags = g.NextWindowData.Flags;\r\n    g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values\r\n    if (window->SkipItems)\r\n        return false;\r\n\r\n    const ImGuiStyle& style = g.Style;\r\n    const ImGuiID id = window->GetID(label);\r\n    IM_ASSERT((flags & (ImGuiComboFlags_NoArrowButton | ImGuiComboFlags_NoPreview)) != (ImGuiComboFlags_NoArrowButton | ImGuiComboFlags_NoPreview)); // Can't use both flags together\r\n\r\n    const float arrow_size = (flags & ImGuiComboFlags_NoArrowButton) ? 0.0f : GetFrameHeight();\r\n    const ImVec2 label_size = CalcTextSize(label, NULL, true);\r\n    const float w = (flags & ImGuiComboFlags_NoPreview) ? arrow_size : CalcItemWidth();\r\n    const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y * 2.0f));\r\n    const ImRect total_bb(bb.Min, bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));\r\n    ItemSize(total_bb, style.FramePadding.y);\r\n    if (!ItemAdd(total_bb, id, &bb))\r\n        return false;\r\n\r\n    // Open on click\r\n    bool hovered, held;\r\n    bool pressed = ButtonBehavior(bb, id, &hovered, &held);\r\n    const ImGuiID popup_id = ImHashStr(\"##ComboPopup\", 0, id);\r\n    bool popup_open = IsPopupOpen(popup_id, ImGuiPopupFlags_None);\r\n    if (pressed && !popup_open)\r\n    {\r\n        OpenPopupEx(popup_id, ImGuiPopupFlags_None);\r\n        popup_open = true;\r\n    }\r\n\r\n    // Render shape\r\n    const ImU32 frame_col = GetColorU32(hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);\r\n    const float value_x2 = ImMax(bb.Min.x, bb.Max.x - arrow_size);\r\n    RenderNavHighlight(bb, id);\r\n    if (!(flags & ImGuiComboFlags_NoPreview))\r\n        window->DrawList->AddRectFilled(bb.Min, ImVec2(value_x2, bb.Max.y), frame_col, style.FrameRounding, (flags & ImGuiComboFlags_NoArrowButton) ? ImDrawFlags_RoundCornersAll : ImDrawFlags_RoundCornersLeft);\r\n    if (!(flags & ImGuiComboFlags_NoArrowButton))\r\n    {\r\n        ImU32 bg_col = GetColorU32((popup_open || hovered) ? ImGuiCol_ButtonHovered : ImGuiCol_Button);\r\n        ImU32 text_col = GetColorU32(ImGuiCol_Text);\r\n        window->DrawList->AddRectFilled(ImVec2(value_x2, bb.Min.y), bb.Max, bg_col, style.FrameRounding, (w <= arrow_size) ? ImDrawFlags_RoundCornersAll : ImDrawFlags_RoundCornersRight);\r\n        if (value_x2 + arrow_size - style.FramePadding.x <= bb.Max.x)\r\n            RenderArrow(window->DrawList, ImVec2(value_x2 + style.FramePadding.y, bb.Min.y + style.FramePadding.y), text_col, ImGuiDir_Down, 1.0f);\r\n    }\r\n    RenderFrameBorder(bb.Min, bb.Max, style.FrameRounding);\r\n\r\n    // Custom preview\r\n    if (flags & ImGuiComboFlags_CustomPreview)\r\n    {\r\n        g.ComboPreviewData.PreviewRect = ImRect(bb.Min.x, bb.Min.y, value_x2, bb.Max.y);\r\n        IM_ASSERT(preview_value == NULL || preview_value[0] == 0);\r\n        preview_value = NULL;\r\n    }\r\n\r\n    // Render preview and label\r\n    if (preview_value != NULL && !(flags & ImGuiComboFlags_NoPreview))\r\n    {\r\n        if (g.LogEnabled)\r\n            LogSetNextTextDecoration(\"{\", \"}\");\r\n        RenderTextClipped(bb.Min + style.FramePadding, ImVec2(value_x2, bb.Max.y), preview_value, NULL, NULL);\r\n    }\r\n    if (label_size.x > 0)\r\n        RenderText(ImVec2(bb.Max.x + style.ItemInnerSpacing.x, bb.Min.y + style.FramePadding.y), label);\r\n\r\n    if (!popup_open)\r\n        return false;\r\n\r\n    g.NextWindowData.Flags = backup_next_window_data_flags;\r\n    return BeginComboPopup(popup_id, bb, flags);\r\n}\r\n\r\nbool ImGui::BeginComboPopup(ImGuiID popup_id, const ImRect& bb, ImGuiComboFlags flags)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    if (!IsPopupOpen(popup_id, ImGuiPopupFlags_None))\r\n    {\r\n        g.NextWindowData.ClearFlags();\r\n        return false;\r\n    }\r\n\r\n    // Set popup size\r\n    float w = bb.GetWidth();\r\n    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)\r\n    {\r\n        g.NextWindowData.SizeConstraintRect.Min.x = ImMax(g.NextWindowData.SizeConstraintRect.Min.x, w);\r\n    }\r\n    else\r\n    {\r\n        if ((flags & ImGuiComboFlags_HeightMask_) == 0)\r\n            flags |= ImGuiComboFlags_HeightRegular;\r\n        IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiComboFlags_HeightMask_)); // Only one\r\n        int popup_max_height_in_items = -1;\r\n        if (flags & ImGuiComboFlags_HeightRegular)     popup_max_height_in_items = 8;\r\n        else if (flags & ImGuiComboFlags_HeightSmall)  popup_max_height_in_items = 4;\r\n        else if (flags & ImGuiComboFlags_HeightLarge)  popup_max_height_in_items = 20;\r\n        SetNextWindowSizeConstraints(ImVec2(w, 0.0f), ImVec2(FLT_MAX, CalcMaxPopupHeightFromItemCount(popup_max_height_in_items)));\r\n    }\r\n\r\n    // This is essentially a specialized version of BeginPopupEx()\r\n    char name[16];\r\n    ImFormatString(name, IM_ARRAYSIZE(name), \"##Combo_%02d\", g.BeginPopupStack.Size); // Recycle windows based on depth\r\n\r\n    // Set position given a custom constraint (peak into expected window size so we can position it)\r\n    // FIXME: This might be easier to express with an hypothetical SetNextWindowPosConstraints() function?\r\n    // FIXME: This might be moved to Begin() or at least around the same spot where Tooltips and other Popups are calling FindBestWindowPosForPopupEx()?\r\n    if (ImGuiWindow* popup_window = FindWindowByName(name))\r\n        if (popup_window->WasActive)\r\n        {\r\n            // Always override 'AutoPosLastDirection' to not leave a chance for a past value to affect us.\r\n            ImVec2 size_expected = CalcWindowNextAutoFitSize(popup_window);\r\n            popup_window->AutoPosLastDirection = (flags & ImGuiComboFlags_PopupAlignLeft) ? ImGuiDir_Left : ImGuiDir_Down; // Left = \"Below, Toward Left\", Down = \"Below, Toward Right (default)\"\r\n            ImRect r_outer = GetPopupAllowedExtentRect(popup_window);\r\n            ImVec2 pos = FindBestWindowPosForPopupEx(bb.GetBL(), size_expected, &popup_window->AutoPosLastDirection, r_outer, bb, ImGuiPopupPositionPolicy_ComboBox);\r\n            SetNextWindowPos(pos);\r\n        }\r\n\r\n    // We don't use BeginPopupEx() solely because we have a custom name string, which we could make an argument to BeginPopupEx()\r\n    ImGuiWindowFlags window_flags = ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoMove;\r\n    PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(g.Style.FramePadding.x, g.Style.WindowPadding.y)); // Horizontally align ourselves with the framed text\r\n    bool ret = Begin(name, NULL, window_flags);\r\n    PopStyleVar();\r\n    if (!ret)\r\n    {\r\n        EndPopup();\r\n        IM_ASSERT(0);   // This should never happen as we tested for IsPopupOpen() above\r\n        return false;\r\n    }\r\n    return true;\r\n}\r\n\r\nvoid ImGui::EndCombo()\r\n{\r\n    EndPopup();\r\n}\r\n\r\n// Call directly after the BeginCombo/EndCombo block. The preview is designed to only host non-interactive elements\r\n// (Experimental, see GitHub issues: #1658, #4168)\r\nbool ImGui::BeginComboPreview()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    ImGuiComboPreviewData* preview_data = &g.ComboPreviewData;\r\n\r\n    if (window->SkipItems || !window->ClipRect.Overlaps(g.LastItemData.Rect)) // FIXME: Because we don't have a ImGuiItemStatusFlags_Visible flag to test last ItemAdd() result\r\n        return false;\r\n    IM_ASSERT(g.LastItemData.Rect.Min.x == preview_data->PreviewRect.Min.x && g.LastItemData.Rect.Min.y == preview_data->PreviewRect.Min.y); // Didn't call after BeginCombo/EndCombo block or forgot to pass ImGuiComboFlags_CustomPreview flag?\r\n    if (!window->ClipRect.Contains(preview_data->PreviewRect)) // Narrower test (optional)\r\n        return false;\r\n\r\n    // FIXME: This could be contained in a PushWorkRect() api\r\n    preview_data->BackupCursorPos = window->DC.CursorPos;\r\n    preview_data->BackupCursorMaxPos = window->DC.CursorMaxPos;\r\n    preview_data->BackupCursorPosPrevLine = window->DC.CursorPosPrevLine;\r\n    preview_data->BackupPrevLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;\r\n    preview_data->BackupLayout = window->DC.LayoutType;\r\n    window->DC.CursorPos = preview_data->PreviewRect.Min + g.Style.FramePadding;\r\n    window->DC.CursorMaxPos = window->DC.CursorPos;\r\n    window->DC.LayoutType = ImGuiLayoutType_Horizontal;\r\n    PushClipRect(preview_data->PreviewRect.Min, preview_data->PreviewRect.Max, true);\r\n\r\n    return true;\r\n}\r\n\r\nvoid ImGui::EndComboPreview()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    ImGuiComboPreviewData* preview_data = &g.ComboPreviewData;\r\n\r\n    // FIXME: Using CursorMaxPos approximation instead of correct AABB which we will store in ImDrawCmd in the future\r\n    ImDrawList* draw_list = window->DrawList;\r\n    if (window->DC.CursorMaxPos.x < preview_data->PreviewRect.Max.x && window->DC.CursorMaxPos.y < preview_data->PreviewRect.Max.y)\r\n        if (draw_list->CmdBuffer.Size > 1) // Unlikely case that the PushClipRect() didn't create a command\r\n        {\r\n            draw_list->_CmdHeader.ClipRect = draw_list->CmdBuffer[draw_list->CmdBuffer.Size - 1].ClipRect = draw_list->CmdBuffer[draw_list->CmdBuffer.Size - 2].ClipRect;\r\n            draw_list->_TryMergeDrawCmds();\r\n        }\r\n    PopClipRect();\r\n    window->DC.CursorPos = preview_data->BackupCursorPos;\r\n    window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, preview_data->BackupCursorMaxPos);\r\n    window->DC.CursorPosPrevLine = preview_data->BackupCursorPosPrevLine;\r\n    window->DC.PrevLineTextBaseOffset = preview_data->BackupPrevLineTextBaseOffset;\r\n    window->DC.LayoutType = preview_data->BackupLayout;\r\n    preview_data->PreviewRect = ImRect();\r\n}\r\n\r\n// Getter for the old Combo() API: const char*[]\r\nstatic bool Items_ArrayGetter(void* data, int idx, const char** out_text)\r\n{\r\n    const char* const* items = (const char* const*)data;\r\n    if (out_text)\r\n        *out_text = items[idx];\r\n    return true;\r\n}\r\n\r\n// Getter for the old Combo() API: \"item1\\0item2\\0item3\\0\"\r\nstatic bool Items_SingleStringGetter(void* data, int idx, const char** out_text)\r\n{\r\n    // FIXME-OPT: we could pre-compute the indices to fasten this. But only 1 active combo means the waste is limited.\r\n    const char* items_separated_by_zeros = (const char*)data;\r\n    int items_count = 0;\r\n    const char* p = items_separated_by_zeros;\r\n    while (*p)\r\n    {\r\n        if (idx == items_count)\r\n            break;\r\n        p += strlen(p) + 1;\r\n        items_count++;\r\n    }\r\n    if (!*p)\r\n        return false;\r\n    if (out_text)\r\n        *out_text = p;\r\n    return true;\r\n}\r\n\r\n// Old API, prefer using BeginCombo() nowadays if you can.\r\nbool ImGui::Combo(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int popup_max_height_in_items)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n\r\n    // Call the getter to obtain the preview string which is a parameter to BeginCombo()\r\n    const char* preview_value = NULL;\r\n    if (*current_item >= 0 && *current_item < items_count)\r\n        items_getter(data, *current_item, &preview_value);\r\n\r\n    // The old Combo() API exposed \"popup_max_height_in_items\". The new more general BeginCombo() API doesn't have/need it, but we emulate it here.\r\n    if (popup_max_height_in_items != -1 && !(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint))\r\n        SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, CalcMaxPopupHeightFromItemCount(popup_max_height_in_items)));\r\n\r\n    if (!BeginCombo(label, preview_value, ImGuiComboFlags_None))\r\n        return false;\r\n\r\n    // Display items\r\n    // FIXME-OPT: Use clipper (but we need to disable it on the appearing frame to make sure our call to SetItemDefaultFocus() is processed)\r\n    bool value_changed = false;\r\n    for (int i = 0; i < items_count; i++)\r\n    {\r\n        PushID(i);\r\n        const bool item_selected = (i == *current_item);\r\n        const char* item_text;\r\n        if (!items_getter(data, i, &item_text))\r\n            item_text = \"*Unknown item*\";\r\n        if (Selectable(item_text, item_selected))\r\n        {\r\n            value_changed = true;\r\n            *current_item = i;\r\n        }\r\n        if (item_selected)\r\n            SetItemDefaultFocus();\r\n        PopID();\r\n    }\r\n\r\n    EndCombo();\r\n\r\n    if (value_changed)\r\n        MarkItemEdited(g.LastItemData.ID);\r\n\r\n    return value_changed;\r\n}\r\n\r\n// Combo box helper allowing to pass an array of strings.\r\nbool ImGui::Combo(const char* label, int* current_item, const char* const items[], int items_count, int height_in_items)\r\n{\r\n    const bool value_changed = Combo(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_in_items);\r\n    return value_changed;\r\n}\r\n\r\n// Combo box helper allowing to pass all items in a single string literal holding multiple zero-terminated items \"item1\\0item2\\0\"\r\nbool ImGui::Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int height_in_items)\r\n{\r\n    int items_count = 0;\r\n    const char* p = items_separated_by_zeros;       // FIXME-OPT: Avoid computing this, or at least only when combo is open\r\n    while (*p)\r\n    {\r\n        p += strlen(p) + 1;\r\n        items_count++;\r\n    }\r\n    bool value_changed = Combo(label, current_item, Items_SingleStringGetter, (void*)items_separated_by_zeros, items_count, height_in_items);\r\n    return value_changed;\r\n}\r\n\r\n//-------------------------------------------------------------------------\r\n// [SECTION] Data Type and Data Formatting Helpers [Internal]\r\n//-------------------------------------------------------------------------\r\n// - PatchFormatStringFloatToInt()\r\n// - DataTypeGetInfo()\r\n// - DataTypeFormatString()\r\n// - DataTypeApplyOp()\r\n// - DataTypeApplyOpFromText()\r\n// - DataTypeClamp()\r\n// - GetMinimumStepAtDecimalPrecision\r\n// - RoundScalarWithFormat<>()\r\n//-------------------------------------------------------------------------\r\n\r\nstatic const ImGuiDataTypeInfo GDataTypeInfo[] =\r\n{\r\n    { sizeof(char),             \"S8\",   \"%d\",   \"%d\"    },  // ImGuiDataType_S8\r\n    { sizeof(unsigned char),    \"U8\",   \"%u\",   \"%u\"    },\r\n    { sizeof(short),            \"S16\",  \"%d\",   \"%d\"    },  // ImGuiDataType_S16\r\n    { sizeof(unsigned short),   \"U16\",  \"%u\",   \"%u\"    },\r\n    { sizeof(int),              \"S32\",  \"%d\",   \"%d\"    },  // ImGuiDataType_S32\r\n    { sizeof(unsigned int),     \"U32\",  \"%u\",   \"%u\"    },\r\n#ifdef _MSC_VER\r\n    { sizeof(ImS64),            \"S64\",  \"%I64d\",\"%I64d\" },  // ImGuiDataType_S64\r\n    { sizeof(ImU64),            \"U64\",  \"%I64u\",\"%I64u\" },\r\n#else\r\n    { sizeof(ImS64),            \"S64\",  \"%lld\", \"%lld\"  },  // ImGuiDataType_S64\r\n    { sizeof(ImU64),            \"U64\",  \"%llu\", \"%llu\"  },\r\n#endif\r\n    { sizeof(float),            \"float\", \"%.3f\",\"%f\"    },  // ImGuiDataType_Float (float are promoted to double in va_arg)\r\n    { sizeof(double),           \"double\",\"%f\",  \"%lf\"   },  // ImGuiDataType_Double\r\n};\r\nIM_STATIC_ASSERT(IM_ARRAYSIZE(GDataTypeInfo) == ImGuiDataType_COUNT);\r\n\r\n// FIXME-LEGACY: Prior to 1.61 our DragInt() function internally used floats and because of this the compile-time default value for format was \"%.0f\".\r\n// Even though we changed the compile-time default, we expect users to have carried %f around, which would break the display of DragInt() calls.\r\n// To honor backward compatibility we are rewriting the format string, unless IMGUI_DISABLE_OBSOLETE_FUNCTIONS is enabled. What could possibly go wrong?!\r\nstatic const char* PatchFormatStringFloatToInt(const char* fmt)\r\n{\r\n    if (fmt[0] == '%' && fmt[1] == '.' && fmt[2] == '0' && fmt[3] == 'f' && fmt[4] == 0) // Fast legacy path for \"%.0f\" which is expected to be the most common case.\r\n        return \"%d\";\r\n    const char* fmt_start = ImParseFormatFindStart(fmt);    // Find % (if any, and ignore %%)\r\n    const char* fmt_end = ImParseFormatFindEnd(fmt_start);  // Find end of format specifier, which itself is an exercise of confidence/recklessness (because snprintf is dependent on libc or user).\r\n    if (fmt_end > fmt_start && fmt_end[-1] == 'f')\r\n    {\r\n#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS\r\n        if (fmt_start == fmt && fmt_end[0] == 0)\r\n            return \"%d\";\r\n        ImGuiContext& g = *GImGui;\r\n        ImFormatString(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), \"%.*s%%d%s\", (int)(fmt_start - fmt), fmt, fmt_end); // Honor leading and trailing decorations, but lose alignment/precision.\r\n        return g.TempBuffer;\r\n#else\r\n        IM_ASSERT(0 && \"DragInt(): Invalid format string!\"); // Old versions used a default parameter of \"%.0f\", please replace with e.g. \"%d\"\r\n#endif\r\n    }\r\n    return fmt;\r\n}\r\n\r\nconst ImGuiDataTypeInfo* ImGui::DataTypeGetInfo(ImGuiDataType data_type)\r\n{\r\n    IM_ASSERT(data_type >= 0 && data_type < ImGuiDataType_COUNT);\r\n    return &GDataTypeInfo[data_type];\r\n}\r\n\r\nint ImGui::DataTypeFormatString(char* buf, int buf_size, ImGuiDataType data_type, const void* p_data, const char* format)\r\n{\r\n    // Signedness doesn't matter when pushing integer arguments\r\n    if (data_type == ImGuiDataType_S32 || data_type == ImGuiDataType_U32)\r\n        return ImFormatString(buf, buf_size, format, *(const ImU32*)p_data);\r\n    if (data_type == ImGuiDataType_S64 || data_type == ImGuiDataType_U64)\r\n        return ImFormatString(buf, buf_size, format, *(const ImU64*)p_data);\r\n    if (data_type == ImGuiDataType_Float)\r\n        return ImFormatString(buf, buf_size, format, *(const float*)p_data);\r\n    if (data_type == ImGuiDataType_Double)\r\n        return ImFormatString(buf, buf_size, format, *(const double*)p_data);\r\n    if (data_type == ImGuiDataType_S8)\r\n        return ImFormatString(buf, buf_size, format, *(const ImS8*)p_data);\r\n    if (data_type == ImGuiDataType_U8)\r\n        return ImFormatString(buf, buf_size, format, *(const ImU8*)p_data);\r\n    if (data_type == ImGuiDataType_S16)\r\n        return ImFormatString(buf, buf_size, format, *(const ImS16*)p_data);\r\n    if (data_type == ImGuiDataType_U16)\r\n        return ImFormatString(buf, buf_size, format, *(const ImU16*)p_data);\r\n    IM_ASSERT(0);\r\n    return 0;\r\n}\r\n\r\nvoid ImGui::DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, const void* arg1, const void* arg2)\r\n{\r\n    IM_ASSERT(op == '+' || op == '-');\r\n    switch (data_type)\r\n    {\r\n        case ImGuiDataType_S8:\r\n            if (op == '+') { *(ImS8*)output  = ImAddClampOverflow(*(const ImS8*)arg1,  *(const ImS8*)arg2,  IM_S8_MIN,  IM_S8_MAX); }\r\n            if (op == '-') { *(ImS8*)output  = ImSubClampOverflow(*(const ImS8*)arg1,  *(const ImS8*)arg2,  IM_S8_MIN,  IM_S8_MAX); }\r\n            return;\r\n        case ImGuiDataType_U8:\r\n            if (op == '+') { *(ImU8*)output  = ImAddClampOverflow(*(const ImU8*)arg1,  *(const ImU8*)arg2,  IM_U8_MIN,  IM_U8_MAX); }\r\n            if (op == '-') { *(ImU8*)output  = ImSubClampOverflow(*(const ImU8*)arg1,  *(const ImU8*)arg2,  IM_U8_MIN,  IM_U8_MAX); }\r\n            return;\r\n        case ImGuiDataType_S16:\r\n            if (op == '+') { *(ImS16*)output = ImAddClampOverflow(*(const ImS16*)arg1, *(const ImS16*)arg2, IM_S16_MIN, IM_S16_MAX); }\r\n            if (op == '-') { *(ImS16*)output = ImSubClampOverflow(*(const ImS16*)arg1, *(const ImS16*)arg2, IM_S16_MIN, IM_S16_MAX); }\r\n            return;\r\n        case ImGuiDataType_U16:\r\n            if (op == '+') { *(ImU16*)output = ImAddClampOverflow(*(const ImU16*)arg1, *(const ImU16*)arg2, IM_U16_MIN, IM_U16_MAX); }\r\n            if (op == '-') { *(ImU16*)output = ImSubClampOverflow(*(const ImU16*)arg1, *(const ImU16*)arg2, IM_U16_MIN, IM_U16_MAX); }\r\n            return;\r\n        case ImGuiDataType_S32:\r\n            if (op == '+') { *(ImS32*)output = ImAddClampOverflow(*(const ImS32*)arg1, *(const ImS32*)arg2, IM_S32_MIN, IM_S32_MAX); }\r\n            if (op == '-') { *(ImS32*)output = ImSubClampOverflow(*(const ImS32*)arg1, *(const ImS32*)arg2, IM_S32_MIN, IM_S32_MAX); }\r\n            return;\r\n        case ImGuiDataType_U32:\r\n            if (op == '+') { *(ImU32*)output = ImAddClampOverflow(*(const ImU32*)arg1, *(const ImU32*)arg2, IM_U32_MIN, IM_U32_MAX); }\r\n            if (op == '-') { *(ImU32*)output = ImSubClampOverflow(*(const ImU32*)arg1, *(const ImU32*)arg2, IM_U32_MIN, IM_U32_MAX); }\r\n            return;\r\n        case ImGuiDataType_S64:\r\n            if (op == '+') { *(ImS64*)output = ImAddClampOverflow(*(const ImS64*)arg1, *(const ImS64*)arg2, IM_S64_MIN, IM_S64_MAX); }\r\n            if (op == '-') { *(ImS64*)output = ImSubClampOverflow(*(const ImS64*)arg1, *(const ImS64*)arg2, IM_S64_MIN, IM_S64_MAX); }\r\n            return;\r\n        case ImGuiDataType_U64:\r\n            if (op == '+') { *(ImU64*)output = ImAddClampOverflow(*(const ImU64*)arg1, *(const ImU64*)arg2, IM_U64_MIN, IM_U64_MAX); }\r\n            if (op == '-') { *(ImU64*)output = ImSubClampOverflow(*(const ImU64*)arg1, *(const ImU64*)arg2, IM_U64_MIN, IM_U64_MAX); }\r\n            return;\r\n        case ImGuiDataType_Float:\r\n            if (op == '+') { *(float*)output = *(const float*)arg1 + *(const float*)arg2; }\r\n            if (op == '-') { *(float*)output = *(const float*)arg1 - *(const float*)arg2; }\r\n            return;\r\n        case ImGuiDataType_Double:\r\n            if (op == '+') { *(double*)output = *(const double*)arg1 + *(const double*)arg2; }\r\n            if (op == '-') { *(double*)output = *(const double*)arg1 - *(const double*)arg2; }\r\n            return;\r\n        case ImGuiDataType_COUNT: break;\r\n    }\r\n    IM_ASSERT(0);\r\n}\r\n\r\n// User can input math operators (e.g. +100) to edit a numerical values.\r\n// NB: This is _not_ a full expression evaluator. We should probably add one and replace this dumb mess..\r\nbool ImGui::DataTypeApplyFromText(const char* buf, ImGuiDataType data_type, void* p_data, const char* format)\r\n{\r\n    while (ImCharIsBlankA(*buf))\r\n        buf++;\r\n    if (!buf[0])\r\n        return false;\r\n\r\n    // Copy the value in an opaque buffer so we can compare at the end of the function if it changed at all.\r\n    const ImGuiDataTypeInfo* type_info = DataTypeGetInfo(data_type);\r\n    ImGuiDataTypeTempStorage data_backup;\r\n    memcpy(&data_backup, p_data, type_info->Size);\r\n\r\n    if (format == NULL)\r\n        format = type_info->ScanFmt;\r\n\r\n    if (data_type == ImGuiDataType_S32 || data_type == ImGuiDataType_U32 || data_type == ImGuiDataType_S64 || data_type == ImGuiDataType_U64 || data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double)\r\n    {\r\n        // For float/double we have to ignore format with precision (e.g. \"%.2f\") because sscanf doesn't take them in, so force them into %f and %lf\r\n        if (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double)\r\n            format = type_info->ScanFmt;\r\n        if (sscanf(buf, format, p_data) < 1)\r\n            return false;\r\n    }\r\n    else\r\n    {\r\n        // Small types need a 32-bit buffer to receive the result from scanf()\r\n        int v32;\r\n        if (sscanf(buf, format, &v32) < 1)\r\n            return false;\r\n        if (data_type == ImGuiDataType_S8)\r\n            *(ImS8*)p_data = (ImS8)ImClamp(v32, (int)IM_S8_MIN, (int)IM_S8_MAX);\r\n        else if (data_type == ImGuiDataType_U8)\r\n            *(ImU8*)p_data = (ImU8)ImClamp(v32, (int)IM_U8_MIN, (int)IM_U8_MAX);\r\n        else if (data_type == ImGuiDataType_S16)\r\n            *(ImS16*)p_data = (ImS16)ImClamp(v32, (int)IM_S16_MIN, (int)IM_S16_MAX);\r\n        else if (data_type == ImGuiDataType_U16)\r\n            *(ImU16*)p_data = (ImU16)ImClamp(v32, (int)IM_U16_MIN, (int)IM_U16_MAX);\r\n        else\r\n            IM_ASSERT(0);\r\n    }\r\n\r\n    return memcmp(&data_backup, p_data, type_info->Size) != 0;\r\n}\r\n\r\ntemplate<typename T>\r\nstatic int DataTypeCompareT(const T* lhs, const T* rhs)\r\n{\r\n    if (*lhs < *rhs) return -1;\r\n    if (*lhs > *rhs) return +1;\r\n    return 0;\r\n}\r\n\r\nint ImGui::DataTypeCompare(ImGuiDataType data_type, const void* arg_1, const void* arg_2)\r\n{\r\n    switch (data_type)\r\n    {\r\n    case ImGuiDataType_S8:     return DataTypeCompareT<ImS8  >((const ImS8*  )arg_1, (const ImS8*  )arg_2);\r\n    case ImGuiDataType_U8:     return DataTypeCompareT<ImU8  >((const ImU8*  )arg_1, (const ImU8*  )arg_2);\r\n    case ImGuiDataType_S16:    return DataTypeCompareT<ImS16 >((const ImS16* )arg_1, (const ImS16* )arg_2);\r\n    case ImGuiDataType_U16:    return DataTypeCompareT<ImU16 >((const ImU16* )arg_1, (const ImU16* )arg_2);\r\n    case ImGuiDataType_S32:    return DataTypeCompareT<ImS32 >((const ImS32* )arg_1, (const ImS32* )arg_2);\r\n    case ImGuiDataType_U32:    return DataTypeCompareT<ImU32 >((const ImU32* )arg_1, (const ImU32* )arg_2);\r\n    case ImGuiDataType_S64:    return DataTypeCompareT<ImS64 >((const ImS64* )arg_1, (const ImS64* )arg_2);\r\n    case ImGuiDataType_U64:    return DataTypeCompareT<ImU64 >((const ImU64* )arg_1, (const ImU64* )arg_2);\r\n    case ImGuiDataType_Float:  return DataTypeCompareT<float >((const float* )arg_1, (const float* )arg_2);\r\n    case ImGuiDataType_Double: return DataTypeCompareT<double>((const double*)arg_1, (const double*)arg_2);\r\n    case ImGuiDataType_COUNT:  break;\r\n    }\r\n    IM_ASSERT(0);\r\n    return 0;\r\n}\r\n\r\ntemplate<typename T>\r\nstatic bool DataTypeClampT(T* v, const T* v_min, const T* v_max)\r\n{\r\n    // Clamp, both sides are optional, return true if modified\r\n    if (v_min && *v < *v_min) { *v = *v_min; return true; }\r\n    if (v_max && *v > *v_max) { *v = *v_max; return true; }\r\n    return false;\r\n}\r\n\r\nbool ImGui::DataTypeClamp(ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max)\r\n{\r\n    switch (data_type)\r\n    {\r\n    case ImGuiDataType_S8:     return DataTypeClampT<ImS8  >((ImS8*  )p_data, (const ImS8*  )p_min, (const ImS8*  )p_max);\r\n    case ImGuiDataType_U8:     return DataTypeClampT<ImU8  >((ImU8*  )p_data, (const ImU8*  )p_min, (const ImU8*  )p_max);\r\n    case ImGuiDataType_S16:    return DataTypeClampT<ImS16 >((ImS16* )p_data, (const ImS16* )p_min, (const ImS16* )p_max);\r\n    case ImGuiDataType_U16:    return DataTypeClampT<ImU16 >((ImU16* )p_data, (const ImU16* )p_min, (const ImU16* )p_max);\r\n    case ImGuiDataType_S32:    return DataTypeClampT<ImS32 >((ImS32* )p_data, (const ImS32* )p_min, (const ImS32* )p_max);\r\n    case ImGuiDataType_U32:    return DataTypeClampT<ImU32 >((ImU32* )p_data, (const ImU32* )p_min, (const ImU32* )p_max);\r\n    case ImGuiDataType_S64:    return DataTypeClampT<ImS64 >((ImS64* )p_data, (const ImS64* )p_min, (const ImS64* )p_max);\r\n    case ImGuiDataType_U64:    return DataTypeClampT<ImU64 >((ImU64* )p_data, (const ImU64* )p_min, (const ImU64* )p_max);\r\n    case ImGuiDataType_Float:  return DataTypeClampT<float >((float* )p_data, (const float* )p_min, (const float* )p_max);\r\n    case ImGuiDataType_Double: return DataTypeClampT<double>((double*)p_data, (const double*)p_min, (const double*)p_max);\r\n    case ImGuiDataType_COUNT:  break;\r\n    }\r\n    IM_ASSERT(0);\r\n    return false;\r\n}\r\n\r\nstatic float GetMinimumStepAtDecimalPrecision(int decimal_precision)\r\n{\r\n    static const float min_steps[10] = { 1.0f, 0.1f, 0.01f, 0.001f, 0.0001f, 0.00001f, 0.000001f, 0.0000001f, 0.00000001f, 0.000000001f };\r\n    if (decimal_precision < 0)\r\n        return FLT_MIN;\r\n    return (decimal_precision < IM_ARRAYSIZE(min_steps)) ? min_steps[decimal_precision] : ImPow(10.0f, (float)-decimal_precision);\r\n}\r\n\r\ntemplate<typename TYPE>\r\nstatic const char* ImAtoi(const char* src, TYPE* output)\r\n{\r\n    int negative = 0;\r\n    if (*src == '-') { negative = 1; src++; }\r\n    if (*src == '+') { src++; }\r\n    TYPE v = 0;\r\n    while (*src >= '0' && *src <= '9')\r\n        v = (v * 10) + (*src++ - '0');\r\n    *output = negative ? -v : v;\r\n    return src;\r\n}\r\n\r\n// Sanitize format\r\n// - Zero terminate so extra characters after format (e.g. \"%f123\") don't confuse atof/atoi\r\n// - stb_sprintf.h supports several new modifiers which format numbers in a way that also makes them incompatible atof/atoi.\r\nstatic void SanitizeFormatString(const char* fmt, char* fmt_out, size_t fmt_out_size)\r\n{\r\n    IM_UNUSED(fmt_out_size);\r\n    const char* fmt_end = ImParseFormatFindEnd(fmt);\r\n    IM_ASSERT((size_t)(fmt_end - fmt + 1) < fmt_out_size); // Format is too long, let us know if this happens to you!\r\n    while (fmt < fmt_end)\r\n    {\r\n        char c = *(fmt++);\r\n        if (c != '\\'' && c != '$' && c != '_') // Custom flags provided by stb_sprintf.h. POSIX 2008 also supports '.\r\n            *(fmt_out++) = c;\r\n    }\r\n    *fmt_out = 0; // Zero-terminate\r\n}\r\n\r\ntemplate<typename TYPE, typename SIGNEDTYPE>\r\nTYPE ImGui::RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, TYPE v)\r\n{\r\n    const char* fmt_start = ImParseFormatFindStart(format);\r\n    if (fmt_start[0] != '%' || fmt_start[1] == '%') // Don't apply if the value is not visible in the format string\r\n        return v;\r\n\r\n    // Sanitize format\r\n    char fmt_sanitized[32];\r\n    SanitizeFormatString(fmt_start, fmt_sanitized, IM_ARRAYSIZE(fmt_sanitized));\r\n    fmt_start = fmt_sanitized;\r\n\r\n    // Format value with our rounding, and read back\r\n    char v_str[64];\r\n    ImFormatString(v_str, IM_ARRAYSIZE(v_str), fmt_start, v);\r\n    const char* p = v_str;\r\n    while (*p == ' ')\r\n        p++;\r\n    if (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double)\r\n        v = (TYPE)ImAtof(p);\r\n    else\r\n        ImAtoi(p, (SIGNEDTYPE*)&v);\r\n    return v;\r\n}\r\n\r\n//-------------------------------------------------------------------------\r\n// [SECTION] Widgets: DragScalar, DragFloat, DragInt, etc.\r\n//-------------------------------------------------------------------------\r\n// - DragBehaviorT<>() [Internal]\r\n// - DragBehavior() [Internal]\r\n// - DragScalar()\r\n// - DragScalarN()\r\n// - DragFloat()\r\n// - DragFloat2()\r\n// - DragFloat3()\r\n// - DragFloat4()\r\n// - DragFloatRange2()\r\n// - DragInt()\r\n// - DragInt2()\r\n// - DragInt3()\r\n// - DragInt4()\r\n// - DragIntRange2()\r\n//-------------------------------------------------------------------------\r\n\r\n// This is called by DragBehavior() when the widget is active (held by mouse or being manipulated with Nav controls)\r\ntemplate<typename TYPE, typename SIGNEDTYPE, typename FLOATTYPE>\r\nbool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const TYPE v_min, const TYPE v_max, const char* format, ImGuiSliderFlags flags)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    const ImGuiAxis axis = (flags & ImGuiSliderFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X;\r\n    const bool is_clamped = (v_min < v_max);\r\n    const bool is_logarithmic = (flags & ImGuiSliderFlags_Logarithmic) != 0;\r\n    const bool is_floating_point = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double);\r\n\r\n    // Default tweak speed\r\n    if (v_speed == 0.0f && is_clamped && (v_max - v_min < FLT_MAX))\r\n        v_speed = (float)((v_max - v_min) * g.DragSpeedDefaultRatio);\r\n\r\n    // Inputs accumulates into g.DragCurrentAccum, which is flushed into the current value as soon as it makes a difference with our precision settings\r\n    float adjust_delta = 0.0f;\r\n    if (g.ActiveIdSource == ImGuiInputSource_Mouse && IsMousePosValid() && IsMouseDragPastThreshold(0, g.IO.MouseDragThreshold * DRAG_MOUSE_THRESHOLD_FACTOR))\r\n    {\r\n        adjust_delta = g.IO.MouseDelta[axis];\r\n        if (g.IO.KeyAlt)\r\n            adjust_delta *= 1.0f / 100.0f;\r\n        if (g.IO.KeyShift)\r\n            adjust_delta *= 10.0f;\r\n    }\r\n    else if (g.ActiveIdSource == ImGuiInputSource_Nav)\r\n    {\r\n        const int decimal_precision = is_floating_point ? ImParseFormatPrecision(format, 3) : 0;\r\n        adjust_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard | ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_RepeatFast, 1.0f / 10.0f, 10.0f)[axis];\r\n        v_speed = ImMax(v_speed, GetMinimumStepAtDecimalPrecision(decimal_precision));\r\n    }\r\n    adjust_delta *= v_speed;\r\n\r\n    // For vertical drag we currently assume that Up=higher value (like we do with vertical sliders). This may become a parameter.\r\n    if (axis == ImGuiAxis_Y)\r\n        adjust_delta = -adjust_delta;\r\n\r\n    // For logarithmic use our range is effectively 0..1 so scale the delta into that range\r\n    if (is_logarithmic && (v_max - v_min < FLT_MAX) && ((v_max - v_min) > 0.000001f)) // Epsilon to avoid /0\r\n        adjust_delta /= (float)(v_max - v_min);\r\n\r\n    // Clear current value on activation\r\n    // Avoid altering values and clamping when we are _already_ past the limits and heading in the same direction, so e.g. if range is 0..255, current value is 300 and we are pushing to the right side, keep the 300.\r\n    bool is_just_activated = g.ActiveIdIsJustActivated;\r\n    bool is_already_past_limits_and_pushing_outward = is_clamped && ((*v >= v_max && adjust_delta > 0.0f) || (*v <= v_min && adjust_delta < 0.0f));\r\n    if (is_just_activated || is_already_past_limits_and_pushing_outward)\r\n    {\r\n        g.DragCurrentAccum = 0.0f;\r\n        g.DragCurrentAccumDirty = false;\r\n    }\r\n    else if (adjust_delta != 0.0f)\r\n    {\r\n        g.DragCurrentAccum += adjust_delta;\r\n        g.DragCurrentAccumDirty = true;\r\n    }\r\n\r\n    if (!g.DragCurrentAccumDirty)\r\n        return false;\r\n\r\n    TYPE v_cur = *v;\r\n    FLOATTYPE v_old_ref_for_accum_remainder = (FLOATTYPE)0.0f;\r\n\r\n    float logarithmic_zero_epsilon = 0.0f; // Only valid when is_logarithmic is true\r\n    const float zero_deadzone_halfsize = 0.0f; // Drag widgets have no deadzone (as it doesn't make sense)\r\n    if (is_logarithmic)\r\n    {\r\n        // When using logarithmic sliders, we need to clamp to avoid hitting zero, but our choice of clamp value greatly affects slider precision. We attempt to use the specified precision to estimate a good lower bound.\r\n        const int decimal_precision = is_floating_point ? ImParseFormatPrecision(format, 3) : 1;\r\n        logarithmic_zero_epsilon = ImPow(0.1f, (float)decimal_precision);\r\n\r\n        // Convert to parametric space, apply delta, convert back\r\n        float v_old_parametric = ScaleRatioFromValueT<TYPE, SIGNEDTYPE, FLOATTYPE>(data_type, v_cur, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize);\r\n        float v_new_parametric = v_old_parametric + g.DragCurrentAccum;\r\n        v_cur = ScaleValueFromRatioT<TYPE, SIGNEDTYPE, FLOATTYPE>(data_type, v_new_parametric, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize);\r\n        v_old_ref_for_accum_remainder = v_old_parametric;\r\n    }\r\n    else\r\n    {\r\n        v_cur += (SIGNEDTYPE)g.DragCurrentAccum;\r\n    }\r\n\r\n    // Round to user desired precision based on format string\r\n    if (!(flags & ImGuiSliderFlags_NoRoundToFormat))\r\n        v_cur = RoundScalarWithFormatT<TYPE, SIGNEDTYPE>(format, data_type, v_cur);\r\n\r\n    // Preserve remainder after rounding has been applied. This also allow slow tweaking of values.\r\n    g.DragCurrentAccumDirty = false;\r\n    if (is_logarithmic)\r\n    {\r\n        // Convert to parametric space, apply delta, convert back\r\n        float v_new_parametric = ScaleRatioFromValueT<TYPE, SIGNEDTYPE, FLOATTYPE>(data_type, v_cur, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize);\r\n        g.DragCurrentAccum -= (float)(v_new_parametric - v_old_ref_for_accum_remainder);\r\n    }\r\n    else\r\n    {\r\n        g.DragCurrentAccum -= (float)((SIGNEDTYPE)v_cur - (SIGNEDTYPE)*v);\r\n    }\r\n\r\n    // Lose zero sign for float/double\r\n    if (v_cur == (TYPE)-0)\r\n        v_cur = (TYPE)0;\r\n\r\n    // Clamp values (+ handle overflow/wrap-around for integer types)\r\n    if (*v != v_cur && is_clamped)\r\n    {\r\n        if (v_cur < v_min || (v_cur > *v && adjust_delta < 0.0f && !is_floating_point))\r\n            v_cur = v_min;\r\n        if (v_cur > v_max || (v_cur < *v && adjust_delta > 0.0f && !is_floating_point))\r\n            v_cur = v_max;\r\n    }\r\n\r\n    // Apply result\r\n    if (*v == v_cur)\r\n        return false;\r\n    *v = v_cur;\r\n    return true;\r\n}\r\n\r\nbool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags)\r\n{\r\n    // Read imgui.cpp \"API BREAKING CHANGES\" section for 1.78 if you hit this assert.\r\n    IM_ASSERT((flags == 1 || (flags & ImGuiSliderFlags_InvalidMask_) == 0) && \"Invalid ImGuiSliderFlags flags! Has the 'float power' argument been mistakenly cast to flags? Call function with ImGuiSliderFlags_Logarithmic flags instead.\");\r\n\r\n    ImGuiContext& g = *GImGui;\r\n    if (g.ActiveId == id)\r\n    {\r\n        if (g.ActiveIdSource == ImGuiInputSource_Mouse && !g.IO.MouseDown[0])\r\n            ClearActiveID();\r\n        else if (g.ActiveIdSource == ImGuiInputSource_Nav && g.NavActivatePressedId == id && !g.ActiveIdIsJustActivated)\r\n            ClearActiveID();\r\n    }\r\n    if (g.ActiveId != id)\r\n        return false;\r\n    if ((g.LastItemData.InFlags & ImGuiItemFlags_ReadOnly) || (flags & ImGuiSliderFlags_ReadOnly))\r\n        return false;\r\n\r\n    switch (data_type)\r\n    {\r\n    case ImGuiDataType_S8:     { ImS32 v32 = (ImS32)*(ImS8*)p_v;  bool r = DragBehaviorT<ImS32, ImS32, float>(ImGuiDataType_S32, &v32, v_speed, p_min ? *(const ImS8*) p_min : IM_S8_MIN,  p_max ? *(const ImS8*)p_max  : IM_S8_MAX,  format, flags); if (r) *(ImS8*)p_v = (ImS8)v32; return r; }\r\n    case ImGuiDataType_U8:     { ImU32 v32 = (ImU32)*(ImU8*)p_v;  bool r = DragBehaviorT<ImU32, ImS32, float>(ImGuiDataType_U32, &v32, v_speed, p_min ? *(const ImU8*) p_min : IM_U8_MIN,  p_max ? *(const ImU8*)p_max  : IM_U8_MAX,  format, flags); if (r) *(ImU8*)p_v = (ImU8)v32; return r; }\r\n    case ImGuiDataType_S16:    { ImS32 v32 = (ImS32)*(ImS16*)p_v; bool r = DragBehaviorT<ImS32, ImS32, float>(ImGuiDataType_S32, &v32, v_speed, p_min ? *(const ImS16*)p_min : IM_S16_MIN, p_max ? *(const ImS16*)p_max : IM_S16_MAX, format, flags); if (r) *(ImS16*)p_v = (ImS16)v32; return r; }\r\n    case ImGuiDataType_U16:    { ImU32 v32 = (ImU32)*(ImU16*)p_v; bool r = DragBehaviorT<ImU32, ImS32, float>(ImGuiDataType_U32, &v32, v_speed, p_min ? *(const ImU16*)p_min : IM_U16_MIN, p_max ? *(const ImU16*)p_max : IM_U16_MAX, format, flags); if (r) *(ImU16*)p_v = (ImU16)v32; return r; }\r\n    case ImGuiDataType_S32:    return DragBehaviorT<ImS32, ImS32, float >(data_type, (ImS32*)p_v,  v_speed, p_min ? *(const ImS32* )p_min : IM_S32_MIN, p_max ? *(const ImS32* )p_max : IM_S32_MAX, format, flags);\r\n    case ImGuiDataType_U32:    return DragBehaviorT<ImU32, ImS32, float >(data_type, (ImU32*)p_v,  v_speed, p_min ? *(const ImU32* )p_min : IM_U32_MIN, p_max ? *(const ImU32* )p_max : IM_U32_MAX, format, flags);\r\n    case ImGuiDataType_S64:    return DragBehaviorT<ImS64, ImS64, double>(data_type, (ImS64*)p_v,  v_speed, p_min ? *(const ImS64* )p_min : IM_S64_MIN, p_max ? *(const ImS64* )p_max : IM_S64_MAX, format, flags);\r\n    case ImGuiDataType_U64:    return DragBehaviorT<ImU64, ImS64, double>(data_type, (ImU64*)p_v,  v_speed, p_min ? *(const ImU64* )p_min : IM_U64_MIN, p_max ? *(const ImU64* )p_max : IM_U64_MAX, format, flags);\r\n    case ImGuiDataType_Float:  return DragBehaviorT<float, float, float >(data_type, (float*)p_v,  v_speed, p_min ? *(const float* )p_min : -FLT_MAX,   p_max ? *(const float* )p_max : FLT_MAX,    format, flags);\r\n    case ImGuiDataType_Double: return DragBehaviorT<double,double,double>(data_type, (double*)p_v, v_speed, p_min ? *(const double*)p_min : -DBL_MAX,   p_max ? *(const double*)p_max : DBL_MAX,    format, flags);\r\n    case ImGuiDataType_COUNT:  break;\r\n    }\r\n    IM_ASSERT(0);\r\n    return false;\r\n}\r\n\r\n// Note: p_data, p_min and p_max are _pointers_ to a memory address holding the data. For a Drag widget, p_min and p_max are optional.\r\n// Read code of e.g. DragFloat(), DragInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly.\r\nbool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return false;\r\n\r\n    ImGuiContext& g = *GImGui;\r\n    const ImGuiStyle& style = g.Style;\r\n    const ImGuiID id = window->GetID(label);\r\n    const float w = CalcItemWidth();\r\n\r\n    const ImVec2 label_size = CalcTextSize(label, NULL, true);\r\n    const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y * 2.0f));\r\n    const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));\r\n\r\n    const bool temp_input_allowed = (flags & ImGuiSliderFlags_NoInput) == 0;\r\n    ItemSize(total_bb, style.FramePadding.y);\r\n    if (!ItemAdd(total_bb, id, &frame_bb, temp_input_allowed ? ImGuiItemFlags_Inputable : 0))\r\n        return false;\r\n\r\n    // Default format string when passing NULL\r\n    if (format == NULL)\r\n        format = DataTypeGetInfo(data_type)->PrintFmt;\r\n    else if (data_type == ImGuiDataType_S32 && strcmp(format, \"%d\") != 0) // (FIXME-LEGACY: Patch old \"%.0f\" format string to use \"%d\", read function more details.)\r\n        format = PatchFormatStringFloatToInt(format);\r\n\r\n    // Tabbing or CTRL-clicking on Drag turns it into an InputText\r\n    const bool hovered = ItemHoverable(frame_bb, id);\r\n    bool temp_input_is_active = temp_input_allowed && TempInputIsActive(id);\r\n    if (!temp_input_is_active)\r\n    {\r\n        const bool input_requested_by_tabbing = temp_input_allowed && (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_FocusedByTabbing) != 0;\r\n        const bool clicked = (hovered && g.IO.MouseClicked[0]);\r\n        const bool double_clicked = (hovered && g.IO.MouseClickedCount[0] == 2);\r\n        if (input_requested_by_tabbing || clicked || double_clicked || g.NavActivateId == id || g.NavActivateInputId == id)\r\n        {\r\n            SetActiveID(id, window);\r\n            SetFocusID(id, window);\r\n            FocusWindow(window);\r\n            g.ActiveIdUsingNavDirMask = (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right);\r\n            if (temp_input_allowed)\r\n                if (input_requested_by_tabbing || (clicked && g.IO.KeyCtrl) || double_clicked || g.NavActivateInputId == id)\r\n                    temp_input_is_active = true;\r\n        }\r\n\r\n        // Experimental: simple click (without moving) turns Drag into an InputText\r\n        if (g.IO.ConfigDragClickToInputText && temp_input_allowed && !temp_input_is_active)\r\n            if (g.ActiveId == id && hovered && g.IO.MouseReleased[0] && !IsMouseDragPastThreshold(0, g.IO.MouseDragThreshold * DRAG_MOUSE_THRESHOLD_FACTOR))\r\n            {\r\n                g.NavActivateId = g.NavActivateInputId = id;\r\n                g.NavActivateFlags = ImGuiActivateFlags_PreferInput;\r\n                temp_input_is_active = true;\r\n            }\r\n    }\r\n\r\n    if (temp_input_is_active)\r\n    {\r\n        // Only clamp CTRL+Click input when ImGuiSliderFlags_AlwaysClamp is set\r\n        const bool is_clamp_input = (flags & ImGuiSliderFlags_AlwaysClamp) != 0 && (p_min == NULL || p_max == NULL || DataTypeCompare(data_type, p_min, p_max) < 0);\r\n        return TempInputScalar(frame_bb, id, label, data_type, p_data, format, is_clamp_input ? p_min : NULL, is_clamp_input ? p_max : NULL);\r\n    }\r\n\r\n    // Draw frame\r\n    const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);\r\n    RenderNavHighlight(frame_bb, id);\r\n    RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, style.FrameRounding);\r\n\r\n    // Drag behavior\r\n    const bool value_changed = DragBehavior(id, data_type, p_data, v_speed, p_min, p_max, format, flags);\r\n    if (value_changed)\r\n        MarkItemEdited(id);\r\n\r\n    // Display value using user-provided display format so user can add prefix/suffix/decorations to the value.\r\n    char value_buf[64];\r\n    const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_ARRAYSIZE(value_buf), data_type, p_data, format);\r\n    if (g.LogEnabled)\r\n        LogSetNextTextDecoration(\"{\", \"}\");\r\n    RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f, 0.5f));\r\n\r\n    if (label_size.x > 0.0f)\r\n        RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);\r\n\r\n    IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags);\r\n    return value_changed;\r\n}\r\n\r\nbool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return false;\r\n\r\n    ImGuiContext& g = *GImGui;\r\n    bool value_changed = false;\r\n    BeginGroup();\r\n    PushID(label);\r\n    PushMultiItemsWidths(components, CalcItemWidth());\r\n    size_t type_size = GDataTypeInfo[data_type].Size;\r\n    for (int i = 0; i < components; i++)\r\n    {\r\n        PushID(i);\r\n        if (i > 0)\r\n            SameLine(0, g.Style.ItemInnerSpacing.x);\r\n        value_changed |= DragScalar(\"\", data_type, p_data, v_speed, p_min, p_max, format, flags);\r\n        PopID();\r\n        PopItemWidth();\r\n        p_data = (void*)((char*)p_data + type_size);\r\n    }\r\n    PopID();\r\n\r\n    const char* label_end = FindRenderedTextEnd(label);\r\n    if (label != label_end)\r\n    {\r\n        SameLine(0, g.Style.ItemInnerSpacing.x);\r\n        TextEx(label, label_end);\r\n    }\r\n\r\n    EndGroup();\r\n    return value_changed;\r\n}\r\n\r\nbool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags)\r\n{\r\n    return DragScalar(label, ImGuiDataType_Float, v, v_speed, &v_min, &v_max, format, flags);\r\n}\r\n\r\nbool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags)\r\n{\r\n    return DragScalarN(label, ImGuiDataType_Float, v, 2, v_speed, &v_min, &v_max, format, flags);\r\n}\r\n\r\nbool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags)\r\n{\r\n    return DragScalarN(label, ImGuiDataType_Float, v, 3, v_speed, &v_min, &v_max, format, flags);\r\n}\r\n\r\nbool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags)\r\n{\r\n    return DragScalarN(label, ImGuiDataType_Float, v, 4, v_speed, &v_min, &v_max, format, flags);\r\n}\r\n\r\n// NB: You likely want to specify the ImGuiSliderFlags_AlwaysClamp when using this.\r\nbool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, ImGuiSliderFlags flags)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return false;\r\n\r\n    ImGuiContext& g = *GImGui;\r\n    PushID(label);\r\n    BeginGroup();\r\n    PushMultiItemsWidths(2, CalcItemWidth());\r\n\r\n    float min_min = (v_min >= v_max) ? -FLT_MAX : v_min;\r\n    float min_max = (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max);\r\n    ImGuiSliderFlags min_flags = flags | ((min_min == min_max) ? ImGuiSliderFlags_ReadOnly : 0);\r\n    bool value_changed = DragScalar(\"##min\", ImGuiDataType_Float, v_current_min, v_speed, &min_min, &min_max, format, min_flags);\r\n    PopItemWidth();\r\n    SameLine(0, g.Style.ItemInnerSpacing.x);\r\n\r\n    float max_min = (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min);\r\n    float max_max = (v_min >= v_max) ? FLT_MAX : v_max;\r\n    ImGuiSliderFlags max_flags = flags | ((max_min == max_max) ? ImGuiSliderFlags_ReadOnly : 0);\r\n    value_changed |= DragScalar(\"##max\", ImGuiDataType_Float, v_current_max, v_speed, &max_min, &max_max, format_max ? format_max : format, max_flags);\r\n    PopItemWidth();\r\n    SameLine(0, g.Style.ItemInnerSpacing.x);\r\n\r\n    TextEx(label, FindRenderedTextEnd(label));\r\n    EndGroup();\r\n    PopID();\r\n\r\n    return value_changed;\r\n}\r\n\r\n// NB: v_speed is float to allow adjusting the drag speed with more precision\r\nbool ImGui::DragInt(const char* label, int* v, float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags)\r\n{\r\n    return DragScalar(label, ImGuiDataType_S32, v, v_speed, &v_min, &v_max, format, flags);\r\n}\r\n\r\nbool ImGui::DragInt2(const char* label, int v[2], float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags)\r\n{\r\n    return DragScalarN(label, ImGuiDataType_S32, v, 2, v_speed, &v_min, &v_max, format, flags);\r\n}\r\n\r\nbool ImGui::DragInt3(const char* label, int v[3], float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags)\r\n{\r\n    return DragScalarN(label, ImGuiDataType_S32, v, 3, v_speed, &v_min, &v_max, format, flags);\r\n}\r\n\r\nbool ImGui::DragInt4(const char* label, int v[4], float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags)\r\n{\r\n    return DragScalarN(label, ImGuiDataType_S32, v, 4, v_speed, &v_min, &v_max, format, flags);\r\n}\r\n\r\n// NB: You likely want to specify the ImGuiSliderFlags_AlwaysClamp when using this.\r\nbool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed, int v_min, int v_max, const char* format, const char* format_max, ImGuiSliderFlags flags)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return false;\r\n\r\n    ImGuiContext& g = *GImGui;\r\n    PushID(label);\r\n    BeginGroup();\r\n    PushMultiItemsWidths(2, CalcItemWidth());\r\n\r\n    int min_min = (v_min >= v_max) ? INT_MIN : v_min;\r\n    int min_max = (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max);\r\n    ImGuiSliderFlags min_flags = flags | ((min_min == min_max) ? ImGuiSliderFlags_ReadOnly : 0);\r\n    bool value_changed = DragInt(\"##min\", v_current_min, v_speed, min_min, min_max, format, min_flags);\r\n    PopItemWidth();\r\n    SameLine(0, g.Style.ItemInnerSpacing.x);\r\n\r\n    int max_min = (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min);\r\n    int max_max = (v_min >= v_max) ? INT_MAX : v_max;\r\n    ImGuiSliderFlags max_flags = flags | ((max_min == max_max) ? ImGuiSliderFlags_ReadOnly : 0);\r\n    value_changed |= DragInt(\"##max\", v_current_max, v_speed, max_min, max_max, format_max ? format_max : format, max_flags);\r\n    PopItemWidth();\r\n    SameLine(0, g.Style.ItemInnerSpacing.x);\r\n\r\n    TextEx(label, FindRenderedTextEnd(label));\r\n    EndGroup();\r\n    PopID();\r\n\r\n    return value_changed;\r\n}\r\n\r\n#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS\r\n\r\n// Obsolete versions with power parameter. See https://github.com/ocornut/imgui/issues/3361 for details.\r\nbool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, float power)\r\n{\r\n    ImGuiSliderFlags drag_flags = ImGuiSliderFlags_None;\r\n    if (power != 1.0f)\r\n    {\r\n        IM_ASSERT(power == 1.0f && \"Call function with ImGuiSliderFlags_Logarithmic flags instead of using the old 'float power' function!\");\r\n        IM_ASSERT(p_min != NULL && p_max != NULL);  // When using a power curve the drag needs to have known bounds\r\n        drag_flags |= ImGuiSliderFlags_Logarithmic;   // Fallback for non-asserting paths\r\n    }\r\n    return DragScalar(label, data_type, p_data, v_speed, p_min, p_max, format, drag_flags);\r\n}\r\n\r\nbool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, float power)\r\n{\r\n    ImGuiSliderFlags drag_flags = ImGuiSliderFlags_None;\r\n    if (power != 1.0f)\r\n    {\r\n        IM_ASSERT(power == 1.0f && \"Call function with ImGuiSliderFlags_Logarithmic flags instead of using the old 'float power' function!\");\r\n        IM_ASSERT(p_min != NULL && p_max != NULL);  // When using a power curve the drag needs to have known bounds\r\n        drag_flags |= ImGuiSliderFlags_Logarithmic;   // Fallback for non-asserting paths\r\n    }\r\n    return DragScalarN(label, data_type, p_data, components, v_speed, p_min, p_max, format, drag_flags);\r\n}\r\n\r\n#endif // IMGUI_DISABLE_OBSOLETE_FUNCTIONS\r\n\r\n//-------------------------------------------------------------------------\r\n// [SECTION] Widgets: SliderScalar, SliderFloat, SliderInt, etc.\r\n//-------------------------------------------------------------------------\r\n// - ScaleRatioFromValueT<> [Internal]\r\n// - ScaleValueFromRatioT<> [Internal]\r\n// - SliderBehaviorT<>() [Internal]\r\n// - SliderBehavior() [Internal]\r\n// - SliderScalar()\r\n// - SliderScalarN()\r\n// - SliderFloat()\r\n// - SliderFloat2()\r\n// - SliderFloat3()\r\n// - SliderFloat4()\r\n// - SliderAngle()\r\n// - SliderInt()\r\n// - SliderInt2()\r\n// - SliderInt3()\r\n// - SliderInt4()\r\n// - VSliderScalar()\r\n// - VSliderFloat()\r\n// - VSliderInt()\r\n//-------------------------------------------------------------------------\r\n\r\n// Convert a value v in the output space of a slider into a parametric position on the slider itself (the logical opposite of ScaleValueFromRatioT)\r\ntemplate<typename TYPE, typename SIGNEDTYPE, typename FLOATTYPE>\r\nfloat ImGui::ScaleRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_min, TYPE v_max, bool is_logarithmic, float logarithmic_zero_epsilon, float zero_deadzone_halfsize)\r\n{\r\n    if (v_min == v_max)\r\n        return 0.0f;\r\n    IM_UNUSED(data_type);\r\n\r\n    const TYPE v_clamped = (v_min < v_max) ? ImClamp(v, v_min, v_max) : ImClamp(v, v_max, v_min);\r\n    if (is_logarithmic)\r\n    {\r\n        bool flipped = v_max < v_min;\r\n\r\n        if (flipped) // Handle the case where the range is backwards\r\n            ImSwap(v_min, v_max);\r\n\r\n        // Fudge min/max to avoid getting close to log(0)\r\n        FLOATTYPE v_min_fudged = (ImAbs((FLOATTYPE)v_min) < logarithmic_zero_epsilon) ? ((v_min < 0.0f) ? -logarithmic_zero_epsilon : logarithmic_zero_epsilon) : (FLOATTYPE)v_min;\r\n        FLOATTYPE v_max_fudged = (ImAbs((FLOATTYPE)v_max) < logarithmic_zero_epsilon) ? ((v_max < 0.0f) ? -logarithmic_zero_epsilon : logarithmic_zero_epsilon) : (FLOATTYPE)v_max;\r\n\r\n        // Awkward special cases - we need ranges of the form (-100 .. 0) to convert to (-100 .. -epsilon), not (-100 .. epsilon)\r\n        if ((v_min == 0.0f) && (v_max < 0.0f))\r\n            v_min_fudged = -logarithmic_zero_epsilon;\r\n        else if ((v_max == 0.0f) && (v_min < 0.0f))\r\n            v_max_fudged = -logarithmic_zero_epsilon;\r\n\r\n        float result;\r\n\r\n        if (v_clamped <= v_min_fudged)\r\n            result = 0.0f; // Workaround for values that are in-range but below our fudge\r\n        else if (v_clamped >= v_max_fudged)\r\n            result = 1.0f; // Workaround for values that are in-range but above our fudge\r\n        else if ((v_min * v_max) < 0.0f) // Range crosses zero, so split into two portions\r\n        {\r\n            float zero_point_center = (-(float)v_min) / ((float)v_max - (float)v_min); // The zero point in parametric space.  There's an argument we should take the logarithmic nature into account when calculating this, but for now this should do (and the most common case of a symmetrical range works fine)\r\n            float zero_point_snap_L = zero_point_center - zero_deadzone_halfsize;\r\n            float zero_point_snap_R = zero_point_center + zero_deadzone_halfsize;\r\n            if (v == 0.0f)\r\n                result = zero_point_center; // Special case for exactly zero\r\n            else if (v < 0.0f)\r\n                result = (1.0f - (float)(ImLog(-(FLOATTYPE)v_clamped / logarithmic_zero_epsilon) / ImLog(-v_min_fudged / logarithmic_zero_epsilon))) * zero_point_snap_L;\r\n            else\r\n                result = zero_point_snap_R + ((float)(ImLog((FLOATTYPE)v_clamped / logarithmic_zero_epsilon) / ImLog(v_max_fudged / logarithmic_zero_epsilon)) * (1.0f - zero_point_snap_R));\r\n        }\r\n        else if ((v_min < 0.0f) || (v_max < 0.0f)) // Entirely negative slider\r\n            result = 1.0f - (float)(ImLog(-(FLOATTYPE)v_clamped / -v_max_fudged) / ImLog(-v_min_fudged / -v_max_fudged));\r\n        else\r\n            result = (float)(ImLog((FLOATTYPE)v_clamped / v_min_fudged) / ImLog(v_max_fudged / v_min_fudged));\r\n\r\n        return flipped ? (1.0f - result) : result;\r\n    }\r\n\r\n    // Linear slider\r\n    return (float)((FLOATTYPE)(SIGNEDTYPE)(v_clamped - v_min) / (FLOATTYPE)(SIGNEDTYPE)(v_max - v_min));\r\n}\r\n\r\n// Convert a parametric position on a slider into a value v in the output space (the logical opposite of ScaleRatioFromValueT)\r\ntemplate<typename TYPE, typename SIGNEDTYPE, typename FLOATTYPE>\r\nTYPE ImGui::ScaleValueFromRatioT(ImGuiDataType data_type, float t, TYPE v_min, TYPE v_max, bool is_logarithmic, float logarithmic_zero_epsilon, float zero_deadzone_halfsize)\r\n{\r\n    if (v_min == v_max)\r\n        return v_min;\r\n    const bool is_floating_point = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double);\r\n\r\n    TYPE result;\r\n    if (is_logarithmic)\r\n    {\r\n        // We special-case the extents because otherwise our fudging can lead to \"mathematically correct\" but non-intuitive behaviors like a fully-left slider not actually reaching the minimum value\r\n        if (t <= 0.0f)\r\n            result = v_min;\r\n        else if (t >= 1.0f)\r\n            result = v_max;\r\n        else\r\n        {\r\n            bool flipped = v_max < v_min; // Check if range is \"backwards\"\r\n\r\n            // Fudge min/max to avoid getting silly results close to zero\r\n            FLOATTYPE v_min_fudged = (ImAbs((FLOATTYPE)v_min) < logarithmic_zero_epsilon) ? ((v_min < 0.0f) ? -logarithmic_zero_epsilon : logarithmic_zero_epsilon) : (FLOATTYPE)v_min;\r\n            FLOATTYPE v_max_fudged = (ImAbs((FLOATTYPE)v_max) < logarithmic_zero_epsilon) ? ((v_max < 0.0f) ? -logarithmic_zero_epsilon : logarithmic_zero_epsilon) : (FLOATTYPE)v_max;\r\n\r\n            if (flipped)\r\n                ImSwap(v_min_fudged, v_max_fudged);\r\n\r\n            // Awkward special case - we need ranges of the form (-100 .. 0) to convert to (-100 .. -epsilon), not (-100 .. epsilon)\r\n            if ((v_max == 0.0f) && (v_min < 0.0f))\r\n                v_max_fudged = -logarithmic_zero_epsilon;\r\n\r\n            float t_with_flip = flipped ? (1.0f - t) : t; // t, but flipped if necessary to account for us flipping the range\r\n\r\n            if ((v_min * v_max) < 0.0f) // Range crosses zero, so we have to do this in two parts\r\n            {\r\n                float zero_point_center = (-(float)ImMin(v_min, v_max)) / ImAbs((float)v_max - (float)v_min); // The zero point in parametric space\r\n                float zero_point_snap_L = zero_point_center - zero_deadzone_halfsize;\r\n                float zero_point_snap_R = zero_point_center + zero_deadzone_halfsize;\r\n                if (t_with_flip >= zero_point_snap_L && t_with_flip <= zero_point_snap_R)\r\n                    result = (TYPE)0.0f; // Special case to make getting exactly zero possible (the epsilon prevents it otherwise)\r\n                else if (t_with_flip < zero_point_center)\r\n                    result = (TYPE)-(logarithmic_zero_epsilon * ImPow(-v_min_fudged / logarithmic_zero_epsilon, (FLOATTYPE)(1.0f - (t_with_flip / zero_point_snap_L))));\r\n                else\r\n                    result = (TYPE)(logarithmic_zero_epsilon * ImPow(v_max_fudged / logarithmic_zero_epsilon, (FLOATTYPE)((t_with_flip - zero_point_snap_R) / (1.0f - zero_point_snap_R))));\r\n            }\r\n            else if ((v_min < 0.0f) || (v_max < 0.0f)) // Entirely negative slider\r\n                result = (TYPE)-(-v_max_fudged * ImPow(-v_min_fudged / -v_max_fudged, (FLOATTYPE)(1.0f - t_with_flip)));\r\n            else\r\n                result = (TYPE)(v_min_fudged * ImPow(v_max_fudged / v_min_fudged, (FLOATTYPE)t_with_flip));\r\n        }\r\n    }\r\n    else\r\n    {\r\n        // Linear slider\r\n        if (is_floating_point)\r\n        {\r\n            result = ImLerp(v_min, v_max, t);\r\n        }\r\n        else\r\n        {\r\n            // - For integer values we want the clicking position to match the grab box so we round above\r\n            //   This code is carefully tuned to work with large values (e.g. high ranges of U64) while preserving this property..\r\n            // - Not doing a *1.0 multiply at the end of a range as it tends to be lossy. While absolute aiming at a large s64/u64\r\n            //   range is going to be imprecise anyway, with this check we at least make the edge values matches expected limits.\r\n            if (t < 1.0)\r\n            {\r\n                FLOATTYPE v_new_off_f = (SIGNEDTYPE)(v_max - v_min) * t;\r\n                result = (TYPE)((SIGNEDTYPE)v_min + (SIGNEDTYPE)(v_new_off_f + (FLOATTYPE)(v_min > v_max ? -0.5 : 0.5)));\r\n            }\r\n            else\r\n            {\r\n                result = v_max;\r\n            }\r\n        }\r\n    }\r\n\r\n    return result;\r\n}\r\n\r\n// FIXME: Move more of the code into SliderBehavior()\r\ntemplate<typename TYPE, typename SIGNEDTYPE, typename FLOATTYPE>\r\nbool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, TYPE* v, const TYPE v_min, const TYPE v_max, const char* format, ImGuiSliderFlags flags, ImRect* out_grab_bb)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    const ImGuiStyle& style = g.Style;\r\n\r\n    const ImGuiAxis axis = (flags & ImGuiSliderFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X;\r\n    const bool is_logarithmic = (flags & ImGuiSliderFlags_Logarithmic) != 0;\r\n    const bool is_floating_point = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double);\r\n\r\n    const float grab_padding = 2.0f;\r\n    const float slider_sz = (bb.Max[axis] - bb.Min[axis]) - grab_padding * 2.0f;\r\n    float grab_sz = style.GrabMinSize;\r\n    SIGNEDTYPE v_range = (v_min < v_max ? v_max - v_min : v_min - v_max);\r\n    if (!is_floating_point && v_range >= 0)                                             // v_range < 0 may happen on integer overflows\r\n        grab_sz = ImMax((float)(slider_sz / (v_range + 1)), style.GrabMinSize);  // For integer sliders: if possible have the grab size represent 1 unit\r\n    grab_sz = ImMin(grab_sz, slider_sz);\r\n    const float slider_usable_sz = slider_sz - grab_sz;\r\n    const float slider_usable_pos_min = bb.Min[axis] + grab_padding + grab_sz * 0.5f;\r\n    const float slider_usable_pos_max = bb.Max[axis] - grab_padding - grab_sz * 0.5f;\r\n\r\n    float logarithmic_zero_epsilon = 0.0f; // Only valid when is_logarithmic is true\r\n    float zero_deadzone_halfsize = 0.0f; // Only valid when is_logarithmic is true\r\n    if (is_logarithmic)\r\n    {\r\n        // When using logarithmic sliders, we need to clamp to avoid hitting zero, but our choice of clamp value greatly affects slider precision. We attempt to use the specified precision to estimate a good lower bound.\r\n        const int decimal_precision = is_floating_point ? ImParseFormatPrecision(format, 3) : 1;\r\n        logarithmic_zero_epsilon = ImPow(0.1f, (float)decimal_precision);\r\n        zero_deadzone_halfsize = (style.LogSliderDeadzone * 0.5f) / ImMax(slider_usable_sz, 1.0f);\r\n    }\r\n\r\n    // Process interacting with the slider\r\n    bool value_changed = false;\r\n    if (g.ActiveId == id)\r\n    {\r\n        bool set_new_value = false;\r\n        float clicked_t = 0.0f;\r\n        if (g.ActiveIdSource == ImGuiInputSource_Mouse)\r\n        {\r\n            if (!g.IO.MouseDown[0])\r\n            {\r\n                ClearActiveID();\r\n            }\r\n            else\r\n            {\r\n                const float mouse_abs_pos = g.IO.MousePos[axis];\r\n                clicked_t = (slider_usable_sz > 0.0f) ? ImClamp((mouse_abs_pos - slider_usable_pos_min) / slider_usable_sz, 0.0f, 1.0f) : 0.0f;\r\n                if (axis == ImGuiAxis_Y)\r\n                    clicked_t = 1.0f - clicked_t;\r\n                set_new_value = true;\r\n            }\r\n        }\r\n        else if (g.ActiveIdSource == ImGuiInputSource_Nav)\r\n        {\r\n            if (g.ActiveIdIsJustActivated)\r\n            {\r\n                g.SliderCurrentAccum = 0.0f; // Reset any stored nav delta upon activation\r\n                g.SliderCurrentAccumDirty = false;\r\n            }\r\n\r\n            const ImVec2 input_delta2 = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard | ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_RepeatFast, 0.0f, 0.0f);\r\n            float input_delta = (axis == ImGuiAxis_X) ? input_delta2.x : -input_delta2.y;\r\n            if (input_delta != 0.0f)\r\n            {\r\n                const int decimal_precision = is_floating_point ? ImParseFormatPrecision(format, 3) : 0;\r\n                if (decimal_precision > 0)\r\n                {\r\n                    input_delta /= 100.0f;    // Gamepad/keyboard tweak speeds in % of slider bounds\r\n                    if (IsNavInputDown(ImGuiNavInput_TweakSlow))\r\n                        input_delta /= 10.0f;\r\n                }\r\n                else\r\n                {\r\n                    if ((v_range >= -100.0f && v_range <= 100.0f) || IsNavInputDown(ImGuiNavInput_TweakSlow))\r\n                        input_delta = ((input_delta < 0.0f) ? -1.0f : +1.0f) / (float)v_range; // Gamepad/keyboard tweak speeds in integer steps\r\n                    else\r\n                        input_delta /= 100.0f;\r\n                }\r\n                if (IsNavInputDown(ImGuiNavInput_TweakFast))\r\n                    input_delta *= 10.0f;\r\n\r\n                g.SliderCurrentAccum += input_delta;\r\n                g.SliderCurrentAccumDirty = true;\r\n            }\r\n\r\n            float delta = g.SliderCurrentAccum;\r\n            if (g.NavActivatePressedId == id && !g.ActiveIdIsJustActivated)\r\n            {\r\n                ClearActiveID();\r\n            }\r\n            else if (g.SliderCurrentAccumDirty)\r\n            {\r\n                clicked_t = ScaleRatioFromValueT<TYPE, SIGNEDTYPE, FLOATTYPE>(data_type, *v, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize);\r\n\r\n                if ((clicked_t >= 1.0f && delta > 0.0f) || (clicked_t <= 0.0f && delta < 0.0f)) // This is to avoid applying the saturation when already past the limits\r\n                {\r\n                    set_new_value = false;\r\n                    g.SliderCurrentAccum = 0.0f; // If pushing up against the limits, don't continue to accumulate\r\n                }\r\n                else\r\n                {\r\n                    set_new_value = true;\r\n                    float old_clicked_t = clicked_t;\r\n                    clicked_t = ImSaturate(clicked_t + delta);\r\n\r\n                    // Calculate what our \"new\" clicked_t will be, and thus how far we actually moved the slider, and subtract this from the accumulator\r\n                    TYPE v_new = ScaleValueFromRatioT<TYPE, SIGNEDTYPE, FLOATTYPE>(data_type, clicked_t, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize);\r\n                    if (!(flags & ImGuiSliderFlags_NoRoundToFormat))\r\n                        v_new = RoundScalarWithFormatT<TYPE, SIGNEDTYPE>(format, data_type, v_new);\r\n                    float new_clicked_t = ScaleRatioFromValueT<TYPE, SIGNEDTYPE, FLOATTYPE>(data_type, v_new, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize);\r\n\r\n                    if (delta > 0)\r\n                        g.SliderCurrentAccum -= ImMin(new_clicked_t - old_clicked_t, delta);\r\n                    else\r\n                        g.SliderCurrentAccum -= ImMax(new_clicked_t - old_clicked_t, delta);\r\n                }\r\n\r\n                g.SliderCurrentAccumDirty = false;\r\n            }\r\n        }\r\n\r\n        if (set_new_value)\r\n        {\r\n            TYPE v_new = ScaleValueFromRatioT<TYPE, SIGNEDTYPE, FLOATTYPE>(data_type, clicked_t, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize);\r\n\r\n            // Round to user desired precision based on format string\r\n            if (!(flags & ImGuiSliderFlags_NoRoundToFormat))\r\n                v_new = RoundScalarWithFormatT<TYPE, SIGNEDTYPE>(format, data_type, v_new);\r\n\r\n            // Apply result\r\n            if (*v != v_new)\r\n            {\r\n                *v = v_new;\r\n                value_changed = true;\r\n            }\r\n        }\r\n    }\r\n\r\n    if (slider_sz < 1.0f)\r\n    {\r\n        *out_grab_bb = ImRect(bb.Min, bb.Min);\r\n    }\r\n    else\r\n    {\r\n        // Output grab position so it can be displayed by the caller\r\n        float grab_t = ScaleRatioFromValueT<TYPE, SIGNEDTYPE, FLOATTYPE>(data_type, *v, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize);\r\n        if (axis == ImGuiAxis_Y)\r\n            grab_t = 1.0f - grab_t;\r\n        const float grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t);\r\n        if (axis == ImGuiAxis_X)\r\n            *out_grab_bb = ImRect(grab_pos - grab_sz * 0.5f, bb.Min.y + grab_padding, grab_pos + grab_sz * 0.5f, bb.Max.y - grab_padding);\r\n        else\r\n            *out_grab_bb = ImRect(bb.Min.x + grab_padding, grab_pos - grab_sz * 0.5f, bb.Max.x - grab_padding, grab_pos + grab_sz * 0.5f);\r\n    }\r\n\r\n    return value_changed;\r\n}\r\n\r\n// For 32-bit and larger types, slider bounds are limited to half the natural type range.\r\n// So e.g. an integer Slider between INT_MAX-10 and INT_MAX will fail, but an integer Slider between INT_MAX/2-10 and INT_MAX/2 will be ok.\r\n// It would be possible to lift that limitation with some work but it doesn't seem to be worth it for sliders.\r\nbool ImGui::SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* p_v, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags, ImRect* out_grab_bb)\r\n{\r\n    // Read imgui.cpp \"API BREAKING CHANGES\" section for 1.78 if you hit this assert.\r\n    IM_ASSERT((flags == 1 || (flags & ImGuiSliderFlags_InvalidMask_) == 0) && \"Invalid ImGuiSliderFlags flag!  Has the 'float power' argument been mistakenly cast to flags? Call function with ImGuiSliderFlags_Logarithmic flags instead.\");\r\n\r\n    ImGuiContext& g = *GImGui;\r\n    if ((g.LastItemData.InFlags & ImGuiItemFlags_ReadOnly) || (flags & ImGuiSliderFlags_ReadOnly))\r\n        return false;\r\n\r\n    switch (data_type)\r\n    {\r\n    case ImGuiDataType_S8:  { ImS32 v32 = (ImS32)*(ImS8*)p_v;  bool r = SliderBehaviorT<ImS32, ImS32, float>(bb, id, ImGuiDataType_S32, &v32, *(const ImS8*)p_min,  *(const ImS8*)p_max,  format, flags, out_grab_bb); if (r) *(ImS8*)p_v  = (ImS8)v32;  return r; }\r\n    case ImGuiDataType_U8:  { ImU32 v32 = (ImU32)*(ImU8*)p_v;  bool r = SliderBehaviorT<ImU32, ImS32, float>(bb, id, ImGuiDataType_U32, &v32, *(const ImU8*)p_min,  *(const ImU8*)p_max,  format, flags, out_grab_bb); if (r) *(ImU8*)p_v  = (ImU8)v32;  return r; }\r\n    case ImGuiDataType_S16: { ImS32 v32 = (ImS32)*(ImS16*)p_v; bool r = SliderBehaviorT<ImS32, ImS32, float>(bb, id, ImGuiDataType_S32, &v32, *(const ImS16*)p_min, *(const ImS16*)p_max, format, flags, out_grab_bb); if (r) *(ImS16*)p_v = (ImS16)v32; return r; }\r\n    case ImGuiDataType_U16: { ImU32 v32 = (ImU32)*(ImU16*)p_v; bool r = SliderBehaviorT<ImU32, ImS32, float>(bb, id, ImGuiDataType_U32, &v32, *(const ImU16*)p_min, *(const ImU16*)p_max, format, flags, out_grab_bb); if (r) *(ImU16*)p_v = (ImU16)v32; return r; }\r\n    case ImGuiDataType_S32:\r\n        IM_ASSERT(*(const ImS32*)p_min >= IM_S32_MIN / 2 && *(const ImS32*)p_max <= IM_S32_MAX / 2);\r\n        return SliderBehaviorT<ImS32, ImS32, float >(bb, id, data_type, (ImS32*)p_v,  *(const ImS32*)p_min,  *(const ImS32*)p_max,  format, flags, out_grab_bb);\r\n    case ImGuiDataType_U32:\r\n        IM_ASSERT(*(const ImU32*)p_max <= IM_U32_MAX / 2);\r\n        return SliderBehaviorT<ImU32, ImS32, float >(bb, id, data_type, (ImU32*)p_v,  *(const ImU32*)p_min,  *(const ImU32*)p_max,  format, flags, out_grab_bb);\r\n    case ImGuiDataType_S64:\r\n        IM_ASSERT(*(const ImS64*)p_min >= IM_S64_MIN / 2 && *(const ImS64*)p_max <= IM_S64_MAX / 2);\r\n        return SliderBehaviorT<ImS64, ImS64, double>(bb, id, data_type, (ImS64*)p_v,  *(const ImS64*)p_min,  *(const ImS64*)p_max,  format, flags, out_grab_bb);\r\n    case ImGuiDataType_U64:\r\n        IM_ASSERT(*(const ImU64*)p_max <= IM_U64_MAX / 2);\r\n        return SliderBehaviorT<ImU64, ImS64, double>(bb, id, data_type, (ImU64*)p_v,  *(const ImU64*)p_min,  *(const ImU64*)p_max,  format, flags, out_grab_bb);\r\n    case ImGuiDataType_Float:\r\n        IM_ASSERT(*(const float*)p_min >= -FLT_MAX / 2.0f && *(const float*)p_max <= FLT_MAX / 2.0f);\r\n        return SliderBehaviorT<float, float, float >(bb, id, data_type, (float*)p_v,  *(const float*)p_min,  *(const float*)p_max,  format, flags, out_grab_bb);\r\n    case ImGuiDataType_Double:\r\n        IM_ASSERT(*(const double*)p_min >= -DBL_MAX / 2.0f && *(const double*)p_max <= DBL_MAX / 2.0f);\r\n        return SliderBehaviorT<double, double, double>(bb, id, data_type, (double*)p_v, *(const double*)p_min, *(const double*)p_max, format, flags, out_grab_bb);\r\n    case ImGuiDataType_COUNT: break;\r\n    }\r\n    IM_ASSERT(0);\r\n    return false;\r\n}\r\n\r\n// Note: p_data, p_min and p_max are _pointers_ to a memory address holding the data. For a slider, they are all required.\r\n// Read code of e.g. SliderFloat(), SliderInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly.\r\nbool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return false;\r\n\r\n    ImGuiContext& g = *GImGui;\r\n    const ImGuiStyle& style = g.Style;\r\n    const ImGuiID id = window->GetID(label);\r\n    const float w = CalcItemWidth();\r\n\r\n    const ImVec2 label_size = CalcTextSize(label, NULL, true);\r\n    const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y * 2.0f));\r\n    const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));\r\n\r\n    const bool temp_input_allowed = (flags & ImGuiSliderFlags_NoInput) == 0;\r\n    ItemSize(total_bb, style.FramePadding.y);\r\n    if (!ItemAdd(total_bb, id, &frame_bb, temp_input_allowed ? ImGuiItemFlags_Inputable : 0))\r\n        return false;\r\n\r\n    // Default format string when passing NULL\r\n    if (format == NULL)\r\n        format = DataTypeGetInfo(data_type)->PrintFmt;\r\n    else if (data_type == ImGuiDataType_S32 && strcmp(format, \"%d\") != 0) // (FIXME-LEGACY: Patch old \"%.0f\" format string to use \"%d\", read function more details.)\r\n        format = PatchFormatStringFloatToInt(format);\r\n\r\n    // Tabbing or CTRL-clicking on Slider turns it into an input box\r\n    const bool hovered = ItemHoverable(frame_bb, id);\r\n    bool temp_input_is_active = temp_input_allowed && TempInputIsActive(id);\r\n    if (!temp_input_is_active)\r\n    {\r\n        const bool input_requested_by_tabbing = temp_input_allowed && (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_FocusedByTabbing) != 0;\r\n        const bool clicked = (hovered && g.IO.MouseClicked[0]);\r\n        if (input_requested_by_tabbing || clicked || g.NavActivateId == id || g.NavActivateInputId == id)\r\n        {\r\n            SetActiveID(id, window);\r\n            SetFocusID(id, window);\r\n            FocusWindow(window);\r\n            g.ActiveIdUsingNavDirMask |= (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right);\r\n            if (temp_input_allowed && (input_requested_by_tabbing || (clicked && g.IO.KeyCtrl) || g.NavActivateInputId == id))\r\n                temp_input_is_active = true;\r\n        }\r\n    }\r\n\r\n    if (temp_input_is_active)\r\n    {\r\n        // Only clamp CTRL+Click input when ImGuiSliderFlags_AlwaysClamp is set\r\n        const bool is_clamp_input = (flags & ImGuiSliderFlags_AlwaysClamp) != 0;\r\n        return TempInputScalar(frame_bb, id, label, data_type, p_data, format, is_clamp_input ? p_min : NULL, is_clamp_input ? p_max : NULL);\r\n    }\r\n\r\n    // Draw frame\r\n    const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);\r\n    RenderNavHighlight(frame_bb, id);\r\n    RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, g.Style.FrameRounding);\r\n\r\n    // Slider behavior\r\n    ImRect grab_bb;\r\n    const bool value_changed = SliderBehavior(frame_bb, id, data_type, p_data, p_min, p_max, format, flags, &grab_bb);\r\n    if (value_changed)\r\n        MarkItemEdited(id);\r\n\r\n    // Render grab\r\n    if (grab_bb.Max.x > grab_bb.Min.x)\r\n        window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, GetColorU32(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab), style.GrabRounding);\r\n\r\n    // Display value using user-provided display format so user can add prefix/suffix/decorations to the value.\r\n    char value_buf[64];\r\n    const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_ARRAYSIZE(value_buf), data_type, p_data, format);\r\n    if (g.LogEnabled)\r\n        LogSetNextTextDecoration(\"{\", \"}\");\r\n    RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f, 0.5f));\r\n\r\n    if (label_size.x > 0.0f)\r\n        RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);\r\n\r\n    IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags);\r\n    return value_changed;\r\n}\r\n\r\n// Add multiple sliders on 1 line for compact edition of multiple components\r\nbool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format, ImGuiSliderFlags flags)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return false;\r\n\r\n    ImGuiContext& g = *GImGui;\r\n    bool value_changed = false;\r\n    BeginGroup();\r\n    PushID(label);\r\n    PushMultiItemsWidths(components, CalcItemWidth());\r\n    size_t type_size = GDataTypeInfo[data_type].Size;\r\n    for (int i = 0; i < components; i++)\r\n    {\r\n        PushID(i);\r\n        if (i > 0)\r\n            SameLine(0, g.Style.ItemInnerSpacing.x);\r\n        value_changed |= SliderScalar(\"\", data_type, v, v_min, v_max, format, flags);\r\n        PopID();\r\n        PopItemWidth();\r\n        v = (void*)((char*)v + type_size);\r\n    }\r\n    PopID();\r\n\r\n    const char* label_end = FindRenderedTextEnd(label);\r\n    if (label != label_end)\r\n    {\r\n        SameLine(0, g.Style.ItemInnerSpacing.x);\r\n        TextEx(label, label_end);\r\n    }\r\n\r\n    EndGroup();\r\n    return value_changed;\r\n}\r\n\r\nbool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, ImGuiSliderFlags flags)\r\n{\r\n    return SliderScalar(label, ImGuiDataType_Float, v, &v_min, &v_max, format, flags);\r\n}\r\n\r\nbool ImGui::SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, ImGuiSliderFlags flags)\r\n{\r\n    return SliderScalarN(label, ImGuiDataType_Float, v, 2, &v_min, &v_max, format, flags);\r\n}\r\n\r\nbool ImGui::SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, ImGuiSliderFlags flags)\r\n{\r\n    return SliderScalarN(label, ImGuiDataType_Float, v, 3, &v_min, &v_max, format, flags);\r\n}\r\n\r\nbool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, ImGuiSliderFlags flags)\r\n{\r\n    return SliderScalarN(label, ImGuiDataType_Float, v, 4, &v_min, &v_max, format, flags);\r\n}\r\n\r\nbool ImGui::SliderAngle(const char* label, float* v_rad, float v_degrees_min, float v_degrees_max, const char* format, ImGuiSliderFlags flags)\r\n{\r\n    if (format == NULL)\r\n        format = \"%.0f deg\";\r\n    float v_deg = (*v_rad) * 360.0f / (2 * IM_PI);\r\n    bool value_changed = SliderFloat(label, &v_deg, v_degrees_min, v_degrees_max, format, flags);\r\n    *v_rad = v_deg * (2 * IM_PI) / 360.0f;\r\n    return value_changed;\r\n}\r\n\r\nbool ImGui::SliderInt(const char* label, int* v, int v_min, int v_max, const char* format, ImGuiSliderFlags flags)\r\n{\r\n    return SliderScalar(label, ImGuiDataType_S32, v, &v_min, &v_max, format, flags);\r\n}\r\n\r\nbool ImGui::SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format, ImGuiSliderFlags flags)\r\n{\r\n    return SliderScalarN(label, ImGuiDataType_S32, v, 2, &v_min, &v_max, format, flags);\r\n}\r\n\r\nbool ImGui::SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format, ImGuiSliderFlags flags)\r\n{\r\n    return SliderScalarN(label, ImGuiDataType_S32, v, 3, &v_min, &v_max, format, flags);\r\n}\r\n\r\nbool ImGui::SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format, ImGuiSliderFlags flags)\r\n{\r\n    return SliderScalarN(label, ImGuiDataType_S32, v, 4, &v_min, &v_max, format, flags);\r\n}\r\n\r\nbool ImGui::VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return false;\r\n\r\n    ImGuiContext& g = *GImGui;\r\n    const ImGuiStyle& style = g.Style;\r\n    const ImGuiID id = window->GetID(label);\r\n\r\n    const ImVec2 label_size = CalcTextSize(label, NULL, true);\r\n    const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size);\r\n    const ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));\r\n\r\n    ItemSize(bb, style.FramePadding.y);\r\n    if (!ItemAdd(frame_bb, id))\r\n        return false;\r\n\r\n    // Default format string when passing NULL\r\n    if (format == NULL)\r\n        format = DataTypeGetInfo(data_type)->PrintFmt;\r\n    else if (data_type == ImGuiDataType_S32 && strcmp(format, \"%d\") != 0) // (FIXME-LEGACY: Patch old \"%.0f\" format string to use \"%d\", read function more details.)\r\n        format = PatchFormatStringFloatToInt(format);\r\n\r\n    const bool hovered = ItemHoverable(frame_bb, id);\r\n    if ((hovered && g.IO.MouseClicked[0]) || g.NavActivateId == id || g.NavActivateInputId == id)\r\n    {\r\n        SetActiveID(id, window);\r\n        SetFocusID(id, window);\r\n        FocusWindow(window);\r\n        g.ActiveIdUsingNavDirMask |= (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down);\r\n    }\r\n\r\n    // Draw frame\r\n    const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);\r\n    RenderNavHighlight(frame_bb, id);\r\n    RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, g.Style.FrameRounding);\r\n\r\n    // Slider behavior\r\n    ImRect grab_bb;\r\n    const bool value_changed = SliderBehavior(frame_bb, id, data_type, p_data, p_min, p_max, format, flags | ImGuiSliderFlags_Vertical, &grab_bb);\r\n    if (value_changed)\r\n        MarkItemEdited(id);\r\n\r\n    // Render grab\r\n    if (grab_bb.Max.y > grab_bb.Min.y)\r\n        window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, GetColorU32(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab), style.GrabRounding);\r\n\r\n    // Display value using user-provided display format so user can add prefix/suffix/decorations to the value.\r\n    // For the vertical slider we allow centered text to overlap the frame padding\r\n    char value_buf[64];\r\n    const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_ARRAYSIZE(value_buf), data_type, p_data, format);\r\n    RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f, 0.0f));\r\n    if (label_size.x > 0.0f)\r\n        RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);\r\n\r\n    return value_changed;\r\n}\r\n\r\nbool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format, ImGuiSliderFlags flags)\r\n{\r\n    return VSliderScalar(label, size, ImGuiDataType_Float, v, &v_min, &v_max, format, flags);\r\n}\r\n\r\nbool ImGui::VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format, ImGuiSliderFlags flags)\r\n{\r\n    return VSliderScalar(label, size, ImGuiDataType_S32, v, &v_min, &v_max, format, flags);\r\n}\r\n\r\n#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS\r\n\r\n// Obsolete versions with power parameter. See https://github.com/ocornut/imgui/issues/3361 for details.\r\nbool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, float power)\r\n{\r\n    ImGuiSliderFlags slider_flags = ImGuiSliderFlags_None;\r\n    if (power != 1.0f)\r\n    {\r\n        IM_ASSERT(power == 1.0f && \"Call function with ImGuiSliderFlags_Logarithmic flags instead of using the old 'float power' function!\");\r\n        slider_flags |= ImGuiSliderFlags_Logarithmic;   // Fallback for non-asserting paths\r\n    }\r\n    return SliderScalar(label, data_type, p_data, p_min, p_max, format, slider_flags);\r\n}\r\n\r\nbool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format, float power)\r\n{\r\n    ImGuiSliderFlags slider_flags = ImGuiSliderFlags_None;\r\n    if (power != 1.0f)\r\n    {\r\n        IM_ASSERT(power == 1.0f && \"Call function with ImGuiSliderFlags_Logarithmic flags instead of using the old 'float power' function!\");\r\n        slider_flags |= ImGuiSliderFlags_Logarithmic;   // Fallback for non-asserting paths\r\n    }\r\n    return SliderScalarN(label, data_type, v, components, v_min, v_max, format, slider_flags);\r\n}\r\n\r\n#endif // IMGUI_DISABLE_OBSOLETE_FUNCTIONS\r\n\r\n//-------------------------------------------------------------------------\r\n// [SECTION] Widgets: InputScalar, InputFloat, InputInt, etc.\r\n//-------------------------------------------------------------------------\r\n// - ImParseFormatFindStart() [Internal]\r\n// - ImParseFormatFindEnd() [Internal]\r\n// - ImParseFormatTrimDecorations() [Internal]\r\n// - ImParseFormatPrecision() [Internal]\r\n// - TempInputTextScalar() [Internal]\r\n// - InputScalar()\r\n// - InputScalarN()\r\n// - InputFloat()\r\n// - InputFloat2()\r\n// - InputFloat3()\r\n// - InputFloat4()\r\n// - InputInt()\r\n// - InputInt2()\r\n// - InputInt3()\r\n// - InputInt4()\r\n// - InputDouble()\r\n//-------------------------------------------------------------------------\r\n\r\n// We don't use strchr() because our strings are usually very short and often start with '%'\r\nconst char* ImParseFormatFindStart(const char* fmt)\r\n{\r\n    while (char c = fmt[0])\r\n    {\r\n        if (c == '%' && fmt[1] != '%')\r\n            return fmt;\r\n        else if (c == '%')\r\n            fmt++;\r\n        fmt++;\r\n    }\r\n    return fmt;\r\n}\r\n\r\nconst char* ImParseFormatFindEnd(const char* fmt)\r\n{\r\n    // Printf/scanf types modifiers: I/L/h/j/l/t/w/z. Other uppercase letters qualify as types aka end of the format.\r\n    if (fmt[0] != '%')\r\n        return fmt;\r\n    const unsigned int ignored_uppercase_mask = (1 << ('I'-'A')) | (1 << ('L'-'A'));\r\n    const unsigned int ignored_lowercase_mask = (1 << ('h'-'a')) | (1 << ('j'-'a')) | (1 << ('l'-'a')) | (1 << ('t'-'a')) | (1 << ('w'-'a')) | (1 << ('z'-'a'));\r\n    for (char c; (c = *fmt) != 0; fmt++)\r\n    {\r\n        if (c >= 'A' && c <= 'Z' && ((1 << (c - 'A')) & ignored_uppercase_mask) == 0)\r\n            return fmt + 1;\r\n        if (c >= 'a' && c <= 'z' && ((1 << (c - 'a')) & ignored_lowercase_mask) == 0)\r\n            return fmt + 1;\r\n    }\r\n    return fmt;\r\n}\r\n\r\n// Extract the format out of a format string with leading or trailing decorations\r\n//  fmt = \"blah blah\"  -> return fmt\r\n//  fmt = \"%.3f\"       -> return fmt\r\n//  fmt = \"hello %.3f\" -> return fmt + 6\r\n//  fmt = \"%.3f hello\" -> return buf written with \"%.3f\"\r\nconst char* ImParseFormatTrimDecorations(const char* fmt, char* buf, size_t buf_size)\r\n{\r\n    const char* fmt_start = ImParseFormatFindStart(fmt);\r\n    if (fmt_start[0] != '%')\r\n        return fmt;\r\n    const char* fmt_end = ImParseFormatFindEnd(fmt_start);\r\n    if (fmt_end[0] == 0) // If we only have leading decoration, we don't need to copy the data.\r\n        return fmt_start;\r\n    ImStrncpy(buf, fmt_start, ImMin((size_t)(fmt_end - fmt_start) + 1, buf_size));\r\n    return buf;\r\n}\r\n\r\n// Parse display precision back from the display format string\r\n// FIXME: This is still used by some navigation code path to infer a minimum tweak step, but we should aim to rework widgets so it isn't needed.\r\nint ImParseFormatPrecision(const char* fmt, int default_precision)\r\n{\r\n    fmt = ImParseFormatFindStart(fmt);\r\n    if (fmt[0] != '%')\r\n        return default_precision;\r\n    fmt++;\r\n    while (*fmt >= '0' && *fmt <= '9')\r\n        fmt++;\r\n    int precision = INT_MAX;\r\n    if (*fmt == '.')\r\n    {\r\n        fmt = ImAtoi<int>(fmt + 1, &precision);\r\n        if (precision < 0 || precision > 99)\r\n            precision = default_precision;\r\n    }\r\n    if (*fmt == 'e' || *fmt == 'E') // Maximum precision with scientific notation\r\n        precision = -1;\r\n    if ((*fmt == 'g' || *fmt == 'G') && precision == INT_MAX)\r\n        precision = -1;\r\n    return (precision == INT_MAX) ? default_precision : precision;\r\n}\r\n\r\n// Create text input in place of another active widget (e.g. used when doing a CTRL+Click on drag/slider widgets)\r\n// FIXME: Facilitate using this in variety of other situations.\r\nbool ImGui::TempInputText(const ImRect& bb, ImGuiID id, const char* label, char* buf, int buf_size, ImGuiInputTextFlags flags)\r\n{\r\n    // On the first frame, g.TempInputTextId == 0, then on subsequent frames it becomes == id.\r\n    // We clear ActiveID on the first frame to allow the InputText() taking it back.\r\n    ImGuiContext& g = *GImGui;\r\n    const bool init = (g.TempInputId != id);\r\n    if (init)\r\n        ClearActiveID();\r\n\r\n    g.CurrentWindow->DC.CursorPos = bb.Min;\r\n    bool value_changed = InputTextEx(label, NULL, buf, buf_size, bb.GetSize(), flags | ImGuiInputTextFlags_MergedItem);\r\n    if (init)\r\n    {\r\n        // First frame we started displaying the InputText widget, we expect it to take the active id.\r\n        IM_ASSERT(g.ActiveId == id);\r\n        g.TempInputId = g.ActiveId;\r\n    }\r\n    return value_changed;\r\n}\r\n\r\n// Note that Drag/Slider functions are only forwarding the min/max values clamping values if the ImGuiSliderFlags_AlwaysClamp flag is set!\r\n// This is intended: this way we allow CTRL+Click manual input to set a value out of bounds, for maximum flexibility.\r\n// However this may not be ideal for all uses, as some user code may break on out of bound values.\r\nbool ImGui::TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* p_data, const char* format, const void* p_clamp_min, const void* p_clamp_max)\r\n{\r\n    char fmt_buf[32];\r\n    char data_buf[32];\r\n    format = ImParseFormatTrimDecorations(format, fmt_buf, IM_ARRAYSIZE(fmt_buf));\r\n    DataTypeFormatString(data_buf, IM_ARRAYSIZE(data_buf), data_type, p_data, format);\r\n    ImStrTrimBlanks(data_buf);\r\n\r\n    ImGuiInputTextFlags flags = ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_NoMarkEdited;\r\n    flags |= ((data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double) ? ImGuiInputTextFlags_CharsScientific : ImGuiInputTextFlags_CharsDecimal);\r\n    bool value_changed = false;\r\n    if (TempInputText(bb, id, label, data_buf, IM_ARRAYSIZE(data_buf), flags))\r\n    {\r\n        // Backup old value\r\n        size_t data_type_size = DataTypeGetInfo(data_type)->Size;\r\n        ImGuiDataTypeTempStorage data_backup;\r\n        memcpy(&data_backup, p_data, data_type_size);\r\n\r\n        // Apply new value (or operations) then clamp\r\n        DataTypeApplyFromText(data_buf, data_type, p_data, NULL);\r\n        if (p_clamp_min || p_clamp_max)\r\n        {\r\n            if (p_clamp_min && p_clamp_max && DataTypeCompare(data_type, p_clamp_min, p_clamp_max) > 0)\r\n                ImSwap(p_clamp_min, p_clamp_max);\r\n            DataTypeClamp(data_type, p_data, p_clamp_min, p_clamp_max);\r\n        }\r\n\r\n        // Only mark as edited if new value is different\r\n        value_changed = memcmp(&data_backup, p_data, data_type_size) != 0;\r\n        if (value_changed)\r\n            MarkItemEdited(id);\r\n    }\r\n    return value_changed;\r\n}\r\n\r\n// Note: p_data, p_step, p_step_fast are _pointers_ to a memory address holding the data. For an Input widget, p_step and p_step_fast are optional.\r\n// Read code of e.g. InputFloat(), InputInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly.\r\nbool ImGui::InputScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_step, const void* p_step_fast, const char* format, ImGuiInputTextFlags flags)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return false;\r\n\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiStyle& style = g.Style;\r\n\r\n    if (format == NULL)\r\n        format = DataTypeGetInfo(data_type)->PrintFmt;\r\n\r\n    char buf[64];\r\n    DataTypeFormatString(buf, IM_ARRAYSIZE(buf), data_type, p_data, format);\r\n\r\n    bool value_changed = false;\r\n    if ((flags & (ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsScientific)) == 0)\r\n        flags |= ImGuiInputTextFlags_CharsDecimal;\r\n    flags |= ImGuiInputTextFlags_AutoSelectAll;\r\n    flags |= ImGuiInputTextFlags_NoMarkEdited;  // We call MarkItemEdited() ourselves by comparing the actual data rather than the string.\r\n\r\n    if (p_step != NULL)\r\n    {\r\n        const float button_size = GetFrameHeight();\r\n\r\n        BeginGroup(); // The only purpose of the group here is to allow the caller to query item data e.g. IsItemActive()\r\n        PushID(label);\r\n        SetNextItemWidth(ImMax(1.0f, CalcItemWidth() - (button_size + style.ItemInnerSpacing.x) * 2));\r\n        if (InputText(\"\", buf, IM_ARRAYSIZE(buf), flags)) // PushId(label) + \"\" gives us the expected ID from outside point of view\r\n            value_changed = DataTypeApplyFromText(buf, data_type, p_data, format);\r\n\r\n        // Step buttons\r\n        const ImVec2 backup_frame_padding = style.FramePadding;\r\n        style.FramePadding.x = style.FramePadding.y;\r\n        ImGuiButtonFlags button_flags = ImGuiButtonFlags_Repeat | ImGuiButtonFlags_DontClosePopups;\r\n        if (flags & ImGuiInputTextFlags_ReadOnly)\r\n            BeginDisabled();\r\n        SameLine(0, style.ItemInnerSpacing.x);\r\n        if (ButtonEx(\"-\", ImVec2(button_size, button_size), button_flags))\r\n        {\r\n            DataTypeApplyOp(data_type, '-', p_data, p_data, g.IO.KeyCtrl && p_step_fast ? p_step_fast : p_step);\r\n            value_changed = true;\r\n        }\r\n        SameLine(0, style.ItemInnerSpacing.x);\r\n        if (ButtonEx(\"+\", ImVec2(button_size, button_size), button_flags))\r\n        {\r\n            DataTypeApplyOp(data_type, '+', p_data, p_data, g.IO.KeyCtrl && p_step_fast ? p_step_fast : p_step);\r\n            value_changed = true;\r\n        }\r\n        if (flags & ImGuiInputTextFlags_ReadOnly)\r\n            EndDisabled();\r\n\r\n        const char* label_end = FindRenderedTextEnd(label);\r\n        if (label != label_end)\r\n        {\r\n            SameLine(0, style.ItemInnerSpacing.x);\r\n            TextEx(label, label_end);\r\n        }\r\n        style.FramePadding = backup_frame_padding;\r\n\r\n        PopID();\r\n        EndGroup();\r\n    }\r\n    else\r\n    {\r\n        if (InputText(label, buf, IM_ARRAYSIZE(buf), flags))\r\n            value_changed = DataTypeApplyFromText(buf, data_type, p_data, format);\r\n    }\r\n    if (value_changed)\r\n        MarkItemEdited(g.LastItemData.ID);\r\n\r\n    return value_changed;\r\n}\r\n\r\nbool ImGui::InputScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_step, const void* p_step_fast, const char* format, ImGuiInputTextFlags flags)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return false;\r\n\r\n    ImGuiContext& g = *GImGui;\r\n    bool value_changed = false;\r\n    BeginGroup();\r\n    PushID(label);\r\n    PushMultiItemsWidths(components, CalcItemWidth());\r\n    size_t type_size = GDataTypeInfo[data_type].Size;\r\n    for (int i = 0; i < components; i++)\r\n    {\r\n        PushID(i);\r\n        if (i > 0)\r\n            SameLine(0, g.Style.ItemInnerSpacing.x);\r\n        value_changed |= InputScalar(\"\", data_type, p_data, p_step, p_step_fast, format, flags);\r\n        PopID();\r\n        PopItemWidth();\r\n        p_data = (void*)((char*)p_data + type_size);\r\n    }\r\n    PopID();\r\n\r\n    const char* label_end = FindRenderedTextEnd(label);\r\n    if (label != label_end)\r\n    {\r\n        SameLine(0.0f, g.Style.ItemInnerSpacing.x);\r\n        TextEx(label, label_end);\r\n    }\r\n\r\n    EndGroup();\r\n    return value_changed;\r\n}\r\n\r\nbool ImGui::InputFloat(const char* label, float* v, float step, float step_fast, const char* format, ImGuiInputTextFlags flags)\r\n{\r\n    flags |= ImGuiInputTextFlags_CharsScientific;\r\n    return InputScalar(label, ImGuiDataType_Float, (void*)v, (void*)(step > 0.0f ? &step : NULL), (void*)(step_fast > 0.0f ? &step_fast : NULL), format, flags);\r\n}\r\n\r\nbool ImGui::InputFloat2(const char* label, float v[2], const char* format, ImGuiInputTextFlags flags)\r\n{\r\n    return InputScalarN(label, ImGuiDataType_Float, v, 2, NULL, NULL, format, flags);\r\n}\r\n\r\nbool ImGui::InputFloat3(const char* label, float v[3], const char* format, ImGuiInputTextFlags flags)\r\n{\r\n    return InputScalarN(label, ImGuiDataType_Float, v, 3, NULL, NULL, format, flags);\r\n}\r\n\r\nbool ImGui::InputFloat4(const char* label, float v[4], const char* format, ImGuiInputTextFlags flags)\r\n{\r\n    return InputScalarN(label, ImGuiDataType_Float, v, 4, NULL, NULL, format, flags);\r\n}\r\n\r\nbool ImGui::InputInt(const char* label, int* v, int step, int step_fast, ImGuiInputTextFlags flags)\r\n{\r\n    // Hexadecimal input provided as a convenience but the flag name is awkward. Typically you'd use InputText() to parse your own data, if you want to handle prefixes.\r\n    const char* format = (flags & ImGuiInputTextFlags_CharsHexadecimal) ? \"%08X\" : \"%d\";\r\n    return InputScalar(label, ImGuiDataType_S32, (void*)v, (void*)(step > 0 ? &step : NULL), (void*)(step_fast > 0 ? &step_fast : NULL), format, flags);\r\n}\r\n\r\nbool ImGui::InputInt2(const char* label, int v[2], ImGuiInputTextFlags flags)\r\n{\r\n    return InputScalarN(label, ImGuiDataType_S32, v, 2, NULL, NULL, \"%d\", flags);\r\n}\r\n\r\nbool ImGui::InputInt3(const char* label, int v[3], ImGuiInputTextFlags flags)\r\n{\r\n    return InputScalarN(label, ImGuiDataType_S32, v, 3, NULL, NULL, \"%d\", flags);\r\n}\r\n\r\nbool ImGui::InputInt4(const char* label, int v[4], ImGuiInputTextFlags flags)\r\n{\r\n    return InputScalarN(label, ImGuiDataType_S32, v, 4, NULL, NULL, \"%d\", flags);\r\n}\r\n\r\nbool ImGui::InputDouble(const char* label, double* v, double step, double step_fast, const char* format, ImGuiInputTextFlags flags)\r\n{\r\n    flags |= ImGuiInputTextFlags_CharsScientific;\r\n    return InputScalar(label, ImGuiDataType_Double, (void*)v, (void*)(step > 0.0 ? &step : NULL), (void*)(step_fast > 0.0 ? &step_fast : NULL), format, flags);\r\n}\r\n\r\n//-------------------------------------------------------------------------\r\n// [SECTION] Widgets: InputText, InputTextMultiline, InputTextWithHint\r\n//-------------------------------------------------------------------------\r\n// - InputText()\r\n// - InputTextWithHint()\r\n// - InputTextMultiline()\r\n// - InputTextEx() [Internal]\r\n//-------------------------------------------------------------------------\r\n\r\nbool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data)\r\n{\r\n    IM_ASSERT(!(flags & ImGuiInputTextFlags_Multiline)); // call InputTextMultiline()\r\n    return InputTextEx(label, NULL, buf, (int)buf_size, ImVec2(0, 0), flags, callback, user_data);\r\n}\r\n\r\nbool ImGui::InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data)\r\n{\r\n    return InputTextEx(label, NULL, buf, (int)buf_size, size, flags | ImGuiInputTextFlags_Multiline, callback, user_data);\r\n}\r\n\r\nbool ImGui::InputTextWithHint(const char* label, const char* hint, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data)\r\n{\r\n    IM_ASSERT(!(flags & ImGuiInputTextFlags_Multiline)); // call InputTextMultiline()\r\n    return InputTextEx(label, hint, buf, (int)buf_size, ImVec2(0, 0), flags, callback, user_data);\r\n}\r\n\r\nstatic int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end)\r\n{\r\n    int line_count = 0;\r\n    const char* s = text_begin;\r\n    while (char c = *s++) // We are only matching for \\n so we can ignore UTF-8 decoding\r\n        if (c == '\\n')\r\n            line_count++;\r\n    s--;\r\n    if (s[0] != '\\n' && s[0] != '\\r')\r\n        line_count++;\r\n    *out_text_end = s;\r\n    return line_count;\r\n}\r\n\r\nstatic ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining, ImVec2* out_offset, bool stop_on_new_line)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImFont* font = g.Font;\r\n    const float line_height = g.FontSize;\r\n    const float scale = line_height / font->FontSize;\r\n\r\n    ImVec2 text_size = ImVec2(0, 0);\r\n    float line_width = 0.0f;\r\n\r\n    const ImWchar* s = text_begin;\r\n    while (s < text_end)\r\n    {\r\n        unsigned int c = (unsigned int)(*s++);\r\n        if (c == '\\n')\r\n        {\r\n            text_size.x = ImMax(text_size.x, line_width);\r\n            text_size.y += line_height;\r\n            line_width = 0.0f;\r\n            if (stop_on_new_line)\r\n                break;\r\n            continue;\r\n        }\r\n        if (c == '\\r')\r\n            continue;\r\n\r\n        const float char_width = font->GetCharAdvance((ImWchar)c) * scale;\r\n        line_width += char_width;\r\n    }\r\n\r\n    if (text_size.x < line_width)\r\n        text_size.x = line_width;\r\n\r\n    if (out_offset)\r\n        *out_offset = ImVec2(line_width, text_size.y + line_height);  // offset allow for the possibility of sitting after a trailing \\n\r\n\r\n    if (line_width > 0 || text_size.y == 0.0f)                        // whereas size.y will ignore the trailing \\n\r\n        text_size.y += line_height;\r\n\r\n    if (remaining)\r\n        *remaining = s;\r\n\r\n    return text_size;\r\n}\r\n\r\n// Wrapper for stb_textedit.h to edit text (our wrapper is for: statically sized buffer, single-line, wchar characters. InputText converts between UTF-8 and wchar)\r\nnamespace ImStb\r\n{\r\n\r\nstatic int     STB_TEXTEDIT_STRINGLEN(const ImGuiInputTextState* obj)                             { return obj->CurLenW; }\r\nstatic ImWchar STB_TEXTEDIT_GETCHAR(const ImGuiInputTextState* obj, int idx)                      { return obj->TextW[idx]; }\r\nstatic float   STB_TEXTEDIT_GETWIDTH(ImGuiInputTextState* obj, int line_start_idx, int char_idx)  { ImWchar c = obj->TextW[line_start_idx + char_idx]; if (c == '\\n') return STB_TEXTEDIT_GETWIDTH_NEWLINE; ImGuiContext& g = *GImGui; return g.Font->GetCharAdvance(c) * (g.FontSize / g.Font->FontSize); }\r\nstatic int     STB_TEXTEDIT_KEYTOTEXT(int key)                                                    { return key >= 0x200000 ? 0 : key; }\r\nstatic ImWchar STB_TEXTEDIT_NEWLINE = '\\n';\r\nstatic void    STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, ImGuiInputTextState* obj, int line_start_idx)\r\n{\r\n    const ImWchar* text = obj->TextW.Data;\r\n    const ImWchar* text_remaining = NULL;\r\n    const ImVec2 size = InputTextCalcTextSizeW(text + line_start_idx, text + obj->CurLenW, &text_remaining, NULL, true);\r\n    r->x0 = 0.0f;\r\n    r->x1 = size.x;\r\n    r->baseline_y_delta = size.y;\r\n    r->ymin = 0.0f;\r\n    r->ymax = size.y;\r\n    r->num_chars = (int)(text_remaining - (text + line_start_idx));\r\n}\r\n\r\n// When ImGuiInputTextFlags_Password is set, we don't want actions such as CTRL+Arrow to leak the fact that underlying data are blanks or separators.\r\nstatic bool is_separator(unsigned int c)                                        { return ImCharIsBlankW(c) || c==',' || c==';' || c=='(' || c==')' || c=='{' || c=='}' || c=='[' || c==']' || c=='|' || c=='\\n' || c=='\\r'; }\r\nstatic int  is_word_boundary_from_right(ImGuiInputTextState* obj, int idx)      { if (obj->Flags & ImGuiInputTextFlags_Password) return 0; return idx > 0 ? (is_separator(obj->TextW[idx - 1]) && !is_separator(obj->TextW[idx]) ) : 1; }\r\nstatic int  is_word_boundary_from_left(ImGuiInputTextState* obj, int idx)       { if (obj->Flags & ImGuiInputTextFlags_Password) return 0; return idx > 0 ? (!is_separator(obj->TextW[idx - 1]) && is_separator(obj->TextW[idx])) : 1; }\r\nstatic int  STB_TEXTEDIT_MOVEWORDLEFT_IMPL(ImGuiInputTextState* obj, int idx)   { idx--; while (idx >= 0 && !is_word_boundary_from_right(obj, idx)) idx--; return idx < 0 ? 0 : idx; }\r\nstatic int  STB_TEXTEDIT_MOVEWORDRIGHT_MAC(ImGuiInputTextState* obj, int idx)   { idx++; int len = obj->CurLenW; while (idx < len && !is_word_boundary_from_left(obj, idx)) idx++; return idx > len ? len : idx; }\r\n#define STB_TEXTEDIT_MOVEWORDLEFT   STB_TEXTEDIT_MOVEWORDLEFT_IMPL    // They need to be #define for stb_textedit.h\r\n#ifdef __APPLE__    // FIXME: Move setting to IO structure\r\n#define STB_TEXTEDIT_MOVEWORDRIGHT  STB_TEXTEDIT_MOVEWORDRIGHT_MAC\r\n#else\r\nstatic int  STB_TEXTEDIT_MOVEWORDRIGHT_WIN(ImGuiInputTextState* obj, int idx)   { idx++; int len = obj->CurLenW; while (idx < len && !is_word_boundary_from_right(obj, idx)) idx++; return idx > len ? len : idx; }\r\n#define STB_TEXTEDIT_MOVEWORDRIGHT  STB_TEXTEDIT_MOVEWORDRIGHT_WIN\r\n#endif\r\n\r\nstatic void STB_TEXTEDIT_DELETECHARS(ImGuiInputTextState* obj, int pos, int n)\r\n{\r\n    ImWchar* dst = obj->TextW.Data + pos;\r\n\r\n    // We maintain our buffer length in both UTF-8 and wchar formats\r\n    obj->Edited = true;\r\n    obj->CurLenA -= ImTextCountUtf8BytesFromStr(dst, dst + n);\r\n    obj->CurLenW -= n;\r\n\r\n    // Offset remaining text (FIXME-OPT: Use memmove)\r\n    const ImWchar* src = obj->TextW.Data + pos + n;\r\n    while (ImWchar c = *src++)\r\n        *dst++ = c;\r\n    *dst = '\\0';\r\n}\r\n\r\nstatic bool STB_TEXTEDIT_INSERTCHARS(ImGuiInputTextState* obj, int pos, const ImWchar* new_text, int new_text_len)\r\n{\r\n    const bool is_resizable = (obj->Flags & ImGuiInputTextFlags_CallbackResize) != 0;\r\n    const int text_len = obj->CurLenW;\r\n    IM_ASSERT(pos <= text_len);\r\n\r\n    const int new_text_len_utf8 = ImTextCountUtf8BytesFromStr(new_text, new_text + new_text_len);\r\n    if (!is_resizable && (new_text_len_utf8 + obj->CurLenA + 1 > obj->BufCapacityA))\r\n        return false;\r\n\r\n    // Grow internal buffer if needed\r\n    if (new_text_len + text_len + 1 > obj->TextW.Size)\r\n    {\r\n        if (!is_resizable)\r\n            return false;\r\n        IM_ASSERT(text_len < obj->TextW.Size);\r\n        obj->TextW.resize(text_len + ImClamp(new_text_len * 4, 32, ImMax(256, new_text_len)) + 1);\r\n    }\r\n\r\n    ImWchar* text = obj->TextW.Data;\r\n    if (pos != text_len)\r\n        memmove(text + pos + new_text_len, text + pos, (size_t)(text_len - pos) * sizeof(ImWchar));\r\n    memcpy(text + pos, new_text, (size_t)new_text_len * sizeof(ImWchar));\r\n\r\n    obj->Edited = true;\r\n    obj->CurLenW += new_text_len;\r\n    obj->CurLenA += new_text_len_utf8;\r\n    obj->TextW[obj->CurLenW] = '\\0';\r\n\r\n    return true;\r\n}\r\n\r\n// We don't use an enum so we can build even with conflicting symbols (if another user of stb_textedit.h leak their STB_TEXTEDIT_K_* symbols)\r\n#define STB_TEXTEDIT_K_LEFT         0x200000 // keyboard input to move cursor left\r\n#define STB_TEXTEDIT_K_RIGHT        0x200001 // keyboard input to move cursor right\r\n#define STB_TEXTEDIT_K_UP           0x200002 // keyboard input to move cursor up\r\n#define STB_TEXTEDIT_K_DOWN         0x200003 // keyboard input to move cursor down\r\n#define STB_TEXTEDIT_K_LINESTART    0x200004 // keyboard input to move cursor to start of line\r\n#define STB_TEXTEDIT_K_LINEEND      0x200005 // keyboard input to move cursor to end of line\r\n#define STB_TEXTEDIT_K_TEXTSTART    0x200006 // keyboard input to move cursor to start of text\r\n#define STB_TEXTEDIT_K_TEXTEND      0x200007 // keyboard input to move cursor to end of text\r\n#define STB_TEXTEDIT_K_DELETE       0x200008 // keyboard input to delete selection or character under cursor\r\n#define STB_TEXTEDIT_K_BACKSPACE    0x200009 // keyboard input to delete selection or character left of cursor\r\n#define STB_TEXTEDIT_K_UNDO         0x20000A // keyboard input to perform undo\r\n#define STB_TEXTEDIT_K_REDO         0x20000B // keyboard input to perform redo\r\n#define STB_TEXTEDIT_K_WORDLEFT     0x20000C // keyboard input to move cursor left one word\r\n#define STB_TEXTEDIT_K_WORDRIGHT    0x20000D // keyboard input to move cursor right one word\r\n#define STB_TEXTEDIT_K_PGUP         0x20000E // keyboard input to move cursor up a page\r\n#define STB_TEXTEDIT_K_PGDOWN       0x20000F // keyboard input to move cursor down a page\r\n#define STB_TEXTEDIT_K_SHIFT        0x400000\r\n\r\n#define STB_TEXTEDIT_IMPLEMENTATION\r\n#include \"imstb_textedit.h\"\r\n\r\n// stb_textedit internally allows for a single undo record to do addition and deletion, but somehow, calling\r\n// the stb_textedit_paste() function creates two separate records, so we perform it manually. (FIXME: Report to nothings/stb?)\r\nstatic void stb_textedit_replace(ImGuiInputTextState* str, STB_TexteditState* state, const STB_TEXTEDIT_CHARTYPE* text, int text_len)\r\n{\r\n    stb_text_makeundo_replace(str, state, 0, str->CurLenW, text_len);\r\n    ImStb::STB_TEXTEDIT_DELETECHARS(str, 0, str->CurLenW);\r\n    if (text_len <= 0)\r\n        return;\r\n    if (ImStb::STB_TEXTEDIT_INSERTCHARS(str, 0, text, text_len))\r\n    {\r\n        state->cursor = text_len;\r\n        state->has_preferred_x = 0;\r\n        return;\r\n    }\r\n    IM_ASSERT(0); // Failed to insert character, normally shouldn't happen because of how we currently use stb_textedit_replace()\r\n}\r\n\r\n} // namespace ImStb\r\n\r\nvoid ImGuiInputTextState::OnKeyPressed(int key)\r\n{\r\n    stb_textedit_key(this, &Stb, key);\r\n    CursorFollow = true;\r\n    CursorAnimReset();\r\n}\r\n\r\nImGuiInputTextCallbackData::ImGuiInputTextCallbackData()\r\n{\r\n    memset(this, 0, sizeof(*this));\r\n}\r\n\r\n// Public API to manipulate UTF-8 text\r\n// We expose UTF-8 to the user (unlike the STB_TEXTEDIT_* functions which are manipulating wchar)\r\n// FIXME: The existence of this rarely exercised code path is a bit of a nuisance.\r\nvoid ImGuiInputTextCallbackData::DeleteChars(int pos, int bytes_count)\r\n{\r\n    IM_ASSERT(pos + bytes_count <= BufTextLen);\r\n    char* dst = Buf + pos;\r\n    const char* src = Buf + pos + bytes_count;\r\n    while (char c = *src++)\r\n        *dst++ = c;\r\n    *dst = '\\0';\r\n\r\n    if (CursorPos >= pos + bytes_count)\r\n        CursorPos -= bytes_count;\r\n    else if (CursorPos >= pos)\r\n        CursorPos = pos;\r\n    SelectionStart = SelectionEnd = CursorPos;\r\n    BufDirty = true;\r\n    BufTextLen -= bytes_count;\r\n}\r\n\r\nvoid ImGuiInputTextCallbackData::InsertChars(int pos, const char* new_text, const char* new_text_end)\r\n{\r\n    const bool is_resizable = (Flags & ImGuiInputTextFlags_CallbackResize) != 0;\r\n    const int new_text_len = new_text_end ? (int)(new_text_end - new_text) : (int)strlen(new_text);\r\n    if (new_text_len + BufTextLen >= BufSize)\r\n    {\r\n        if (!is_resizable)\r\n            return;\r\n\r\n        // Contrary to STB_TEXTEDIT_INSERTCHARS() this is working in the UTF8 buffer, hence the mildly similar code (until we remove the U16 buffer altogether!)\r\n        ImGuiContext& g = *GImGui;\r\n        ImGuiInputTextState* edit_state = &g.InputTextState;\r\n        IM_ASSERT(edit_state->ID != 0 && g.ActiveId == edit_state->ID);\r\n        IM_ASSERT(Buf == edit_state->TextA.Data);\r\n        int new_buf_size = BufTextLen + ImClamp(new_text_len * 4, 32, ImMax(256, new_text_len)) + 1;\r\n        edit_state->TextA.reserve(new_buf_size + 1);\r\n        Buf = edit_state->TextA.Data;\r\n        BufSize = edit_state->BufCapacityA = new_buf_size;\r\n    }\r\n\r\n    if (BufTextLen != pos)\r\n        memmove(Buf + pos + new_text_len, Buf + pos, (size_t)(BufTextLen - pos));\r\n    memcpy(Buf + pos, new_text, (size_t)new_text_len * sizeof(char));\r\n    Buf[BufTextLen + new_text_len] = '\\0';\r\n\r\n    if (CursorPos >= pos)\r\n        CursorPos += new_text_len;\r\n    SelectionStart = SelectionEnd = CursorPos;\r\n    BufDirty = true;\r\n    BufTextLen += new_text_len;\r\n}\r\n\r\n// Return false to discard a character.\r\nstatic bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data, ImGuiInputSource input_source)\r\n{\r\n    IM_ASSERT(input_source == ImGuiInputSource_Keyboard || input_source == ImGuiInputSource_Clipboard);\r\n    unsigned int c = *p_char;\r\n\r\n    // Filter non-printable (NB: isprint is unreliable! see #2467)\r\n    bool apply_named_filters = true;\r\n    if (c < 0x20)\r\n    {\r\n        bool pass = false;\r\n        pass |= (c == '\\n' && (flags & ImGuiInputTextFlags_Multiline));\r\n        pass |= (c == '\\t' && (flags & ImGuiInputTextFlags_AllowTabInput));\r\n        if (!pass)\r\n            return false;\r\n        apply_named_filters = false; // Override named filters below so newline and tabs can still be inserted.\r\n    }\r\n\r\n    if (input_source != ImGuiInputSource_Clipboard)\r\n    {\r\n        // We ignore Ascii representation of delete (emitted from Backspace on OSX, see #2578, #2817)\r\n        if (c == 127)\r\n            return false;\r\n\r\n        // Filter private Unicode range. GLFW on OSX seems to send private characters for special keys like arrow keys (FIXME)\r\n        if (c >= 0xE000 && c <= 0xF8FF)\r\n            return false;\r\n    }\r\n\r\n    // Filter Unicode ranges we are not handling in this build\r\n    if (c > IM_UNICODE_CODEPOINT_MAX)\r\n        return false;\r\n\r\n    // Generic named filters\r\n    if (apply_named_filters && (flags & (ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase | ImGuiInputTextFlags_CharsNoBlank | ImGuiInputTextFlags_CharsScientific)))\r\n    {\r\n        // The libc allows overriding locale, with e.g. 'setlocale(LC_NUMERIC, \"de_DE.UTF-8\");' which affect the output/input of printf/scanf to use e.g. ',' instead of '.'.\r\n        // The standard mandate that programs starts in the \"C\" locale where the decimal point is '.'.\r\n        // We don't really intend to provide widespread support for it, but out of empathy for people stuck with using odd API, we support the bare minimum aka overriding the decimal point.\r\n        // Change the default decimal_point with:\r\n        //   ImGui::GetCurrentContext()->PlatformLocaleDecimalPoint = *localeconv()->decimal_point;\r\n        // Users of non-default decimal point (in particular ',') may be affected by word-selection logic (is_word_boundary_from_right/is_word_boundary_from_left) functions.\r\n        ImGuiContext& g = *GImGui;\r\n        const unsigned c_decimal_point = (unsigned int)g.PlatformLocaleDecimalPoint;\r\n\r\n        // Allow 0-9 . - + * /\r\n        if (flags & ImGuiInputTextFlags_CharsDecimal)\r\n            if (!(c >= '0' && c <= '9') && (c != c_decimal_point) && (c != '-') && (c != '+') && (c != '*') && (c != '/'))\r\n                return false;\r\n\r\n        // Allow 0-9 . - + * / e E\r\n        if (flags & ImGuiInputTextFlags_CharsScientific)\r\n            if (!(c >= '0' && c <= '9') && (c != c_decimal_point) && (c != '-') && (c != '+') && (c != '*') && (c != '/') && (c != 'e') && (c != 'E'))\r\n                return false;\r\n\r\n        // Allow 0-9 a-F A-F\r\n        if (flags & ImGuiInputTextFlags_CharsHexadecimal)\r\n            if (!(c >= '0' && c <= '9') && !(c >= 'a' && c <= 'f') && !(c >= 'A' && c <= 'F'))\r\n                return false;\r\n\r\n        // Turn a-z into A-Z\r\n        if (flags & ImGuiInputTextFlags_CharsUppercase)\r\n            if (c >= 'a' && c <= 'z')\r\n                *p_char = (c += (unsigned int)('A' - 'a'));\r\n\r\n        if (flags & ImGuiInputTextFlags_CharsNoBlank)\r\n            if (ImCharIsBlankW(c))\r\n                return false;\r\n    }\r\n\r\n    // Custom callback filter\r\n    if (flags & ImGuiInputTextFlags_CallbackCharFilter)\r\n    {\r\n        ImGuiInputTextCallbackData callback_data;\r\n        memset(&callback_data, 0, sizeof(ImGuiInputTextCallbackData));\r\n        callback_data.EventFlag = ImGuiInputTextFlags_CallbackCharFilter;\r\n        callback_data.EventChar = (ImWchar)c;\r\n        callback_data.Flags = flags;\r\n        callback_data.UserData = user_data;\r\n        if (callback(&callback_data) != 0)\r\n            return false;\r\n        *p_char = callback_data.EventChar;\r\n        if (!callback_data.EventChar)\r\n            return false;\r\n    }\r\n\r\n    return true;\r\n}\r\n\r\n// Edit a string of text\r\n// - buf_size account for the zero-terminator, so a buf_size of 6 can hold \"Hello\" but not \"Hello!\".\r\n//   This is so we can easily call InputText() on static arrays using ARRAYSIZE() and to match\r\n//   Note that in std::string world, capacity() would omit 1 byte used by the zero-terminator.\r\n// - When active, hold on a privately held copy of the text (and apply back to 'buf'). So changing 'buf' while the InputText is active has no effect.\r\n// - If you want to use ImGui::InputText() with std::string, see misc/cpp/imgui_stdlib.h\r\n// (FIXME: Rather confusing and messy function, among the worse part of our codebase, expecting to rewrite a V2 at some point.. Partly because we are\r\n//  doing UTF8 > U16 > UTF8 conversions on the go to easily interface with stb_textedit. Ideally should stay in UTF-8 all the time. See https://github.com/nothings/stb/issues/188)\r\nbool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* callback_user_data)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return false;\r\n\r\n    IM_ASSERT(buf != NULL && buf_size >= 0);\r\n    IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackHistory) && (flags & ImGuiInputTextFlags_Multiline)));        // Can't use both together (they both use up/down keys)\r\n    IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackCompletion) && (flags & ImGuiInputTextFlags_AllowTabInput))); // Can't use both together (they both use tab key)\r\n\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiIO& io = g.IO;\r\n    const ImGuiStyle& style = g.Style;\r\n\r\n    const bool RENDER_SELECTION_WHEN_INACTIVE = false;\r\n    const bool is_multiline = (flags & ImGuiInputTextFlags_Multiline) != 0;\r\n    const bool is_readonly = (flags & ImGuiInputTextFlags_ReadOnly) != 0;\r\n    const bool is_password = (flags & ImGuiInputTextFlags_Password) != 0;\r\n    const bool is_undoable = (flags & ImGuiInputTextFlags_NoUndoRedo) == 0;\r\n    const bool is_resizable = (flags & ImGuiInputTextFlags_CallbackResize) != 0;\r\n    if (is_resizable)\r\n        IM_ASSERT(callback != NULL); // Must provide a callback if you set the ImGuiInputTextFlags_CallbackResize flag!\r\n\r\n    if (is_multiline) // Open group before calling GetID() because groups tracks id created within their scope (including the scrollbar)\r\n        BeginGroup();\r\n    const ImGuiID id = window->GetID(label);\r\n    const ImVec2 label_size = CalcTextSize(label, NULL, true);\r\n    const ImVec2 frame_size = CalcItemSize(size_arg, CalcItemWidth(), (is_multiline ? g.FontSize * 8.0f : label_size.y) + style.FramePadding.y * 2.0f); // Arbitrary default of 8 lines high for multi-line\r\n    const ImVec2 total_size = ImVec2(frame_size.x + (label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f), frame_size.y);\r\n\r\n    const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size);\r\n    const ImRect total_bb(frame_bb.Min, frame_bb.Min + total_size);\r\n\r\n    ImGuiWindow* draw_window = window;\r\n    ImVec2 inner_size = frame_size;\r\n    ImGuiItemStatusFlags item_status_flags = 0;\r\n    ImGuiLastItemData item_data_backup;\r\n    if (is_multiline)\r\n    {\r\n        ImVec2 backup_pos = window->DC.CursorPos;\r\n        ItemSize(total_bb, style.FramePadding.y);\r\n        if (!ItemAdd(total_bb, id, &frame_bb, ImGuiItemFlags_Inputable))\r\n        {\r\n            EndGroup();\r\n            return false;\r\n        }\r\n        item_status_flags = g.LastItemData.StatusFlags;\r\n        item_data_backup = g.LastItemData;\r\n        window->DC.CursorPos = backup_pos;\r\n\r\n        // We reproduce the contents of BeginChildFrame() in order to provide 'label' so our window internal data are easier to read/debug.\r\n        // FIXME-NAV: Pressing NavActivate will trigger general child activation right before triggering our own below. Harmless but bizarre.\r\n        PushStyleColor(ImGuiCol_ChildBg, style.Colors[ImGuiCol_FrameBg]);\r\n        PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding);\r\n        PushStyleVar(ImGuiStyleVar_ChildBorderSize, style.FrameBorderSize);\r\n        PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0)); // Ensure no clip rect so mouse hover can reach FramePadding edges\r\n        bool child_visible = BeginChildEx(label, id, frame_bb.GetSize(), true, ImGuiWindowFlags_NoMove);\r\n        PopStyleVar(3);\r\n        PopStyleColor();\r\n        if (!child_visible)\r\n        {\r\n            EndChild();\r\n            EndGroup();\r\n            return false;\r\n        }\r\n        draw_window = g.CurrentWindow; // Child window\r\n        draw_window->DC.NavLayersActiveMaskNext |= (1 << draw_window->DC.NavLayerCurrent); // This is to ensure that EndChild() will display a navigation highlight so we can \"enter\" into it.\r\n        draw_window->DC.CursorPos += style.FramePadding;\r\n        inner_size.x -= draw_window->ScrollbarSizes.x;\r\n    }\r\n    else\r\n    {\r\n        // Support for internal ImGuiInputTextFlags_MergedItem flag, which could be redesigned as an ItemFlags if needed (with test performed in ItemAdd)\r\n        ItemSize(total_bb, style.FramePadding.y);\r\n        if (!(flags & ImGuiInputTextFlags_MergedItem))\r\n            if (!ItemAdd(total_bb, id, &frame_bb, ImGuiItemFlags_Inputable))\r\n                return false;\r\n        item_status_flags = g.LastItemData.StatusFlags;\r\n    }\r\n    const bool hovered = ItemHoverable(frame_bb, id);\r\n    if (hovered)\r\n        g.MouseCursor = ImGuiMouseCursor_TextInput;\r\n\r\n    // We are only allowed to access the state if we are already the active widget.\r\n    ImGuiInputTextState* state = GetInputTextState(id);\r\n\r\n    const bool input_requested_by_tabbing = (item_status_flags & ImGuiItemStatusFlags_FocusedByTabbing) != 0;\r\n    const bool input_requested_by_nav = (g.ActiveId != id) && ((g.NavActivateInputId == id) || (g.NavActivateId == id && g.NavInputSource == ImGuiInputSource_Keyboard));\r\n\r\n    const bool user_clicked = hovered && io.MouseClicked[0];\r\n    const bool user_scroll_finish = is_multiline && state != NULL && g.ActiveId == 0 && g.ActiveIdPreviousFrame == GetWindowScrollbarID(draw_window, ImGuiAxis_Y);\r\n    const bool user_scroll_active = is_multiline && state != NULL && g.ActiveId == GetWindowScrollbarID(draw_window, ImGuiAxis_Y);\r\n    bool clear_active_id = false;\r\n    bool select_all = false;\r\n\r\n    float scroll_y = is_multiline ? draw_window->Scroll.y : FLT_MAX;\r\n\r\n    const bool init_changed_specs = (state != NULL && state->Stb.single_line != !is_multiline);\r\n    const bool init_make_active = (user_clicked || user_scroll_finish || input_requested_by_nav || input_requested_by_tabbing);\r\n    const bool init_state = (init_make_active || user_scroll_active);\r\n    if ((init_state && g.ActiveId != id) || init_changed_specs)\r\n    {\r\n        // Access state even if we don't own it yet.\r\n        state = &g.InputTextState;\r\n        state->CursorAnimReset();\r\n\r\n        // Take a copy of the initial buffer value (both in original UTF-8 format and converted to wchar)\r\n        // From the moment we focused we are ignoring the content of 'buf' (unless we are in read-only mode)\r\n        const int buf_len = (int)strlen(buf);\r\n        state->InitialTextA.resize(buf_len + 1);    // UTF-8. we use +1 to make sure that .Data is always pointing to at least an empty string.\r\n        memcpy(state->InitialTextA.Data, buf, buf_len + 1);\r\n\r\n        // Start edition\r\n        const char* buf_end = NULL;\r\n        state->TextW.resize(buf_size + 1);          // wchar count <= UTF-8 count. we use +1 to make sure that .Data is always pointing to at least an empty string.\r\n        state->TextA.resize(0);\r\n        state->TextAIsValid = false;                // TextA is not valid yet (we will display buf until then)\r\n        state->CurLenW = ImTextStrFromUtf8(state->TextW.Data, buf_size, buf, NULL, &buf_end);\r\n        state->CurLenA = (int)(buf_end - buf);      // We can't get the result from ImStrncpy() above because it is not UTF-8 aware. Here we'll cut off malformed UTF-8.\r\n\r\n        // Preserve cursor position and undo/redo stack if we come back to same widget\r\n        // FIXME: For non-readonly widgets we might be able to require that TextAIsValid && TextA == buf ? (untested) and discard undo stack if user buffer has changed.\r\n        const bool recycle_state = (state->ID == id && !init_changed_specs);\r\n        if (recycle_state)\r\n        {\r\n            // Recycle existing cursor/selection/undo stack but clamp position\r\n            // Note a single mouse click will override the cursor/position immediately by calling stb_textedit_click handler.\r\n            state->CursorClamp();\r\n        }\r\n        else\r\n        {\r\n            state->ID = id;\r\n            state->ScrollX = 0.0f;\r\n            stb_textedit_initialize_state(&state->Stb, !is_multiline);\r\n        }\r\n\r\n        if (!is_multiline)\r\n        {\r\n            if (flags & ImGuiInputTextFlags_AutoSelectAll)\r\n                select_all = true;\r\n            if (input_requested_by_nav && (!recycle_state || !(g.NavActivateFlags & ImGuiActivateFlags_TryToPreserveState)))\r\n                select_all = true;\r\n            if (input_requested_by_tabbing || (user_clicked && io.KeyCtrl))\r\n                select_all = true;\r\n        }\r\n\r\n        if (flags & ImGuiInputTextFlags_AlwaysOverwrite)\r\n            state->Stb.insert_mode = 1; // stb field name is indeed incorrect (see #2863)\r\n    }\r\n\r\n    if (g.ActiveId != id && init_make_active)\r\n    {\r\n        IM_ASSERT(state && state->ID == id);\r\n        SetActiveID(id, window);\r\n        SetFocusID(id, window);\r\n        FocusWindow(window);\r\n\r\n        // Declare our inputs\r\n        IM_ASSERT(ImGuiNavInput_COUNT < 32);\r\n        g.ActiveIdUsingNavDirMask |= (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right);\r\n        if (is_multiline || (flags & ImGuiInputTextFlags_CallbackHistory))\r\n            g.ActiveIdUsingNavDirMask |= (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down);\r\n        g.ActiveIdUsingNavInputMask |= (1 << ImGuiNavInput_Cancel);\r\n        SetActiveIdUsingKey(ImGuiKey_Home);\r\n        SetActiveIdUsingKey(ImGuiKey_End);\r\n        if (is_multiline)\r\n        {\r\n            SetActiveIdUsingKey(ImGuiKey_PageUp);\r\n            SetActiveIdUsingKey(ImGuiKey_PageDown);\r\n        }\r\n        if (flags & (ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_AllowTabInput)) // Disable keyboard tabbing out as we will use the \\t character.\r\n        {\r\n            SetActiveIdUsingKey(ImGuiKey_Tab);\r\n        }\r\n    }\r\n\r\n    // We have an edge case if ActiveId was set through another widget (e.g. widget being swapped), clear id immediately (don't wait until the end of the function)\r\n    if (g.ActiveId == id && state == NULL)\r\n        ClearActiveID();\r\n\r\n    // Release focus when we click outside\r\n    if (g.ActiveId == id && io.MouseClicked[0] && !init_state && !init_make_active) //-V560\r\n        clear_active_id = true;\r\n\r\n    // Lock the decision of whether we are going to take the path displaying the cursor or selection\r\n    const bool render_cursor = (g.ActiveId == id) || (state && user_scroll_active);\r\n    bool render_selection = state && (state->HasSelection() || select_all) && (RENDER_SELECTION_WHEN_INACTIVE || render_cursor);\r\n    bool value_changed = false;\r\n    bool enter_pressed = false;\r\n\r\n    // When read-only we always use the live data passed to the function\r\n    // FIXME-OPT: Because our selection/cursor code currently needs the wide text we need to convert it when active, which is not ideal :(\r\n    if (is_readonly && state != NULL && (render_cursor || render_selection))\r\n    {\r\n        const char* buf_end = NULL;\r\n        state->TextW.resize(buf_size + 1);\r\n        state->CurLenW = ImTextStrFromUtf8(state->TextW.Data, state->TextW.Size, buf, NULL, &buf_end);\r\n        state->CurLenA = (int)(buf_end - buf);\r\n        state->CursorClamp();\r\n        render_selection &= state->HasSelection();\r\n    }\r\n\r\n    // Select the buffer to render.\r\n    const bool buf_display_from_state = (render_cursor || render_selection || g.ActiveId == id) && !is_readonly && state && state->TextAIsValid;\r\n    const bool is_displaying_hint = (hint != NULL && (buf_display_from_state ? state->TextA.Data : buf)[0] == 0);\r\n\r\n    // Password pushes a temporary font with only a fallback glyph\r\n    if (is_password && !is_displaying_hint)\r\n    {\r\n        const ImFontGlyph* glyph = g.Font->FindGlyph('*');\r\n        ImFont* password_font = &g.InputTextPasswordFont;\r\n        password_font->FontSize = g.Font->FontSize;\r\n        password_font->Scale = g.Font->Scale;\r\n        password_font->Ascent = g.Font->Ascent;\r\n        password_font->Descent = g.Font->Descent;\r\n        password_font->ContainerAtlas = g.Font->ContainerAtlas;\r\n        password_font->FallbackGlyph = glyph;\r\n        password_font->FallbackAdvanceX = glyph->AdvanceX;\r\n        IM_ASSERT(password_font->Glyphs.empty() && password_font->IndexAdvanceX.empty() && password_font->IndexLookup.empty());\r\n        PushFont(password_font);\r\n    }\r\n\r\n    // Process mouse inputs and character inputs\r\n    int backup_current_text_length = 0;\r\n    if (g.ActiveId == id)\r\n    {\r\n        IM_ASSERT(state != NULL);\r\n        backup_current_text_length = state->CurLenA;\r\n        state->Edited = false;\r\n        state->BufCapacityA = buf_size;\r\n        state->Flags = flags;\r\n\r\n        // Although we are active we don't prevent mouse from hovering other elements unless we are interacting right now with the widget.\r\n        // Down the line we should have a cleaner library-wide concept of Selected vs Active.\r\n        g.ActiveIdAllowOverlap = !io.MouseDown[0];\r\n        g.WantTextInputNextFrame = 1;\r\n\r\n        // Edit in progress\r\n        const float mouse_x = (io.MousePos.x - frame_bb.Min.x - style.FramePadding.x) + state->ScrollX;\r\n        const float mouse_y = (is_multiline ? (io.MousePos.y - draw_window->DC.CursorPos.y) : (g.FontSize * 0.5f));\r\n\r\n        const bool is_osx = io.ConfigMacOSXBehaviors;\r\n        if (select_all)\r\n        {\r\n            state->SelectAll();\r\n            state->SelectedAllMouseLock = true;\r\n        }\r\n        else if (hovered && io.MouseClickedCount[0] >= 2 && !io.KeyShift)\r\n        {\r\n            stb_textedit_click(state, &state->Stb, mouse_x, mouse_y);\r\n            const int multiclick_count = (io.MouseClickedCount[0] - 2);\r\n            if ((multiclick_count % 2) == 0)\r\n            {\r\n                // Double-click: Select word\r\n                // We always use the \"Mac\" word advance for double-click select vs CTRL+Right which use the platform dependent variant:\r\n                // FIXME: There are likely many ways to improve this behavior, but there's no \"right\" behavior (depends on use-case, software, OS)\r\n                const bool is_bol = (state->Stb.cursor == 0) || ImStb::STB_TEXTEDIT_GETCHAR(state, state->Stb.cursor - 1) == '\\n';\r\n                if (STB_TEXT_HAS_SELECTION(&state->Stb) || !is_bol)\r\n                    state->OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT);\r\n                //state->OnKeyPressed(STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT);\r\n                if (!STB_TEXT_HAS_SELECTION(&state->Stb))\r\n                    ImStb::stb_textedit_prep_selection_at_cursor(&state->Stb);\r\n                state->Stb.cursor = ImStb::STB_TEXTEDIT_MOVEWORDRIGHT_MAC(state, state->Stb.cursor);\r\n                state->Stb.select_end = state->Stb.cursor;\r\n                ImStb::stb_textedit_clamp(state, &state->Stb);\r\n            }\r\n            else\r\n            {\r\n                // Triple-click: Select line\r\n                const bool is_eol = ImStb::STB_TEXTEDIT_GETCHAR(state, state->Stb.cursor) == '\\n';\r\n                state->OnKeyPressed(STB_TEXTEDIT_K_LINESTART);\r\n                state->OnKeyPressed(STB_TEXTEDIT_K_LINEEND | STB_TEXTEDIT_K_SHIFT);\r\n                state->OnKeyPressed(STB_TEXTEDIT_K_RIGHT | STB_TEXTEDIT_K_SHIFT);\r\n                if (!is_eol && is_multiline)\r\n                {\r\n                    ImSwap(state->Stb.select_start, state->Stb.select_end);\r\n                    state->Stb.cursor = state->Stb.select_end;\r\n                }\r\n                state->CursorFollow = false;\r\n            }\r\n            state->CursorAnimReset();\r\n        }\r\n        else if (io.MouseClicked[0] && !state->SelectedAllMouseLock)\r\n        {\r\n            // FIXME: unselect on late click could be done release?\r\n            if (hovered)\r\n            {\r\n                stb_textedit_click(state, &state->Stb, mouse_x, mouse_y);\r\n                state->CursorAnimReset();\r\n            }\r\n        }\r\n        else if (io.MouseDown[0] && !state->SelectedAllMouseLock && (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f))\r\n        {\r\n            stb_textedit_drag(state, &state->Stb, mouse_x, mouse_y);\r\n            state->CursorAnimReset();\r\n            state->CursorFollow = true;\r\n        }\r\n        if (state->SelectedAllMouseLock && !io.MouseDown[0])\r\n            state->SelectedAllMouseLock = false;\r\n\r\n        // It is ill-defined whether the backend needs to send a \\t character when pressing the TAB keys.\r\n        // Win32 and GLFW naturally do it but not SDL.\r\n        const bool ignore_char_inputs = (io.KeyCtrl && !io.KeyAlt) || (is_osx && io.KeySuper);\r\n        if ((flags & ImGuiInputTextFlags_AllowTabInput) && IsKeyPressed(ImGuiKey_Tab) && !ignore_char_inputs && !io.KeyShift && !is_readonly)\r\n            if (!io.InputQueueCharacters.contains('\\t'))\r\n            {\r\n                unsigned int c = '\\t'; // Insert TAB\r\n                if (InputTextFilterCharacter(&c, flags, callback, callback_user_data, ImGuiInputSource_Keyboard))\r\n                    state->OnKeyPressed((int)c);\r\n            }\r\n\r\n        // Process regular text input (before we check for Return because using some IME will effectively send a Return?)\r\n        // We ignore CTRL inputs, but need to allow ALT+CTRL as some keyboards (e.g. German) use AltGR (which _is_ Alt+Ctrl) to input certain characters.\r\n        if (io.InputQueueCharacters.Size > 0)\r\n        {\r\n            if (!ignore_char_inputs && !is_readonly && !input_requested_by_nav)\r\n                for (int n = 0; n < io.InputQueueCharacters.Size; n++)\r\n                {\r\n                    // Insert character if they pass filtering\r\n                    unsigned int c = (unsigned int)io.InputQueueCharacters[n];\r\n                    if (c == '\\t' && io.KeyShift)\r\n                        continue;\r\n                    if (InputTextFilterCharacter(&c, flags, callback, callback_user_data, ImGuiInputSource_Keyboard))\r\n                        state->OnKeyPressed((int)c);\r\n                }\r\n\r\n            // Consume characters\r\n            io.InputQueueCharacters.resize(0);\r\n        }\r\n    }\r\n\r\n    // Process other shortcuts/key-presses\r\n    bool cancel_edit = false;\r\n    if (g.ActiveId == id && !g.ActiveIdIsJustActivated && !clear_active_id)\r\n    {\r\n        IM_ASSERT(state != NULL);\r\n        IM_ASSERT(io.KeyMods == GetMergedKeyModFlags() && \"Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods\"); // We rarely do this check, but if anything let's do it here.\r\n\r\n        const int row_count_per_page = ImMax((int)((inner_size.y - style.FramePadding.y) / g.FontSize), 1);\r\n        state->Stb.row_count_per_page = row_count_per_page;\r\n\r\n        const int k_mask = (io.KeyShift ? STB_TEXTEDIT_K_SHIFT : 0);\r\n        const bool is_osx = io.ConfigMacOSXBehaviors;\r\n        const bool is_osx_shift_shortcut = is_osx && (io.KeyMods == (ImGuiKeyModFlags_Super | ImGuiKeyModFlags_Shift));\r\n        const bool is_wordmove_key_down = is_osx ? io.KeyAlt : io.KeyCtrl;                     // OS X style: Text editing cursor movement using Alt instead of Ctrl\r\n        const bool is_startend_key_down = is_osx && io.KeySuper && !io.KeyCtrl && !io.KeyAlt;  // OS X style: Line/Text Start and End using Cmd+Arrows instead of Home/End\r\n        const bool is_ctrl_key_only = (io.KeyMods == ImGuiKeyModFlags_Ctrl);\r\n        const bool is_shift_key_only = (io.KeyMods == ImGuiKeyModFlags_Shift);\r\n        const bool is_shortcut_key = g.IO.ConfigMacOSXBehaviors ? (io.KeyMods == ImGuiKeyModFlags_Super) : (io.KeyMods == ImGuiKeyModFlags_Ctrl);\r\n\r\n        const bool is_cut   = ((is_shortcut_key && IsKeyPressed(ImGuiKey_X)) || (is_shift_key_only && IsKeyPressed(ImGuiKey_Delete))) && !is_readonly && !is_password && (!is_multiline || state->HasSelection());\r\n        const bool is_copy  = ((is_shortcut_key && IsKeyPressed(ImGuiKey_C)) || (is_ctrl_key_only  && IsKeyPressed(ImGuiKey_Insert))) && !is_password && (!is_multiline || state->HasSelection());\r\n        const bool is_paste = ((is_shortcut_key && IsKeyPressed(ImGuiKey_V)) || (is_shift_key_only && IsKeyPressed(ImGuiKey_Insert))) && !is_readonly;\r\n        const bool is_undo  = ((is_shortcut_key && IsKeyPressed(ImGuiKey_Z)) && !is_readonly && is_undoable);\r\n        const bool is_redo  = ((is_shortcut_key && IsKeyPressed(ImGuiKey_Y)) || (is_osx_shift_shortcut && IsKeyPressed(ImGuiKey_Z))) && !is_readonly && is_undoable;\r\n\r\n        // We allow validate/cancel with Nav source (gamepad) to makes it easier to undo an accidental NavInput press with no keyboard wired, but otherwise it isn't very useful.\r\n        const bool is_validate_enter = IsKeyPressed(ImGuiKey_Enter) || IsKeyPressed(ImGuiKey_KeypadEnter);\r\n        const bool is_validate_nav = (IsNavInputTest(ImGuiNavInput_Activate, ImGuiInputReadMode_Pressed) && !IsKeyPressed(ImGuiKey_Space)) || IsNavInputTest(ImGuiNavInput_Input, ImGuiInputReadMode_Pressed);\r\n        const bool is_cancel   = IsKeyPressed(ImGuiKey_Escape) || IsNavInputTest(ImGuiNavInput_Cancel, ImGuiInputReadMode_Pressed);\r\n\r\n        if (IsKeyPressed(ImGuiKey_LeftArrow))                        { state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINESTART : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDLEFT : STB_TEXTEDIT_K_LEFT) | k_mask); }\r\n        else if (IsKeyPressed(ImGuiKey_RightArrow))                  { state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINEEND : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDRIGHT : STB_TEXTEDIT_K_RIGHT) | k_mask); }\r\n        else if (IsKeyPressed(ImGuiKey_UpArrow) && is_multiline)     { if (io.KeyCtrl) SetScrollY(draw_window, ImMax(draw_window->Scroll.y - g.FontSize, 0.0f)); else state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTSTART : STB_TEXTEDIT_K_UP) | k_mask); }\r\n        else if (IsKeyPressed(ImGuiKey_DownArrow) && is_multiline)   { if (io.KeyCtrl) SetScrollY(draw_window, ImMin(draw_window->Scroll.y + g.FontSize, GetScrollMaxY())); else state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTEND : STB_TEXTEDIT_K_DOWN) | k_mask); }\r\n        else if (IsKeyPressed(ImGuiKey_PageUp) && is_multiline)      { state->OnKeyPressed(STB_TEXTEDIT_K_PGUP | k_mask); scroll_y -= row_count_per_page * g.FontSize; }\r\n        else if (IsKeyPressed(ImGuiKey_PageDown) && is_multiline)    { state->OnKeyPressed(STB_TEXTEDIT_K_PGDOWN | k_mask); scroll_y += row_count_per_page * g.FontSize; }\r\n        else if (IsKeyPressed(ImGuiKey_Home))                        { state->OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTSTART | k_mask : STB_TEXTEDIT_K_LINESTART | k_mask); }\r\n        else if (IsKeyPressed(ImGuiKey_End))                         { state->OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTEND | k_mask : STB_TEXTEDIT_K_LINEEND | k_mask); }\r\n        else if (IsKeyPressed(ImGuiKey_Delete) && !is_readonly && !is_cut) { state->OnKeyPressed(STB_TEXTEDIT_K_DELETE | k_mask); }\r\n        else if (IsKeyPressed(ImGuiKey_Backspace) && !is_readonly)\r\n        {\r\n            if (!state->HasSelection())\r\n            {\r\n                if (is_wordmove_key_down)\r\n                    state->OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT | STB_TEXTEDIT_K_SHIFT);\r\n                else if (is_osx && io.KeySuper && !io.KeyAlt && !io.KeyCtrl)\r\n                    state->OnKeyPressed(STB_TEXTEDIT_K_LINESTART | STB_TEXTEDIT_K_SHIFT);\r\n            }\r\n            state->OnKeyPressed(STB_TEXTEDIT_K_BACKSPACE | k_mask);\r\n        }\r\n        else if (is_validate_enter)\r\n        {\r\n            bool ctrl_enter_for_new_line = (flags & ImGuiInputTextFlags_CtrlEnterForNewLine) != 0;\r\n            if (!is_multiline || (ctrl_enter_for_new_line && !io.KeyCtrl) || (!ctrl_enter_for_new_line && io.KeyCtrl))\r\n            {\r\n                enter_pressed = clear_active_id = true;\r\n            }\r\n            else if (!is_readonly)\r\n            {\r\n                unsigned int c = '\\n'; // Insert new line\r\n                if (InputTextFilterCharacter(&c, flags, callback, callback_user_data, ImGuiInputSource_Keyboard))\r\n                    state->OnKeyPressed((int)c);\r\n            }\r\n        }\r\n        else if (is_validate_nav)\r\n        {\r\n            IM_ASSERT(!is_validate_enter);\r\n            enter_pressed = clear_active_id = true;\r\n        }\r\n        else if (is_cancel)\r\n        {\r\n            clear_active_id = cancel_edit = true;\r\n        }\r\n        else if (is_undo || is_redo)\r\n        {\r\n            state->OnKeyPressed(is_undo ? STB_TEXTEDIT_K_UNDO : STB_TEXTEDIT_K_REDO);\r\n            state->ClearSelection();\r\n        }\r\n        else if (is_shortcut_key && IsKeyPressed(ImGuiKey_A))\r\n        {\r\n            state->SelectAll();\r\n            state->CursorFollow = true;\r\n        }\r\n        else if (is_cut || is_copy)\r\n        {\r\n            // Cut, Copy\r\n            if (io.SetClipboardTextFn)\r\n            {\r\n                const int ib = state->HasSelection() ? ImMin(state->Stb.select_start, state->Stb.select_end) : 0;\r\n                const int ie = state->HasSelection() ? ImMax(state->Stb.select_start, state->Stb.select_end) : state->CurLenW;\r\n                const int clipboard_data_len = ImTextCountUtf8BytesFromStr(state->TextW.Data + ib, state->TextW.Data + ie) + 1;\r\n                char* clipboard_data = (char*)IM_ALLOC(clipboard_data_len * sizeof(char));\r\n                ImTextStrToUtf8(clipboard_data, clipboard_data_len, state->TextW.Data + ib, state->TextW.Data + ie);\r\n                SetClipboardText(clipboard_data);\r\n                MemFree(clipboard_data);\r\n            }\r\n            if (is_cut)\r\n            {\r\n                if (!state->HasSelection())\r\n                    state->SelectAll();\r\n                state->CursorFollow = true;\r\n                stb_textedit_cut(state, &state->Stb);\r\n            }\r\n        }\r\n        else if (is_paste)\r\n        {\r\n            if (const char* clipboard = GetClipboardText())\r\n            {\r\n                // Filter pasted buffer\r\n                const int clipboard_len = (int)strlen(clipboard);\r\n                ImWchar* clipboard_filtered = (ImWchar*)IM_ALLOC((clipboard_len + 1) * sizeof(ImWchar));\r\n                int clipboard_filtered_len = 0;\r\n                for (const char* s = clipboard; *s; )\r\n                {\r\n                    unsigned int c;\r\n                    s += ImTextCharFromUtf8(&c, s, NULL);\r\n                    if (c == 0)\r\n                        break;\r\n                    if (!InputTextFilterCharacter(&c, flags, callback, callback_user_data, ImGuiInputSource_Clipboard))\r\n                        continue;\r\n                    clipboard_filtered[clipboard_filtered_len++] = (ImWchar)c;\r\n                }\r\n                clipboard_filtered[clipboard_filtered_len] = 0;\r\n                if (clipboard_filtered_len > 0) // If everything was filtered, ignore the pasting operation\r\n                {\r\n                    stb_textedit_paste(state, &state->Stb, clipboard_filtered, clipboard_filtered_len);\r\n                    state->CursorFollow = true;\r\n                }\r\n                MemFree(clipboard_filtered);\r\n            }\r\n        }\r\n\r\n        // Update render selection flag after events have been handled, so selection highlight can be displayed during the same frame.\r\n        render_selection |= state->HasSelection() && (RENDER_SELECTION_WHEN_INACTIVE || render_cursor);\r\n    }\r\n\r\n    // Process callbacks and apply result back to user's buffer.\r\n    const char* apply_new_text = NULL;\r\n    int apply_new_text_length = 0;\r\n    if (g.ActiveId == id)\r\n    {\r\n        IM_ASSERT(state != NULL);\r\n        if (cancel_edit)\r\n        {\r\n            // Restore initial value. Only return true if restoring to the initial value changes the current buffer contents.\r\n            if (!is_readonly && strcmp(buf, state->InitialTextA.Data) != 0)\r\n            {\r\n                // Push records into the undo stack so we can CTRL+Z the revert operation itself\r\n                apply_new_text = state->InitialTextA.Data;\r\n                apply_new_text_length = state->InitialTextA.Size - 1;\r\n                ImVector<ImWchar> w_text;\r\n                if (apply_new_text_length > 0)\r\n                {\r\n                    w_text.resize(ImTextCountCharsFromUtf8(apply_new_text, apply_new_text + apply_new_text_length) + 1);\r\n                    ImTextStrFromUtf8(w_text.Data, w_text.Size, apply_new_text, apply_new_text + apply_new_text_length);\r\n                }\r\n                stb_textedit_replace(state, &state->Stb, w_text.Data, (apply_new_text_length > 0) ? (w_text.Size - 1) : 0);\r\n            }\r\n        }\r\n\r\n        // When using 'ImGuiInputTextFlags_EnterReturnsTrue' as a special case we reapply the live buffer back to the input buffer before clearing ActiveId, even though strictly speaking it wasn't modified on this frame.\r\n        // If we didn't do that, code like InputInt() with ImGuiInputTextFlags_EnterReturnsTrue would fail.\r\n        // This also allows the user to use InputText() with ImGuiInputTextFlags_EnterReturnsTrue without maintaining any user-side storage (please note that if you use this property along ImGuiInputTextFlags_CallbackResize you can end up with your temporary string object unnecessarily allocating once a frame, either store your string data, either if you don't then don't use ImGuiInputTextFlags_CallbackResize).\r\n        bool apply_edit_back_to_user_buffer = !cancel_edit || (enter_pressed && (flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0);\r\n        if (apply_edit_back_to_user_buffer)\r\n        {\r\n            // Apply new value immediately - copy modified buffer back\r\n            // Note that as soon as the input box is active, the in-widget value gets priority over any underlying modification of the input buffer\r\n            // FIXME: We actually always render 'buf' when calling DrawList->AddText, making the comment above incorrect.\r\n            // FIXME-OPT: CPU waste to do this every time the widget is active, should mark dirty state from the stb_textedit callbacks.\r\n            if (!is_readonly)\r\n            {\r\n                state->TextAIsValid = true;\r\n                state->TextA.resize(state->TextW.Size * 4 + 1);\r\n                ImTextStrToUtf8(state->TextA.Data, state->TextA.Size, state->TextW.Data, NULL);\r\n            }\r\n\r\n            // User callback\r\n            if ((flags & (ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory | ImGuiInputTextFlags_CallbackEdit | ImGuiInputTextFlags_CallbackAlways)) != 0)\r\n            {\r\n                IM_ASSERT(callback != NULL);\r\n\r\n                // The reason we specify the usage semantic (Completion/History) is that Completion needs to disable keyboard TABBING at the moment.\r\n                ImGuiInputTextFlags event_flag = 0;\r\n                ImGuiKey event_key = ImGuiKey_None;\r\n                if ((flags & ImGuiInputTextFlags_CallbackCompletion) != 0 && IsKeyPressed(ImGuiKey_Tab))\r\n                {\r\n                    event_flag = ImGuiInputTextFlags_CallbackCompletion;\r\n                    event_key = ImGuiKey_Tab;\r\n                }\r\n                else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressed(ImGuiKey_UpArrow))\r\n                {\r\n                    event_flag = ImGuiInputTextFlags_CallbackHistory;\r\n                    event_key = ImGuiKey_UpArrow;\r\n                }\r\n                else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressed(ImGuiKey_DownArrow))\r\n                {\r\n                    event_flag = ImGuiInputTextFlags_CallbackHistory;\r\n                    event_key = ImGuiKey_DownArrow;\r\n                }\r\n                else if ((flags & ImGuiInputTextFlags_CallbackEdit) && state->Edited)\r\n                {\r\n                    event_flag = ImGuiInputTextFlags_CallbackEdit;\r\n                }\r\n                else if (flags & ImGuiInputTextFlags_CallbackAlways)\r\n                {\r\n                    event_flag = ImGuiInputTextFlags_CallbackAlways;\r\n                }\r\n\r\n                if (event_flag)\r\n                {\r\n                    ImGuiInputTextCallbackData callback_data;\r\n                    memset(&callback_data, 0, sizeof(ImGuiInputTextCallbackData));\r\n                    callback_data.EventFlag = event_flag;\r\n                    callback_data.Flags = flags;\r\n                    callback_data.UserData = callback_user_data;\r\n\r\n                    char* callback_buf = is_readonly ? buf : state->TextA.Data;\r\n                    callback_data.EventKey = event_key;\r\n                    callback_data.Buf = callback_buf;\r\n                    callback_data.BufTextLen = state->CurLenA;\r\n                    callback_data.BufSize = state->BufCapacityA;\r\n                    callback_data.BufDirty = false;\r\n\r\n                    // We have to convert from wchar-positions to UTF-8-positions, which can be pretty slow (an incentive to ditch the ImWchar buffer, see https://github.com/nothings/stb/issues/188)\r\n                    ImWchar* text = state->TextW.Data;\r\n                    const int utf8_cursor_pos = callback_data.CursorPos = ImTextCountUtf8BytesFromStr(text, text + state->Stb.cursor);\r\n                    const int utf8_selection_start = callback_data.SelectionStart = ImTextCountUtf8BytesFromStr(text, text + state->Stb.select_start);\r\n                    const int utf8_selection_end = callback_data.SelectionEnd = ImTextCountUtf8BytesFromStr(text, text + state->Stb.select_end);\r\n\r\n                    // Call user code\r\n                    callback(&callback_data);\r\n\r\n                    // Read back what user may have modified\r\n                    callback_buf = is_readonly ? buf : state->TextA.Data; // Pointer may have been invalidated by a resize callback\r\n                    IM_ASSERT(callback_data.Buf == callback_buf);         // Invalid to modify those fields\r\n                    IM_ASSERT(callback_data.BufSize == state->BufCapacityA);\r\n                    IM_ASSERT(callback_data.Flags == flags);\r\n                    const bool buf_dirty = callback_data.BufDirty;\r\n                    if (callback_data.CursorPos != utf8_cursor_pos || buf_dirty)            { state->Stb.cursor = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.CursorPos); state->CursorFollow = true; }\r\n                    if (callback_data.SelectionStart != utf8_selection_start || buf_dirty)  { state->Stb.select_start = (callback_data.SelectionStart == callback_data.CursorPos) ? state->Stb.cursor : ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionStart); }\r\n                    if (callback_data.SelectionEnd != utf8_selection_end || buf_dirty)      { state->Stb.select_end = (callback_data.SelectionEnd == callback_data.SelectionStart) ? state->Stb.select_start : ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionEnd); }\r\n                    if (buf_dirty)\r\n                    {\r\n                        IM_ASSERT(callback_data.BufTextLen == (int)strlen(callback_data.Buf)); // You need to maintain BufTextLen if you change the text!\r\n                        if (callback_data.BufTextLen > backup_current_text_length && is_resizable)\r\n                            state->TextW.resize(state->TextW.Size + (callback_data.BufTextLen - backup_current_text_length));\r\n                        state->CurLenW = ImTextStrFromUtf8(state->TextW.Data, state->TextW.Size, callback_data.Buf, NULL);\r\n                        state->CurLenA = callback_data.BufTextLen;  // Assume correct length and valid UTF-8 from user, saves us an extra strlen()\r\n                        state->CursorAnimReset();\r\n                    }\r\n                }\r\n            }\r\n\r\n            // Will copy result string if modified\r\n            if (!is_readonly && strcmp(state->TextA.Data, buf) != 0)\r\n            {\r\n                apply_new_text = state->TextA.Data;\r\n                apply_new_text_length = state->CurLenA;\r\n            }\r\n        }\r\n\r\n        // Clear temporary user storage\r\n        state->Flags = ImGuiInputTextFlags_None;\r\n    }\r\n\r\n    // Copy result to user buffer. This can currently only happen when (g.ActiveId == id)\r\n    if (apply_new_text != NULL)\r\n    {\r\n        // We cannot test for 'backup_current_text_length != apply_new_text_length' here because we have no guarantee that the size\r\n        // of our owned buffer matches the size of the string object held by the user, and by design we allow InputText() to be used\r\n        // without any storage on user's side.\r\n        IM_ASSERT(apply_new_text_length >= 0);\r\n        if (is_resizable)\r\n        {\r\n            ImGuiInputTextCallbackData callback_data;\r\n            callback_data.EventFlag = ImGuiInputTextFlags_CallbackResize;\r\n            callback_data.Flags = flags;\r\n            callback_data.Buf = buf;\r\n            callback_data.BufTextLen = apply_new_text_length;\r\n            callback_data.BufSize = ImMax(buf_size, apply_new_text_length + 1);\r\n            callback_data.UserData = callback_user_data;\r\n            callback(&callback_data);\r\n            buf = callback_data.Buf;\r\n            buf_size = callback_data.BufSize;\r\n            apply_new_text_length = ImMin(callback_data.BufTextLen, buf_size - 1);\r\n            IM_ASSERT(apply_new_text_length <= buf_size);\r\n        }\r\n        //IMGUI_DEBUG_LOG(\"InputText(\\\"%s\\\"): apply_new_text length %d\\n\", label, apply_new_text_length);\r\n\r\n        // If the underlying buffer resize was denied or not carried to the next frame, apply_new_text_length+1 may be >= buf_size.\r\n        ImStrncpy(buf, apply_new_text, ImMin(apply_new_text_length + 1, buf_size));\r\n        value_changed = true;\r\n    }\r\n\r\n    // Release active ID at the end of the function (so e.g. pressing Return still does a final application of the value)\r\n    if (clear_active_id && g.ActiveId == id)\r\n        ClearActiveID();\r\n\r\n    // Render frame\r\n    if (!is_multiline)\r\n    {\r\n        RenderNavHighlight(frame_bb, id);\r\n        RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);\r\n    }\r\n\r\n    const ImVec4 clip_rect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + inner_size.x, frame_bb.Min.y + inner_size.y); // Not using frame_bb.Max because we have adjusted size\r\n    ImVec2 draw_pos = is_multiline ? draw_window->DC.CursorPos : frame_bb.Min + style.FramePadding;\r\n    ImVec2 text_size(0.0f, 0.0f);\r\n\r\n    // Set upper limit of single-line InputTextEx() at 2 million characters strings. The current pathological worst case is a long line\r\n    // without any carriage return, which would makes ImFont::RenderText() reserve too many vertices and probably crash. Avoid it altogether.\r\n    // Note that we only use this limit on single-line InputText(), so a pathologically large line on a InputTextMultiline() would still crash.\r\n    const int buf_display_max_length = 2 * 1024 * 1024;\r\n    const char* buf_display = buf_display_from_state ? state->TextA.Data : buf; //-V595\r\n    const char* buf_display_end = NULL; // We have specialized paths below for setting the length\r\n    if (is_displaying_hint)\r\n    {\r\n        buf_display = hint;\r\n        buf_display_end = hint + strlen(hint);\r\n    }\r\n\r\n    // Render text. We currently only render selection when the widget is active or while scrolling.\r\n    // FIXME: We could remove the '&& render_cursor' to keep rendering selection when inactive.\r\n    if (render_cursor || render_selection)\r\n    {\r\n        IM_ASSERT(state != NULL);\r\n        if (!is_displaying_hint)\r\n            buf_display_end = buf_display + state->CurLenA;\r\n\r\n        // Render text (with cursor and selection)\r\n        // This is going to be messy. We need to:\r\n        // - Display the text (this alone can be more easily clipped)\r\n        // - Handle scrolling, highlight selection, display cursor (those all requires some form of 1d->2d cursor position calculation)\r\n        // - Measure text height (for scrollbar)\r\n        // We are attempting to do most of that in **one main pass** to minimize the computation cost (non-negligible for large amount of text) + 2nd pass for selection rendering (we could merge them by an extra refactoring effort)\r\n        // FIXME: This should occur on buf_display but we'd need to maintain cursor/select_start/select_end for UTF-8.\r\n        const ImWchar* text_begin = state->TextW.Data;\r\n        ImVec2 cursor_offset, select_start_offset;\r\n\r\n        {\r\n            // Find lines numbers straddling 'cursor' (slot 0) and 'select_start' (slot 1) positions.\r\n            const ImWchar* searches_input_ptr[2] = { NULL, NULL };\r\n            int searches_result_line_no[2] = { -1000, -1000 };\r\n            int searches_remaining = 0;\r\n            if (render_cursor)\r\n            {\r\n                searches_input_ptr[0] = text_begin + state->Stb.cursor;\r\n                searches_result_line_no[0] = -1;\r\n                searches_remaining++;\r\n            }\r\n            if (render_selection)\r\n            {\r\n                searches_input_ptr[1] = text_begin + ImMin(state->Stb.select_start, state->Stb.select_end);\r\n                searches_result_line_no[1] = -1;\r\n                searches_remaining++;\r\n            }\r\n\r\n            // Iterate all lines to find our line numbers\r\n            // In multi-line mode, we never exit the loop until all lines are counted, so add one extra to the searches_remaining counter.\r\n            searches_remaining += is_multiline ? 1 : 0;\r\n            int line_count = 0;\r\n            //for (const ImWchar* s = text_begin; (s = (const ImWchar*)wcschr((const wchar_t*)s, (wchar_t)'\\n')) != NULL; s++)  // FIXME-OPT: Could use this when wchar_t are 16-bit\r\n            for (const ImWchar* s = text_begin; *s != 0; s++)\r\n                if (*s == '\\n')\r\n                {\r\n                    line_count++;\r\n                    if (searches_result_line_no[0] == -1 && s >= searches_input_ptr[0]) { searches_result_line_no[0] = line_count; if (--searches_remaining <= 0) break; }\r\n                    if (searches_result_line_no[1] == -1 && s >= searches_input_ptr[1]) { searches_result_line_no[1] = line_count; if (--searches_remaining <= 0) break; }\r\n                }\r\n            line_count++;\r\n            if (searches_result_line_no[0] == -1)\r\n                searches_result_line_no[0] = line_count;\r\n            if (searches_result_line_no[1] == -1)\r\n                searches_result_line_no[1] = line_count;\r\n\r\n            // Calculate 2d position by finding the beginning of the line and measuring distance\r\n            cursor_offset.x = InputTextCalcTextSizeW(ImStrbolW(searches_input_ptr[0], text_begin), searches_input_ptr[0]).x;\r\n            cursor_offset.y = searches_result_line_no[0] * g.FontSize;\r\n            if (searches_result_line_no[1] >= 0)\r\n            {\r\n                select_start_offset.x = InputTextCalcTextSizeW(ImStrbolW(searches_input_ptr[1], text_begin), searches_input_ptr[1]).x;\r\n                select_start_offset.y = searches_result_line_no[1] * g.FontSize;\r\n            }\r\n\r\n            // Store text height (note that we haven't calculated text width at all, see GitHub issues #383, #1224)\r\n            if (is_multiline)\r\n                text_size = ImVec2(inner_size.x, line_count * g.FontSize);\r\n        }\r\n\r\n        // Scroll\r\n        if (render_cursor && state->CursorFollow)\r\n        {\r\n            // Horizontal scroll in chunks of quarter width\r\n            if (!(flags & ImGuiInputTextFlags_NoHorizontalScroll))\r\n            {\r\n                const float scroll_increment_x = inner_size.x * 0.25f;\r\n                const float visible_width = inner_size.x - style.FramePadding.x;\r\n                if (cursor_offset.x < state->ScrollX)\r\n                    state->ScrollX = IM_FLOOR(ImMax(0.0f, cursor_offset.x - scroll_increment_x));\r\n                else if (cursor_offset.x - visible_width >= state->ScrollX)\r\n                    state->ScrollX = IM_FLOOR(cursor_offset.x - visible_width + scroll_increment_x);\r\n            }\r\n            else\r\n            {\r\n                state->ScrollX = 0.0f;\r\n            }\r\n\r\n            // Vertical scroll\r\n            if (is_multiline)\r\n            {\r\n                // Test if cursor is vertically visible\r\n                if (cursor_offset.y - g.FontSize < scroll_y)\r\n                    scroll_y = ImMax(0.0f, cursor_offset.y - g.FontSize);\r\n                else if (cursor_offset.y - (inner_size.y - style.FramePadding.y * 2.0f) >= scroll_y)\r\n                    scroll_y = cursor_offset.y - inner_size.y + style.FramePadding.y * 2.0f;\r\n                const float scroll_max_y = ImMax((text_size.y + style.FramePadding.y * 2.0f) - inner_size.y, 0.0f);\r\n                scroll_y = ImClamp(scroll_y, 0.0f, scroll_max_y);\r\n                draw_pos.y += (draw_window->Scroll.y - scroll_y);   // Manipulate cursor pos immediately avoid a frame of lag\r\n                draw_window->Scroll.y = scroll_y;\r\n            }\r\n\r\n            state->CursorFollow = false;\r\n        }\r\n\r\n        // Draw selection\r\n        const ImVec2 draw_scroll = ImVec2(state->ScrollX, 0.0f);\r\n        if (render_selection)\r\n        {\r\n            const ImWchar* text_selected_begin = text_begin + ImMin(state->Stb.select_start, state->Stb.select_end);\r\n            const ImWchar* text_selected_end = text_begin + ImMax(state->Stb.select_start, state->Stb.select_end);\r\n\r\n            ImU32 bg_color = GetColorU32(ImGuiCol_TextSelectedBg, render_cursor ? 1.0f : 0.6f); // FIXME: current code flow mandate that render_cursor is always true here, we are leaving the transparent one for tests.\r\n            float bg_offy_up = is_multiline ? 0.0f : -1.0f;    // FIXME: those offsets should be part of the style? they don't play so well with multi-line selection.\r\n            float bg_offy_dn = is_multiline ? 0.0f : 2.0f;\r\n            ImVec2 rect_pos = draw_pos + select_start_offset - draw_scroll;\r\n            for (const ImWchar* p = text_selected_begin; p < text_selected_end; )\r\n            {\r\n                if (rect_pos.y > clip_rect.w + g.FontSize)\r\n                    break;\r\n                if (rect_pos.y < clip_rect.y)\r\n                {\r\n                    //p = (const ImWchar*)wmemchr((const wchar_t*)p, '\\n', text_selected_end - p);  // FIXME-OPT: Could use this when wchar_t are 16-bit\r\n                    //p = p ? p + 1 : text_selected_end;\r\n                    while (p < text_selected_end)\r\n                        if (*p++ == '\\n')\r\n                            break;\r\n                }\r\n                else\r\n                {\r\n                    ImVec2 rect_size = InputTextCalcTextSizeW(p, text_selected_end, &p, NULL, true);\r\n                    if (rect_size.x <= 0.0f) rect_size.x = IM_FLOOR(g.Font->GetCharAdvance((ImWchar)' ') * 0.50f); // So we can see selected empty lines\r\n                    ImRect rect(rect_pos + ImVec2(0.0f, bg_offy_up - g.FontSize), rect_pos + ImVec2(rect_size.x, bg_offy_dn));\r\n                    rect.ClipWith(clip_rect);\r\n                    if (rect.Overlaps(clip_rect))\r\n                        draw_window->DrawList->AddRectFilled(rect.Min, rect.Max, bg_color);\r\n                }\r\n                rect_pos.x = draw_pos.x - draw_scroll.x;\r\n                rect_pos.y += g.FontSize;\r\n            }\r\n        }\r\n\r\n        // We test for 'buf_display_max_length' as a way to avoid some pathological cases (e.g. single-line 1 MB string) which would make ImDrawList crash.\r\n        if (is_multiline || (buf_display_end - buf_display) < buf_display_max_length)\r\n        {\r\n            ImU32 col = GetColorU32(is_displaying_hint ? ImGuiCol_TextDisabled : ImGuiCol_Text);\r\n            draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos - draw_scroll, col, buf_display, buf_display_end, 0.0f, is_multiline ? NULL : &clip_rect);\r\n        }\r\n\r\n        // Draw blinking cursor\r\n        if (render_cursor)\r\n        {\r\n            state->CursorAnim += io.DeltaTime;\r\n            bool cursor_is_visible = (!g.IO.ConfigInputTextCursorBlink) || (state->CursorAnim <= 0.0f) || ImFmod(state->CursorAnim, 1.20f) <= 0.80f;\r\n            ImVec2 cursor_screen_pos = ImFloor(draw_pos + cursor_offset - draw_scroll);\r\n            ImRect cursor_screen_rect(cursor_screen_pos.x, cursor_screen_pos.y - g.FontSize + 0.5f, cursor_screen_pos.x + 1.0f, cursor_screen_pos.y - 1.5f);\r\n            if (cursor_is_visible && cursor_screen_rect.Overlaps(clip_rect))\r\n                draw_window->DrawList->AddLine(cursor_screen_rect.Min, cursor_screen_rect.GetBL(), GetColorU32(ImGuiCol_Text));\r\n\r\n            // Notify OS of text input position for advanced IME (-1 x offset so that Windows IME can cover our cursor. Bit of an extra nicety.)\r\n            if (!is_readonly)\r\n            {\r\n                g.PlatformImeData.WantVisible = true;\r\n                g.PlatformImeData.InputPos = ImVec2(cursor_screen_pos.x - 1.0f, cursor_screen_pos.y - g.FontSize);\r\n                g.PlatformImeData.InputLineHeight = g.FontSize;\r\n            }\r\n        }\r\n    }\r\n    else\r\n    {\r\n        // Render text only (no selection, no cursor)\r\n        if (is_multiline)\r\n            text_size = ImVec2(inner_size.x, InputTextCalcTextLenAndLineCount(buf_display, &buf_display_end) * g.FontSize); // We don't need width\r\n        else if (!is_displaying_hint && g.ActiveId == id)\r\n            buf_display_end = buf_display + state->CurLenA;\r\n        else if (!is_displaying_hint)\r\n            buf_display_end = buf_display + strlen(buf_display);\r\n\r\n        if (is_multiline || (buf_display_end - buf_display) < buf_display_max_length)\r\n        {\r\n            ImU32 col = GetColorU32(is_displaying_hint ? ImGuiCol_TextDisabled : ImGuiCol_Text);\r\n            draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos, col, buf_display, buf_display_end, 0.0f, is_multiline ? NULL : &clip_rect);\r\n        }\r\n    }\r\n\r\n    if (is_password && !is_displaying_hint)\r\n        PopFont();\r\n\r\n    if (is_multiline)\r\n    {\r\n        // For focus requests to work on our multiline we need to ensure our child ItemAdd() call specifies the ImGuiItemFlags_Inputable (ref issue #4761)...\r\n        Dummy(ImVec2(text_size.x, text_size.y + style.FramePadding.y));\r\n        ImGuiItemFlags backup_item_flags = g.CurrentItemFlags;\r\n        g.CurrentItemFlags |= ImGuiItemFlags_Inputable | ImGuiItemFlags_NoTabStop;\r\n        EndChild();\r\n        item_data_backup.StatusFlags |= (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredWindow);\r\n        g.CurrentItemFlags = backup_item_flags;\r\n\r\n        // ...and then we need to undo the group overriding last item data, which gets a bit messy as EndGroup() tries to forward scrollbar being active...\r\n        // FIXME: This quite messy/tricky, should attempt to get rid of the child window.\r\n        EndGroup();\r\n        if (g.LastItemData.ID == 0)\r\n        {\r\n            g.LastItemData.ID = id;\r\n            g.LastItemData.InFlags = item_data_backup.InFlags;\r\n            g.LastItemData.StatusFlags = item_data_backup.StatusFlags;\r\n        }\r\n    }\r\n\r\n    // Log as text\r\n    if (g.LogEnabled && (!is_password || is_displaying_hint))\r\n    {\r\n        LogSetNextTextDecoration(\"{\", \"}\");\r\n        LogRenderedText(&draw_pos, buf_display, buf_display_end);\r\n    }\r\n\r\n    if (label_size.x > 0)\r\n        RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);\r\n\r\n    if (value_changed && !(flags & ImGuiInputTextFlags_NoMarkEdited))\r\n        MarkItemEdited(id);\r\n\r\n    IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags);\r\n    if ((flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0)\r\n        return enter_pressed;\r\n    else\r\n        return value_changed;\r\n}\r\n\r\n//-------------------------------------------------------------------------\r\n// [SECTION] Widgets: ColorEdit, ColorPicker, ColorButton, etc.\r\n//-------------------------------------------------------------------------\r\n// - ColorEdit3()\r\n// - ColorEdit4()\r\n// - ColorPicker3()\r\n// - RenderColorRectWithAlphaCheckerboard() [Internal]\r\n// - ColorPicker4()\r\n// - ColorButton()\r\n// - SetColorEditOptions()\r\n// - ColorTooltip() [Internal]\r\n// - ColorEditOptionsPopup() [Internal]\r\n// - ColorPickerOptionsPopup() [Internal]\r\n//-------------------------------------------------------------------------\r\n\r\nbool ImGui::ColorEdit3(const char* label, float col[3], ImGuiColorEditFlags flags)\r\n{\r\n    return ColorEdit4(label, col, flags | ImGuiColorEditFlags_NoAlpha);\r\n}\r\n\r\n// ColorEdit supports RGB and HSV inputs. In case of RGB input resulting color may have undefined hue and/or saturation.\r\n// Since widget displays both RGB and HSV values we must preserve hue and saturation to prevent these values resetting.\r\nstatic void ColorEditRestoreHS(const float* col, float* H, float* S, float* V)\r\n{\r\n    // This check is optional. Suppose we have two color widgets side by side, both widgets display different colors, but both colors have hue and/or saturation undefined.\r\n    // With color check: hue/saturation is preserved in one widget. Editing color in one widget would reset hue/saturation in another one.\r\n    // Without color check: common hue/saturation would be displayed in all widgets that have hue/saturation undefined.\r\n    // g.ColorEditLastColor is stored as ImU32 RGB value: this essentially gives us color equality check with reduced precision.\r\n    // Tiny external color changes would not be detected and this check would still pass. This is OK, since we only restore hue/saturation _only_ if they are undefined,\r\n    // therefore this change flipping hue/saturation from undefined to a very tiny value would still be represented in color picker.\r\n    ImGuiContext& g = *GImGui;\r\n    if (g.ColorEditLastColor != ImGui::ColorConvertFloat4ToU32(ImVec4(col[0], col[1], col[2], 0)))\r\n        return;\r\n\r\n    // When S == 0, H is undefined.\r\n    // When H == 1 it wraps around to 0.\r\n    if (*S == 0.0f || (*H == 0.0f && g.ColorEditLastHue == 1))\r\n        *H = g.ColorEditLastHue;\r\n\r\n    // When V == 0, S is undefined.\r\n    if (*V == 0.0f)\r\n        *S = g.ColorEditLastSat;\r\n}\r\n\r\n// Edit colors components (each component in 0.0f..1.0f range).\r\n// See enum ImGuiColorEditFlags_ for available options. e.g. Only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set.\r\n// With typical options: Left-click on color square to open color picker. Right-click to open option menu. CTRL-Click over input fields to edit them and TAB to go to next item.\r\nbool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return false;\r\n\r\n    ImGuiContext& g = *GImGui;\r\n    const ImGuiStyle& style = g.Style;\r\n    const float square_sz = GetFrameHeight();\r\n    const float w_full = CalcItemWidth();\r\n    const float w_button = (flags & ImGuiColorEditFlags_NoSmallPreview) ? 0.0f : (square_sz + style.ItemInnerSpacing.x);\r\n    const float w_inputs = w_full - w_button;\r\n    const char* label_display_end = FindRenderedTextEnd(label);\r\n    g.NextItemData.ClearFlags();\r\n\r\n    BeginGroup();\r\n    PushID(label);\r\n\r\n    // If we're not showing any slider there's no point in doing any HSV conversions\r\n    const ImGuiColorEditFlags flags_untouched = flags;\r\n    if (flags & ImGuiColorEditFlags_NoInputs)\r\n        flags = (flags & (~ImGuiColorEditFlags_DisplayMask_)) | ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_NoOptions;\r\n\r\n    // Context menu: display and modify options (before defaults are applied)\r\n    if (!(flags & ImGuiColorEditFlags_NoOptions))\r\n        ColorEditOptionsPopup(col, flags);\r\n\r\n    // Read stored options\r\n    if (!(flags & ImGuiColorEditFlags_DisplayMask_))\r\n        flags |= (g.ColorEditOptions & ImGuiColorEditFlags_DisplayMask_);\r\n    if (!(flags & ImGuiColorEditFlags_DataTypeMask_))\r\n        flags |= (g.ColorEditOptions & ImGuiColorEditFlags_DataTypeMask_);\r\n    if (!(flags & ImGuiColorEditFlags_PickerMask_))\r\n        flags |= (g.ColorEditOptions & ImGuiColorEditFlags_PickerMask_);\r\n    if (!(flags & ImGuiColorEditFlags_InputMask_))\r\n        flags |= (g.ColorEditOptions & ImGuiColorEditFlags_InputMask_);\r\n    flags |= (g.ColorEditOptions & ~(ImGuiColorEditFlags_DisplayMask_ | ImGuiColorEditFlags_DataTypeMask_ | ImGuiColorEditFlags_PickerMask_ | ImGuiColorEditFlags_InputMask_));\r\n    IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_DisplayMask_)); // Check that only 1 is selected\r\n    IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_InputMask_));   // Check that only 1 is selected\r\n\r\n    const bool alpha = (flags & ImGuiColorEditFlags_NoAlpha) == 0;\r\n    const bool hdr = (flags & ImGuiColorEditFlags_HDR) != 0;\r\n    const int components = alpha ? 4 : 3;\r\n\r\n    // Convert to the formats we need\r\n    float f[4] = { col[0], col[1], col[2], alpha ? col[3] : 1.0f };\r\n    if ((flags & ImGuiColorEditFlags_InputHSV) && (flags & ImGuiColorEditFlags_DisplayRGB))\r\n        ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]);\r\n    else if ((flags & ImGuiColorEditFlags_InputRGB) && (flags & ImGuiColorEditFlags_DisplayHSV))\r\n    {\r\n        // Hue is lost when converting from greyscale rgb (saturation=0). Restore it.\r\n        ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]);\r\n        ColorEditRestoreHS(col, &f[0], &f[1], &f[2]);\r\n    }\r\n    int i[4] = { IM_F32_TO_INT8_UNBOUND(f[0]), IM_F32_TO_INT8_UNBOUND(f[1]), IM_F32_TO_INT8_UNBOUND(f[2]), IM_F32_TO_INT8_UNBOUND(f[3]) };\r\n\r\n    bool value_changed = false;\r\n    bool value_changed_as_float = false;\r\n\r\n    const ImVec2 pos = window->DC.CursorPos;\r\n    const float inputs_offset_x = (style.ColorButtonPosition == ImGuiDir_Left) ? w_button : 0.0f;\r\n    window->DC.CursorPos.x = pos.x + inputs_offset_x;\r\n\r\n    if ((flags & (ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_DisplayHSV)) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0)\r\n    {\r\n        // RGB/HSV 0..255 Sliders\r\n        const float w_item_one  = ImMax(1.0f, IM_FLOOR((w_inputs - (style.ItemInnerSpacing.x) * (components - 1)) / (float)components));\r\n        const float w_item_last = ImMax(1.0f, IM_FLOOR(w_inputs - (w_item_one + style.ItemInnerSpacing.x) * (components - 1)));\r\n\r\n        const bool hide_prefix = (w_item_one <= CalcTextSize((flags & ImGuiColorEditFlags_Float) ? \"M:0.000\" : \"M:000\").x);\r\n        static const char* ids[4] = { \"##X\", \"##Y\", \"##Z\", \"##W\" };\r\n        static const char* fmt_table_int[3][4] =\r\n        {\r\n            {   \"%3d\",   \"%3d\",   \"%3d\",   \"%3d\" }, // Short display\r\n            { \"R:%3d\", \"G:%3d\", \"B:%3d\", \"A:%3d\" }, // Long display for RGBA\r\n            { \"H:%3d\", \"S:%3d\", \"V:%3d\", \"A:%3d\" }  // Long display for HSVA\r\n        };\r\n        static const char* fmt_table_float[3][4] =\r\n        {\r\n            {   \"%0.3f\",   \"%0.3f\",   \"%0.3f\",   \"%0.3f\" }, // Short display\r\n            { \"R:%0.3f\", \"G:%0.3f\", \"B:%0.3f\", \"A:%0.3f\" }, // Long display for RGBA\r\n            { \"H:%0.3f\", \"S:%0.3f\", \"V:%0.3f\", \"A:%0.3f\" }  // Long display for HSVA\r\n        };\r\n        const int fmt_idx = hide_prefix ? 0 : (flags & ImGuiColorEditFlags_DisplayHSV) ? 2 : 1;\r\n\r\n        for (int n = 0; n < components; n++)\r\n        {\r\n            if (n > 0)\r\n                SameLine(0, style.ItemInnerSpacing.x);\r\n            SetNextItemWidth((n + 1 < components) ? w_item_one : w_item_last);\r\n\r\n            // FIXME: When ImGuiColorEditFlags_HDR flag is passed HS values snap in weird ways when SV values go below 0.\r\n            if (flags & ImGuiColorEditFlags_Float)\r\n            {\r\n                value_changed |= DragFloat(ids[n], &f[n], 1.0f / 255.0f, 0.0f, hdr ? 0.0f : 1.0f, fmt_table_float[fmt_idx][n]);\r\n                value_changed_as_float |= value_changed;\r\n            }\r\n            else\r\n            {\r\n                value_changed |= DragInt(ids[n], &i[n], 1.0f, 0, hdr ? 0 : 255, fmt_table_int[fmt_idx][n]);\r\n            }\r\n            if (!(flags & ImGuiColorEditFlags_NoOptions))\r\n                OpenPopupOnItemClick(\"context\", ImGuiPopupFlags_MouseButtonRight);\r\n        }\r\n    }\r\n    else if ((flags & ImGuiColorEditFlags_DisplayHex) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0)\r\n    {\r\n        // RGB Hexadecimal Input\r\n        char buf[64];\r\n        if (alpha)\r\n            ImFormatString(buf, IM_ARRAYSIZE(buf), \"#%02X%02X%02X%02X\", ImClamp(i[0], 0, 255), ImClamp(i[1], 0, 255), ImClamp(i[2], 0, 255), ImClamp(i[3], 0, 255));\r\n        else\r\n            ImFormatString(buf, IM_ARRAYSIZE(buf), \"#%02X%02X%02X\", ImClamp(i[0], 0, 255), ImClamp(i[1], 0, 255), ImClamp(i[2], 0, 255));\r\n        SetNextItemWidth(w_inputs);\r\n        if (InputText(\"##Text\", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase))\r\n        {\r\n            value_changed = true;\r\n            char* p = buf;\r\n            while (*p == '#' || ImCharIsBlankA(*p))\r\n                p++;\r\n            i[0] = i[1] = i[2] = 0;\r\n            i[3] = 0xFF; // alpha default to 255 is not parsed by scanf (e.g. inputting #FFFFFF omitting alpha)\r\n            int r;\r\n            if (alpha)\r\n                r = sscanf(p, \"%02X%02X%02X%02X\", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2], (unsigned int*)&i[3]); // Treat at unsigned (%X is unsigned)\r\n            else\r\n                r = sscanf(p, \"%02X%02X%02X\", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2]);\r\n            IM_UNUSED(r); // Fixes C6031: Return value ignored: 'sscanf'.\r\n        }\r\n        if (!(flags & ImGuiColorEditFlags_NoOptions))\r\n            OpenPopupOnItemClick(\"context\", ImGuiPopupFlags_MouseButtonRight);\r\n    }\r\n\r\n    ImGuiWindow* picker_active_window = NULL;\r\n    if (!(flags & ImGuiColorEditFlags_NoSmallPreview))\r\n    {\r\n        const float button_offset_x = ((flags & ImGuiColorEditFlags_NoInputs) || (style.ColorButtonPosition == ImGuiDir_Left)) ? 0.0f : w_inputs + style.ItemInnerSpacing.x;\r\n        window->DC.CursorPos = ImVec2(pos.x + button_offset_x, pos.y);\r\n\r\n        const ImVec4 col_v4(col[0], col[1], col[2], alpha ? col[3] : 1.0f);\r\n        if (ColorButton(\"##ColorButton\", col_v4, flags))\r\n        {\r\n            if (!(flags & ImGuiColorEditFlags_NoPicker))\r\n            {\r\n                // Store current color and open a picker\r\n                g.ColorPickerRef = col_v4;\r\n                OpenPopup(\"picker\");\r\n                SetNextWindowPos(g.LastItemData.Rect.GetBL() + ImVec2(0.0f, style.ItemSpacing.y));\r\n            }\r\n        }\r\n        if (!(flags & ImGuiColorEditFlags_NoOptions))\r\n            OpenPopupOnItemClick(\"context\", ImGuiPopupFlags_MouseButtonRight);\r\n\r\n        if (BeginPopup(\"picker\"))\r\n        {\r\n            picker_active_window = g.CurrentWindow;\r\n            if (label != label_display_end)\r\n            {\r\n                TextEx(label, label_display_end);\r\n                Spacing();\r\n            }\r\n            ImGuiColorEditFlags picker_flags_to_forward = ImGuiColorEditFlags_DataTypeMask_ | ImGuiColorEditFlags_PickerMask_ | ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaBar;\r\n            ImGuiColorEditFlags picker_flags = (flags_untouched & picker_flags_to_forward) | ImGuiColorEditFlags_DisplayMask_ | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_AlphaPreviewHalf;\r\n            SetNextItemWidth(square_sz * 12.0f); // Use 256 + bar sizes?\r\n            value_changed |= ColorPicker4(\"##picker\", col, picker_flags, &g.ColorPickerRef.x);\r\n            EndPopup();\r\n        }\r\n    }\r\n\r\n    if (label != label_display_end && !(flags & ImGuiColorEditFlags_NoLabel))\r\n    {\r\n        const float text_offset_x = (flags & ImGuiColorEditFlags_NoInputs) ? w_button : w_full + style.ItemInnerSpacing.x;\r\n        window->DC.CursorPos = ImVec2(pos.x + text_offset_x, pos.y + style.FramePadding.y);\r\n        TextEx(label, label_display_end);\r\n    }\r\n\r\n    // Convert back\r\n    if (value_changed && picker_active_window == NULL)\r\n    {\r\n        if (!value_changed_as_float)\r\n            for (int n = 0; n < 4; n++)\r\n                f[n] = i[n] / 255.0f;\r\n        if ((flags & ImGuiColorEditFlags_DisplayHSV) && (flags & ImGuiColorEditFlags_InputRGB))\r\n        {\r\n            g.ColorEditLastHue = f[0];\r\n            g.ColorEditLastSat = f[1];\r\n            ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]);\r\n            g.ColorEditLastColor = ColorConvertFloat4ToU32(ImVec4(f[0], f[1], f[2], 0));\r\n        }\r\n        if ((flags & ImGuiColorEditFlags_DisplayRGB) && (flags & ImGuiColorEditFlags_InputHSV))\r\n            ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]);\r\n\r\n        col[0] = f[0];\r\n        col[1] = f[1];\r\n        col[2] = f[2];\r\n        if (alpha)\r\n            col[3] = f[3];\r\n    }\r\n\r\n    PopID();\r\n    EndGroup();\r\n\r\n    // Drag and Drop Target\r\n    // NB: The flag test is merely an optional micro-optimization, BeginDragDropTarget() does the same test.\r\n    if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) && !(flags & ImGuiColorEditFlags_NoDragDrop) && BeginDragDropTarget())\r\n    {\r\n        bool accepted_drag_drop = false;\r\n        if (const ImGuiPayload* payload = AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F))\r\n        {\r\n            memcpy((float*)col, payload->Data, sizeof(float) * 3); // Preserve alpha if any //-V512\r\n            value_changed = accepted_drag_drop = true;\r\n        }\r\n        if (const ImGuiPayload* payload = AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F))\r\n        {\r\n            memcpy((float*)col, payload->Data, sizeof(float) * components);\r\n            value_changed = accepted_drag_drop = true;\r\n        }\r\n\r\n        // Drag-drop payloads are always RGB\r\n        if (accepted_drag_drop && (flags & ImGuiColorEditFlags_InputHSV))\r\n            ColorConvertRGBtoHSV(col[0], col[1], col[2], col[0], col[1], col[2]);\r\n        EndDragDropTarget();\r\n    }\r\n\r\n    // When picker is being actively used, use its active id so IsItemActive() will function on ColorEdit4().\r\n    if (picker_active_window && g.ActiveId != 0 && g.ActiveIdWindow == picker_active_window)\r\n        g.LastItemData.ID = g.ActiveId;\r\n\r\n    if (value_changed)\r\n        MarkItemEdited(g.LastItemData.ID);\r\n\r\n    return value_changed;\r\n}\r\n\r\nbool ImGui::ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags flags)\r\n{\r\n    float col4[4] = { col[0], col[1], col[2], 1.0f };\r\n    if (!ColorPicker4(label, col4, flags | ImGuiColorEditFlags_NoAlpha))\r\n        return false;\r\n    col[0] = col4[0]; col[1] = col4[1]; col[2] = col4[2];\r\n    return true;\r\n}\r\n\r\n// Helper for ColorPicker4()\r\nstatic void RenderArrowsForVerticalBar(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, float bar_w, float alpha)\r\n{\r\n    ImU32 alpha8 = IM_F32_TO_INT8_SAT(alpha);\r\n    ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + half_sz.x + 1,         pos.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Right, IM_COL32(0,0,0,alpha8));\r\n    ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + half_sz.x,             pos.y), half_sz,                              ImGuiDir_Right, IM_COL32(255,255,255,alpha8));\r\n    ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + bar_w - half_sz.x - 1, pos.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Left,  IM_COL32(0,0,0,alpha8));\r\n    ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + bar_w - half_sz.x,     pos.y), half_sz,                              ImGuiDir_Left,  IM_COL32(255,255,255,alpha8));\r\n}\r\n\r\n// Note: ColorPicker4() only accesses 3 floats if ImGuiColorEditFlags_NoAlpha flag is set.\r\n// (In C++ the 'float col[4]' notation for a function argument is equivalent to 'float* col', we only specify a size to facilitate understanding of the code.)\r\n// FIXME: we adjust the big color square height based on item width, which may cause a flickering feedback loop (if automatic height makes a vertical scrollbar appears, affecting automatic width..)\r\n// FIXME: this is trying to be aware of style.Alpha but not fully correct. Also, the color wheel will have overlapping glitches with (style.Alpha < 1.0)\r\nbool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags flags, const float* ref_col)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return false;\r\n\r\n    ImDrawList* draw_list = window->DrawList;\r\n    ImGuiStyle& style = g.Style;\r\n    ImGuiIO& io = g.IO;\r\n\r\n    const float width = CalcItemWidth();\r\n    g.NextItemData.ClearFlags();\r\n\r\n    PushID(label);\r\n    BeginGroup();\r\n\r\n    if (!(flags & ImGuiColorEditFlags_NoSidePreview))\r\n        flags |= ImGuiColorEditFlags_NoSmallPreview;\r\n\r\n    // Context menu: display and store options.\r\n    if (!(flags & ImGuiColorEditFlags_NoOptions))\r\n        ColorPickerOptionsPopup(col, flags);\r\n\r\n    // Read stored options\r\n    if (!(flags & ImGuiColorEditFlags_PickerMask_))\r\n        flags |= ((g.ColorEditOptions & ImGuiColorEditFlags_PickerMask_) ? g.ColorEditOptions : ImGuiColorEditFlags_DefaultOptions_) & ImGuiColorEditFlags_PickerMask_;\r\n    if (!(flags & ImGuiColorEditFlags_InputMask_))\r\n        flags |= ((g.ColorEditOptions & ImGuiColorEditFlags_InputMask_) ? g.ColorEditOptions : ImGuiColorEditFlags_DefaultOptions_) & ImGuiColorEditFlags_InputMask_;\r\n    IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_PickerMask_)); // Check that only 1 is selected\r\n    IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_InputMask_));  // Check that only 1 is selected\r\n    if (!(flags & ImGuiColorEditFlags_NoOptions))\r\n        flags |= (g.ColorEditOptions & ImGuiColorEditFlags_AlphaBar);\r\n\r\n    // Setup\r\n    int components = (flags & ImGuiColorEditFlags_NoAlpha) ? 3 : 4;\r\n    bool alpha_bar = (flags & ImGuiColorEditFlags_AlphaBar) && !(flags & ImGuiColorEditFlags_NoAlpha);\r\n    ImVec2 picker_pos = window->DC.CursorPos;\r\n    float square_sz = GetFrameHeight();\r\n    float bars_width = square_sz; // Arbitrary smallish width of Hue/Alpha picking bars\r\n    float sv_picker_size = ImMax(bars_width * 1, width - (alpha_bar ? 2 : 1) * (bars_width + style.ItemInnerSpacing.x)); // Saturation/Value picking box\r\n    float bar0_pos_x = picker_pos.x + sv_picker_size + style.ItemInnerSpacing.x;\r\n    float bar1_pos_x = bar0_pos_x + bars_width + style.ItemInnerSpacing.x;\r\n    float bars_triangles_half_sz = IM_FLOOR(bars_width * 0.20f);\r\n\r\n    float backup_initial_col[4];\r\n    memcpy(backup_initial_col, col, components * sizeof(float));\r\n\r\n    float wheel_thickness = sv_picker_size * 0.08f;\r\n    float wheel_r_outer = sv_picker_size * 0.50f;\r\n    float wheel_r_inner = wheel_r_outer - wheel_thickness;\r\n    ImVec2 wheel_center(picker_pos.x + (sv_picker_size + bars_width)*0.5f, picker_pos.y + sv_picker_size * 0.5f);\r\n\r\n    // Note: the triangle is displayed rotated with triangle_pa pointing to Hue, but most coordinates stays unrotated for logic.\r\n    float triangle_r = wheel_r_inner - (int)(sv_picker_size * 0.027f);\r\n    ImVec2 triangle_pa = ImVec2(triangle_r, 0.0f); // Hue point.\r\n    ImVec2 triangle_pb = ImVec2(triangle_r * -0.5f, triangle_r * -0.866025f); // Black point.\r\n    ImVec2 triangle_pc = ImVec2(triangle_r * -0.5f, triangle_r * +0.866025f); // White point.\r\n\r\n    float H = col[0], S = col[1], V = col[2];\r\n    float R = col[0], G = col[1], B = col[2];\r\n    if (flags & ImGuiColorEditFlags_InputRGB)\r\n    {\r\n        // Hue is lost when converting from greyscale rgb (saturation=0). Restore it.\r\n        ColorConvertRGBtoHSV(R, G, B, H, S, V);\r\n        ColorEditRestoreHS(col, &H, &S, &V);\r\n    }\r\n    else if (flags & ImGuiColorEditFlags_InputHSV)\r\n    {\r\n        ColorConvertHSVtoRGB(H, S, V, R, G, B);\r\n    }\r\n\r\n    bool value_changed = false, value_changed_h = false, value_changed_sv = false;\r\n\r\n    PushItemFlag(ImGuiItemFlags_NoNav, true);\r\n    if (flags & ImGuiColorEditFlags_PickerHueWheel)\r\n    {\r\n        // Hue wheel + SV triangle logic\r\n        InvisibleButton(\"hsv\", ImVec2(sv_picker_size + style.ItemInnerSpacing.x + bars_width, sv_picker_size));\r\n        if (IsItemActive())\r\n        {\r\n            ImVec2 initial_off = g.IO.MouseClickedPos[0] - wheel_center;\r\n            ImVec2 current_off = g.IO.MousePos - wheel_center;\r\n            float initial_dist2 = ImLengthSqr(initial_off);\r\n            if (initial_dist2 >= (wheel_r_inner - 1) * (wheel_r_inner - 1) && initial_dist2 <= (wheel_r_outer + 1) * (wheel_r_outer + 1))\r\n            {\r\n                // Interactive with Hue wheel\r\n                H = ImAtan2(current_off.y, current_off.x) / IM_PI * 0.5f;\r\n                if (H < 0.0f)\r\n                    H += 1.0f;\r\n                value_changed = value_changed_h = true;\r\n            }\r\n            float cos_hue_angle = ImCos(-H * 2.0f * IM_PI);\r\n            float sin_hue_angle = ImSin(-H * 2.0f * IM_PI);\r\n            if (ImTriangleContainsPoint(triangle_pa, triangle_pb, triangle_pc, ImRotate(initial_off, cos_hue_angle, sin_hue_angle)))\r\n            {\r\n                // Interacting with SV triangle\r\n                ImVec2 current_off_unrotated = ImRotate(current_off, cos_hue_angle, sin_hue_angle);\r\n                if (!ImTriangleContainsPoint(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated))\r\n                    current_off_unrotated = ImTriangleClosestPoint(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated);\r\n                float uu, vv, ww;\r\n                ImTriangleBarycentricCoords(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated, uu, vv, ww);\r\n                V = ImClamp(1.0f - vv, 0.0001f, 1.0f);\r\n                S = ImClamp(uu / V, 0.0001f, 1.0f);\r\n                value_changed = value_changed_sv = true;\r\n            }\r\n        }\r\n        if (!(flags & ImGuiColorEditFlags_NoOptions))\r\n            OpenPopupOnItemClick(\"context\", ImGuiPopupFlags_MouseButtonRight);\r\n    }\r\n    else if (flags & ImGuiColorEditFlags_PickerHueBar)\r\n    {\r\n        // SV rectangle logic\r\n        InvisibleButton(\"sv\", ImVec2(sv_picker_size, sv_picker_size));\r\n        if (IsItemActive())\r\n        {\r\n            S = ImSaturate((io.MousePos.x - picker_pos.x) / (sv_picker_size - 1));\r\n            V = 1.0f - ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size - 1));\r\n\r\n            // Greatly reduces hue jitter and reset to 0 when hue == 255 and color is rapidly modified using SV square.\r\n            if (g.ColorEditLastColor == ColorConvertFloat4ToU32(ImVec4(col[0], col[1], col[2], 0)))\r\n                H = g.ColorEditLastHue;\r\n            value_changed = value_changed_sv = true;\r\n        }\r\n        if (!(flags & ImGuiColorEditFlags_NoOptions))\r\n            OpenPopupOnItemClick(\"context\", ImGuiPopupFlags_MouseButtonRight);\r\n\r\n        // Hue bar logic\r\n        SetCursorScreenPos(ImVec2(bar0_pos_x, picker_pos.y));\r\n        InvisibleButton(\"hue\", ImVec2(bars_width, sv_picker_size));\r\n        if (IsItemActive())\r\n        {\r\n            H = ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size - 1));\r\n            value_changed = value_changed_h = true;\r\n        }\r\n    }\r\n\r\n    // Alpha bar logic\r\n    if (alpha_bar)\r\n    {\r\n        SetCursorScreenPos(ImVec2(bar1_pos_x, picker_pos.y));\r\n        InvisibleButton(\"alpha\", ImVec2(bars_width, sv_picker_size));\r\n        if (IsItemActive())\r\n        {\r\n            col[3] = 1.0f - ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size - 1));\r\n            value_changed = true;\r\n        }\r\n    }\r\n    PopItemFlag(); // ImGuiItemFlags_NoNav\r\n\r\n    if (!(flags & ImGuiColorEditFlags_NoSidePreview))\r\n    {\r\n        SameLine(0, style.ItemInnerSpacing.x);\r\n        BeginGroup();\r\n    }\r\n\r\n    if (!(flags & ImGuiColorEditFlags_NoLabel))\r\n    {\r\n        const char* label_display_end = FindRenderedTextEnd(label);\r\n        if (label != label_display_end)\r\n        {\r\n            if ((flags & ImGuiColorEditFlags_NoSidePreview))\r\n                SameLine(0, style.ItemInnerSpacing.x);\r\n            TextEx(label, label_display_end);\r\n        }\r\n    }\r\n\r\n    if (!(flags & ImGuiColorEditFlags_NoSidePreview))\r\n    {\r\n        PushItemFlag(ImGuiItemFlags_NoNavDefaultFocus, true);\r\n        ImVec4 col_v4(col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]);\r\n        if ((flags & ImGuiColorEditFlags_NoLabel))\r\n            Text(\"Current\");\r\n\r\n        ImGuiColorEditFlags sub_flags_to_forward = ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf | ImGuiColorEditFlags_NoTooltip;\r\n        ColorButton(\"##current\", col_v4, (flags & sub_flags_to_forward), ImVec2(square_sz * 3, square_sz * 2));\r\n        if (ref_col != NULL)\r\n        {\r\n            Text(\"Original\");\r\n            ImVec4 ref_col_v4(ref_col[0], ref_col[1], ref_col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : ref_col[3]);\r\n            if (ColorButton(\"##original\", ref_col_v4, (flags & sub_flags_to_forward), ImVec2(square_sz * 3, square_sz * 2)))\r\n            {\r\n                memcpy(col, ref_col, components * sizeof(float));\r\n                value_changed = true;\r\n            }\r\n        }\r\n        PopItemFlag();\r\n        EndGroup();\r\n    }\r\n\r\n    // Convert back color to RGB\r\n    if (value_changed_h || value_changed_sv)\r\n    {\r\n        if (flags & ImGuiColorEditFlags_InputRGB)\r\n        {\r\n            ColorConvertHSVtoRGB(H, S, V, col[0], col[1], col[2]);\r\n            g.ColorEditLastHue = H;\r\n            g.ColorEditLastSat = S;\r\n            g.ColorEditLastColor = ColorConvertFloat4ToU32(ImVec4(col[0], col[1], col[2], 0));\r\n        }\r\n        else if (flags & ImGuiColorEditFlags_InputHSV)\r\n        {\r\n            col[0] = H;\r\n            col[1] = S;\r\n            col[2] = V;\r\n        }\r\n    }\r\n\r\n    // R,G,B and H,S,V slider color editor\r\n    bool value_changed_fix_hue_wrap = false;\r\n    if ((flags & ImGuiColorEditFlags_NoInputs) == 0)\r\n    {\r\n        PushItemWidth((alpha_bar ? bar1_pos_x : bar0_pos_x) + bars_width - picker_pos.x);\r\n        ImGuiColorEditFlags sub_flags_to_forward = ImGuiColorEditFlags_DataTypeMask_ | ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoOptions | ImGuiColorEditFlags_NoSmallPreview | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf;\r\n        ImGuiColorEditFlags sub_flags = (flags & sub_flags_to_forward) | ImGuiColorEditFlags_NoPicker;\r\n        if (flags & ImGuiColorEditFlags_DisplayRGB || (flags & ImGuiColorEditFlags_DisplayMask_) == 0)\r\n            if (ColorEdit4(\"##rgb\", col, sub_flags | ImGuiColorEditFlags_DisplayRGB))\r\n            {\r\n                // FIXME: Hackily differentiating using the DragInt (ActiveId != 0 && !ActiveIdAllowOverlap) vs. using the InputText or DropTarget.\r\n                // For the later we don't want to run the hue-wrap canceling code. If you are well versed in HSV picker please provide your input! (See #2050)\r\n                value_changed_fix_hue_wrap = (g.ActiveId != 0 && !g.ActiveIdAllowOverlap);\r\n                value_changed = true;\r\n            }\r\n        if (flags & ImGuiColorEditFlags_DisplayHSV || (flags & ImGuiColorEditFlags_DisplayMask_) == 0)\r\n            value_changed |= ColorEdit4(\"##hsv\", col, sub_flags | ImGuiColorEditFlags_DisplayHSV);\r\n        if (flags & ImGuiColorEditFlags_DisplayHex || (flags & ImGuiColorEditFlags_DisplayMask_) == 0)\r\n            value_changed |= ColorEdit4(\"##hex\", col, sub_flags | ImGuiColorEditFlags_DisplayHex);\r\n        PopItemWidth();\r\n    }\r\n\r\n    // Try to cancel hue wrap (after ColorEdit4 call), if any\r\n    if (value_changed_fix_hue_wrap && (flags & ImGuiColorEditFlags_InputRGB))\r\n    {\r\n        float new_H, new_S, new_V;\r\n        ColorConvertRGBtoHSV(col[0], col[1], col[2], new_H, new_S, new_V);\r\n        if (new_H <= 0 && H > 0)\r\n        {\r\n            if (new_V <= 0 && V != new_V)\r\n                ColorConvertHSVtoRGB(H, S, new_V <= 0 ? V * 0.5f : new_V, col[0], col[1], col[2]);\r\n            else if (new_S <= 0)\r\n                ColorConvertHSVtoRGB(H, new_S <= 0 ? S * 0.5f : new_S, new_V, col[0], col[1], col[2]);\r\n        }\r\n    }\r\n\r\n    if (value_changed)\r\n    {\r\n        if (flags & ImGuiColorEditFlags_InputRGB)\r\n        {\r\n            R = col[0];\r\n            G = col[1];\r\n            B = col[2];\r\n            ColorConvertRGBtoHSV(R, G, B, H, S, V);\r\n            ColorEditRestoreHS(col, &H, &S, &V);   // Fix local Hue as display below will use it immediately.\r\n        }\r\n        else if (flags & ImGuiColorEditFlags_InputHSV)\r\n        {\r\n            H = col[0];\r\n            S = col[1];\r\n            V = col[2];\r\n            ColorConvertHSVtoRGB(H, S, V, R, G, B);\r\n        }\r\n    }\r\n\r\n    const int style_alpha8 = IM_F32_TO_INT8_SAT(style.Alpha);\r\n    const ImU32 col_black = IM_COL32(0,0,0,style_alpha8);\r\n    const ImU32 col_white = IM_COL32(255,255,255,style_alpha8);\r\n    const ImU32 col_midgrey = IM_COL32(128,128,128,style_alpha8);\r\n    const ImU32 col_hues[6 + 1] = { IM_COL32(255,0,0,style_alpha8), IM_COL32(255,255,0,style_alpha8), IM_COL32(0,255,0,style_alpha8), IM_COL32(0,255,255,style_alpha8), IM_COL32(0,0,255,style_alpha8), IM_COL32(255,0,255,style_alpha8), IM_COL32(255,0,0,style_alpha8) };\r\n\r\n    ImVec4 hue_color_f(1, 1, 1, style.Alpha); ColorConvertHSVtoRGB(H, 1, 1, hue_color_f.x, hue_color_f.y, hue_color_f.z);\r\n    ImU32 hue_color32 = ColorConvertFloat4ToU32(hue_color_f);\r\n    ImU32 user_col32_striped_of_alpha = ColorConvertFloat4ToU32(ImVec4(R, G, B, style.Alpha)); // Important: this is still including the main rendering/style alpha!!\r\n\r\n    ImVec2 sv_cursor_pos;\r\n\r\n    if (flags & ImGuiColorEditFlags_PickerHueWheel)\r\n    {\r\n        // Render Hue Wheel\r\n        const float aeps = 0.5f / wheel_r_outer; // Half a pixel arc length in radians (2pi cancels out).\r\n        const int segment_per_arc = ImMax(4, (int)wheel_r_outer / 12);\r\n        for (int n = 0; n < 6; n++)\r\n        {\r\n            const float a0 = (n)     /6.0f * 2.0f * IM_PI - aeps;\r\n            const float a1 = (n+1.0f)/6.0f * 2.0f * IM_PI + aeps;\r\n            const int vert_start_idx = draw_list->VtxBuffer.Size;\r\n            draw_list->PathArcTo(wheel_center, (wheel_r_inner + wheel_r_outer)*0.5f, a0, a1, segment_per_arc);\r\n            draw_list->PathStroke(col_white, 0, wheel_thickness);\r\n            const int vert_end_idx = draw_list->VtxBuffer.Size;\r\n\r\n            // Paint colors over existing vertices\r\n            ImVec2 gradient_p0(wheel_center.x + ImCos(a0) * wheel_r_inner, wheel_center.y + ImSin(a0) * wheel_r_inner);\r\n            ImVec2 gradient_p1(wheel_center.x + ImCos(a1) * wheel_r_inner, wheel_center.y + ImSin(a1) * wheel_r_inner);\r\n            ShadeVertsLinearColorGradientKeepAlpha(draw_list, vert_start_idx, vert_end_idx, gradient_p0, gradient_p1, col_hues[n], col_hues[n + 1]);\r\n        }\r\n\r\n        // Render Cursor + preview on Hue Wheel\r\n        float cos_hue_angle = ImCos(H * 2.0f * IM_PI);\r\n        float sin_hue_angle = ImSin(H * 2.0f * IM_PI);\r\n        ImVec2 hue_cursor_pos(wheel_center.x + cos_hue_angle * (wheel_r_inner + wheel_r_outer) * 0.5f, wheel_center.y + sin_hue_angle * (wheel_r_inner + wheel_r_outer) * 0.5f);\r\n        float hue_cursor_rad = value_changed_h ? wheel_thickness * 0.65f : wheel_thickness * 0.55f;\r\n        int hue_cursor_segments = ImClamp((int)(hue_cursor_rad / 1.4f), 9, 32);\r\n        draw_list->AddCircleFilled(hue_cursor_pos, hue_cursor_rad, hue_color32, hue_cursor_segments);\r\n        draw_list->AddCircle(hue_cursor_pos, hue_cursor_rad + 1, col_midgrey, hue_cursor_segments);\r\n        draw_list->AddCircle(hue_cursor_pos, hue_cursor_rad, col_white, hue_cursor_segments);\r\n\r\n        // Render SV triangle (rotated according to hue)\r\n        ImVec2 tra = wheel_center + ImRotate(triangle_pa, cos_hue_angle, sin_hue_angle);\r\n        ImVec2 trb = wheel_center + ImRotate(triangle_pb, cos_hue_angle, sin_hue_angle);\r\n        ImVec2 trc = wheel_center + ImRotate(triangle_pc, cos_hue_angle, sin_hue_angle);\r\n        ImVec2 uv_white = GetFontTexUvWhitePixel();\r\n        draw_list->PrimReserve(6, 6);\r\n        draw_list->PrimVtx(tra, uv_white, hue_color32);\r\n        draw_list->PrimVtx(trb, uv_white, hue_color32);\r\n        draw_list->PrimVtx(trc, uv_white, col_white);\r\n        draw_list->PrimVtx(tra, uv_white, 0);\r\n        draw_list->PrimVtx(trb, uv_white, col_black);\r\n        draw_list->PrimVtx(trc, uv_white, 0);\r\n        draw_list->AddTriangle(tra, trb, trc, col_midgrey, 1.5f);\r\n        sv_cursor_pos = ImLerp(ImLerp(trc, tra, ImSaturate(S)), trb, ImSaturate(1 - V));\r\n    }\r\n    else if (flags & ImGuiColorEditFlags_PickerHueBar)\r\n    {\r\n        // Render SV Square\r\n        draw_list->AddRectFilledMultiColor(picker_pos, picker_pos + ImVec2(sv_picker_size, sv_picker_size), col_white, hue_color32, hue_color32, col_white);\r\n        draw_list->AddRectFilledMultiColor(picker_pos, picker_pos + ImVec2(sv_picker_size, sv_picker_size), 0, 0, col_black, col_black);\r\n        RenderFrameBorder(picker_pos, picker_pos + ImVec2(sv_picker_size, sv_picker_size), 0.0f);\r\n        sv_cursor_pos.x = ImClamp(IM_ROUND(picker_pos.x + ImSaturate(S)     * sv_picker_size), picker_pos.x + 2, picker_pos.x + sv_picker_size - 2); // Sneakily prevent the circle to stick out too much\r\n        sv_cursor_pos.y = ImClamp(IM_ROUND(picker_pos.y + ImSaturate(1 - V) * sv_picker_size), picker_pos.y + 2, picker_pos.y + sv_picker_size - 2);\r\n\r\n        // Render Hue Bar\r\n        for (int i = 0; i < 6; ++i)\r\n            draw_list->AddRectFilledMultiColor(ImVec2(bar0_pos_x, picker_pos.y + i * (sv_picker_size / 6)), ImVec2(bar0_pos_x + bars_width, picker_pos.y + (i + 1) * (sv_picker_size / 6)), col_hues[i], col_hues[i], col_hues[i + 1], col_hues[i + 1]);\r\n        float bar0_line_y = IM_ROUND(picker_pos.y + H * sv_picker_size);\r\n        RenderFrameBorder(ImVec2(bar0_pos_x, picker_pos.y), ImVec2(bar0_pos_x + bars_width, picker_pos.y + sv_picker_size), 0.0f);\r\n        RenderArrowsForVerticalBar(draw_list, ImVec2(bar0_pos_x - 1, bar0_line_y), ImVec2(bars_triangles_half_sz + 1, bars_triangles_half_sz), bars_width + 2.0f, style.Alpha);\r\n    }\r\n\r\n    // Render cursor/preview circle (clamp S/V within 0..1 range because floating points colors may lead HSV values to be out of range)\r\n    float sv_cursor_rad = value_changed_sv ? 10.0f : 6.0f;\r\n    draw_list->AddCircleFilled(sv_cursor_pos, sv_cursor_rad, user_col32_striped_of_alpha, 12);\r\n    draw_list->AddCircle(sv_cursor_pos, sv_cursor_rad + 1, col_midgrey, 12);\r\n    draw_list->AddCircle(sv_cursor_pos, sv_cursor_rad, col_white, 12);\r\n\r\n    // Render alpha bar\r\n    if (alpha_bar)\r\n    {\r\n        float alpha = ImSaturate(col[3]);\r\n        ImRect bar1_bb(bar1_pos_x, picker_pos.y, bar1_pos_x + bars_width, picker_pos.y + sv_picker_size);\r\n        RenderColorRectWithAlphaCheckerboard(draw_list, bar1_bb.Min, bar1_bb.Max, 0, bar1_bb.GetWidth() / 2.0f, ImVec2(0.0f, 0.0f));\r\n        draw_list->AddRectFilledMultiColor(bar1_bb.Min, bar1_bb.Max, user_col32_striped_of_alpha, user_col32_striped_of_alpha, user_col32_striped_of_alpha & ~IM_COL32_A_MASK, user_col32_striped_of_alpha & ~IM_COL32_A_MASK);\r\n        float bar1_line_y = IM_ROUND(picker_pos.y + (1.0f - alpha) * sv_picker_size);\r\n        RenderFrameBorder(bar1_bb.Min, bar1_bb.Max, 0.0f);\r\n        RenderArrowsForVerticalBar(draw_list, ImVec2(bar1_pos_x - 1, bar1_line_y), ImVec2(bars_triangles_half_sz + 1, bars_triangles_half_sz), bars_width + 2.0f, style.Alpha);\r\n    }\r\n\r\n    EndGroup();\r\n\r\n    if (value_changed && memcmp(backup_initial_col, col, components * sizeof(float)) == 0)\r\n        value_changed = false;\r\n    if (value_changed)\r\n        MarkItemEdited(g.LastItemData.ID);\r\n\r\n    PopID();\r\n\r\n    return value_changed;\r\n}\r\n\r\n// A little color square. Return true when clicked.\r\n// FIXME: May want to display/ignore the alpha component in the color display? Yet show it in the tooltip.\r\n// 'desc_id' is not called 'label' because we don't display it next to the button, but only in the tooltip.\r\n// Note that 'col' may be encoded in HSV if ImGuiColorEditFlags_InputHSV is set.\r\nbool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags, ImVec2 size)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return false;\r\n\r\n    ImGuiContext& g = *GImGui;\r\n    const ImGuiID id = window->GetID(desc_id);\r\n    float default_size = GetFrameHeight();\r\n    if (size.x == 0.0f)\r\n        size.x = default_size;\r\n    if (size.y == 0.0f)\r\n        size.y = default_size;\r\n    const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);\r\n    ItemSize(bb, (size.y >= default_size) ? g.Style.FramePadding.y : 0.0f);\r\n    if (!ItemAdd(bb, id))\r\n        return false;\r\n\r\n    bool hovered, held;\r\n    bool pressed = ButtonBehavior(bb, id, &hovered, &held);\r\n\r\n    if (flags & ImGuiColorEditFlags_NoAlpha)\r\n        flags &= ~(ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf);\r\n\r\n    ImVec4 col_rgb = col;\r\n    if (flags & ImGuiColorEditFlags_InputHSV)\r\n        ColorConvertHSVtoRGB(col_rgb.x, col_rgb.y, col_rgb.z, col_rgb.x, col_rgb.y, col_rgb.z);\r\n\r\n    ImVec4 col_rgb_without_alpha(col_rgb.x, col_rgb.y, col_rgb.z, 1.0f);\r\n    float grid_step = ImMin(size.x, size.y) / 2.99f;\r\n    float rounding = ImMin(g.Style.FrameRounding, grid_step * 0.5f);\r\n    ImRect bb_inner = bb;\r\n    float off = 0.0f;\r\n    if ((flags & ImGuiColorEditFlags_NoBorder) == 0)\r\n    {\r\n        off = -0.75f; // The border (using Col_FrameBg) tends to look off when color is near-opaque and rounding is enabled. This offset seemed like a good middle ground to reduce those artifacts.\r\n        bb_inner.Expand(off);\r\n    }\r\n    if ((flags & ImGuiColorEditFlags_AlphaPreviewHalf) && col_rgb.w < 1.0f)\r\n    {\r\n        float mid_x = IM_ROUND((bb_inner.Min.x + bb_inner.Max.x) * 0.5f);\r\n        RenderColorRectWithAlphaCheckerboard(window->DrawList, ImVec2(bb_inner.Min.x + grid_step, bb_inner.Min.y), bb_inner.Max, GetColorU32(col_rgb), grid_step, ImVec2(-grid_step + off, off), rounding, ImDrawFlags_RoundCornersRight);\r\n        window->DrawList->AddRectFilled(bb_inner.Min, ImVec2(mid_x, bb_inner.Max.y), GetColorU32(col_rgb_without_alpha), rounding, ImDrawFlags_RoundCornersLeft);\r\n    }\r\n    else\r\n    {\r\n        // Because GetColorU32() multiplies by the global style Alpha and we don't want to display a checkerboard if the source code had no alpha\r\n        ImVec4 col_source = (flags & ImGuiColorEditFlags_AlphaPreview) ? col_rgb : col_rgb_without_alpha;\r\n        if (col_source.w < 1.0f)\r\n            RenderColorRectWithAlphaCheckerboard(window->DrawList, bb_inner.Min, bb_inner.Max, GetColorU32(col_source), grid_step, ImVec2(off, off), rounding);\r\n        else\r\n            window->DrawList->AddRectFilled(bb_inner.Min, bb_inner.Max, GetColorU32(col_source), rounding);\r\n    }\r\n    RenderNavHighlight(bb, id);\r\n    if ((flags & ImGuiColorEditFlags_NoBorder) == 0)\r\n    {\r\n        if (g.Style.FrameBorderSize > 0.0f)\r\n            RenderFrameBorder(bb.Min, bb.Max, rounding);\r\n        else\r\n            window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), rounding); // Color button are often in need of some sort of border\r\n    }\r\n\r\n    // Drag and Drop Source\r\n    // NB: The ActiveId test is merely an optional micro-optimization, BeginDragDropSource() does the same test.\r\n    if (g.ActiveId == id && !(flags & ImGuiColorEditFlags_NoDragDrop) && BeginDragDropSource())\r\n    {\r\n        if (flags & ImGuiColorEditFlags_NoAlpha)\r\n            SetDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F, &col_rgb, sizeof(float) * 3, ImGuiCond_Once);\r\n        else\r\n            SetDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F, &col_rgb, sizeof(float) * 4, ImGuiCond_Once);\r\n        ColorButton(desc_id, col, flags);\r\n        SameLine();\r\n        TextEx(\"Color\");\r\n        EndDragDropSource();\r\n    }\r\n\r\n    // Tooltip\r\n    if (!(flags & ImGuiColorEditFlags_NoTooltip) && hovered)\r\n        ColorTooltip(desc_id, &col.x, flags & (ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf));\r\n\r\n    return pressed;\r\n}\r\n\r\n// Initialize/override default color options\r\nvoid ImGui::SetColorEditOptions(ImGuiColorEditFlags flags)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    if ((flags & ImGuiColorEditFlags_DisplayMask_) == 0)\r\n        flags |= ImGuiColorEditFlags_DefaultOptions_ & ImGuiColorEditFlags_DisplayMask_;\r\n    if ((flags & ImGuiColorEditFlags_DataTypeMask_) == 0)\r\n        flags |= ImGuiColorEditFlags_DefaultOptions_ & ImGuiColorEditFlags_DataTypeMask_;\r\n    if ((flags & ImGuiColorEditFlags_PickerMask_) == 0)\r\n        flags |= ImGuiColorEditFlags_DefaultOptions_ & ImGuiColorEditFlags_PickerMask_;\r\n    if ((flags & ImGuiColorEditFlags_InputMask_) == 0)\r\n        flags |= ImGuiColorEditFlags_DefaultOptions_ & ImGuiColorEditFlags_InputMask_;\r\n    IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_DisplayMask_));    // Check only 1 option is selected\r\n    IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_DataTypeMask_));   // Check only 1 option is selected\r\n    IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_PickerMask_));     // Check only 1 option is selected\r\n    IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_InputMask_));      // Check only 1 option is selected\r\n    g.ColorEditOptions = flags;\r\n}\r\n\r\n// Note: only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set.\r\nvoid ImGui::ColorTooltip(const char* text, const float* col, ImGuiColorEditFlags flags)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n\r\n    BeginTooltipEx(ImGuiTooltipFlags_OverridePreviousTooltip, ImGuiWindowFlags_None);\r\n    const char* text_end = text ? FindRenderedTextEnd(text, NULL) : text;\r\n    if (text_end > text)\r\n    {\r\n        TextEx(text, text_end);\r\n        Separator();\r\n    }\r\n\r\n    ImVec2 sz(g.FontSize * 3 + g.Style.FramePadding.y * 2, g.FontSize * 3 + g.Style.FramePadding.y * 2);\r\n    ImVec4 cf(col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]);\r\n    int cr = IM_F32_TO_INT8_SAT(col[0]), cg = IM_F32_TO_INT8_SAT(col[1]), cb = IM_F32_TO_INT8_SAT(col[2]), ca = (flags & ImGuiColorEditFlags_NoAlpha) ? 255 : IM_F32_TO_INT8_SAT(col[3]);\r\n    ColorButton(\"##preview\", cf, (flags & (ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf)) | ImGuiColorEditFlags_NoTooltip, sz);\r\n    SameLine();\r\n    if ((flags & ImGuiColorEditFlags_InputRGB) || !(flags & ImGuiColorEditFlags_InputMask_))\r\n    {\r\n        if (flags & ImGuiColorEditFlags_NoAlpha)\r\n            Text(\"#%02X%02X%02X\\nR: %d, G: %d, B: %d\\n(%.3f, %.3f, %.3f)\", cr, cg, cb, cr, cg, cb, col[0], col[1], col[2]);\r\n        else\r\n            Text(\"#%02X%02X%02X%02X\\nR:%d, G:%d, B:%d, A:%d\\n(%.3f, %.3f, %.3f, %.3f)\", cr, cg, cb, ca, cr, cg, cb, ca, col[0], col[1], col[2], col[3]);\r\n    }\r\n    else if (flags & ImGuiColorEditFlags_InputHSV)\r\n    {\r\n        if (flags & ImGuiColorEditFlags_NoAlpha)\r\n            Text(\"H: %.3f, S: %.3f, V: %.3f\", col[0], col[1], col[2]);\r\n        else\r\n            Text(\"H: %.3f, S: %.3f, V: %.3f, A: %.3f\", col[0], col[1], col[2], col[3]);\r\n    }\r\n    EndTooltip();\r\n}\r\n\r\nvoid ImGui::ColorEditOptionsPopup(const float* col, ImGuiColorEditFlags flags)\r\n{\r\n    bool allow_opt_inputs = !(flags & ImGuiColorEditFlags_DisplayMask_);\r\n    bool allow_opt_datatype = !(flags & ImGuiColorEditFlags_DataTypeMask_);\r\n    if ((!allow_opt_inputs && !allow_opt_datatype) || !BeginPopup(\"context\"))\r\n        return;\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiColorEditFlags opts = g.ColorEditOptions;\r\n    if (allow_opt_inputs)\r\n    {\r\n        if (RadioButton(\"RGB\", (opts & ImGuiColorEditFlags_DisplayRGB) != 0)) opts = (opts & ~ImGuiColorEditFlags_DisplayMask_) | ImGuiColorEditFlags_DisplayRGB;\r\n        if (RadioButton(\"HSV\", (opts & ImGuiColorEditFlags_DisplayHSV) != 0)) opts = (opts & ~ImGuiColorEditFlags_DisplayMask_) | ImGuiColorEditFlags_DisplayHSV;\r\n        if (RadioButton(\"Hex\", (opts & ImGuiColorEditFlags_DisplayHex) != 0)) opts = (opts & ~ImGuiColorEditFlags_DisplayMask_) | ImGuiColorEditFlags_DisplayHex;\r\n    }\r\n    if (allow_opt_datatype)\r\n    {\r\n        if (allow_opt_inputs) Separator();\r\n        if (RadioButton(\"0..255\",     (opts & ImGuiColorEditFlags_Uint8) != 0)) opts = (opts & ~ImGuiColorEditFlags_DataTypeMask_) | ImGuiColorEditFlags_Uint8;\r\n        if (RadioButton(\"0.00..1.00\", (opts & ImGuiColorEditFlags_Float) != 0)) opts = (opts & ~ImGuiColorEditFlags_DataTypeMask_) | ImGuiColorEditFlags_Float;\r\n    }\r\n\r\n    if (allow_opt_inputs || allow_opt_datatype)\r\n        Separator();\r\n    if (Button(\"Copy as..\", ImVec2(-1, 0)))\r\n        OpenPopup(\"Copy\");\r\n    if (BeginPopup(\"Copy\"))\r\n    {\r\n        int cr = IM_F32_TO_INT8_SAT(col[0]), cg = IM_F32_TO_INT8_SAT(col[1]), cb = IM_F32_TO_INT8_SAT(col[2]), ca = (flags & ImGuiColorEditFlags_NoAlpha) ? 255 : IM_F32_TO_INT8_SAT(col[3]);\r\n        char buf[64];\r\n        ImFormatString(buf, IM_ARRAYSIZE(buf), \"(%.3ff, %.3ff, %.3ff, %.3ff)\", col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]);\r\n        if (Selectable(buf))\r\n            SetClipboardText(buf);\r\n        ImFormatString(buf, IM_ARRAYSIZE(buf), \"(%d,%d,%d,%d)\", cr, cg, cb, ca);\r\n        if (Selectable(buf))\r\n            SetClipboardText(buf);\r\n        ImFormatString(buf, IM_ARRAYSIZE(buf), \"#%02X%02X%02X\", cr, cg, cb);\r\n        if (Selectable(buf))\r\n            SetClipboardText(buf);\r\n        if (!(flags & ImGuiColorEditFlags_NoAlpha))\r\n        {\r\n            ImFormatString(buf, IM_ARRAYSIZE(buf), \"#%02X%02X%02X%02X\", cr, cg, cb, ca);\r\n            if (Selectable(buf))\r\n                SetClipboardText(buf);\r\n        }\r\n        EndPopup();\r\n    }\r\n\r\n    g.ColorEditOptions = opts;\r\n    EndPopup();\r\n}\r\n\r\nvoid ImGui::ColorPickerOptionsPopup(const float* ref_col, ImGuiColorEditFlags flags)\r\n{\r\n    bool allow_opt_picker = !(flags & ImGuiColorEditFlags_PickerMask_);\r\n    bool allow_opt_alpha_bar = !(flags & ImGuiColorEditFlags_NoAlpha) && !(flags & ImGuiColorEditFlags_AlphaBar);\r\n    if ((!allow_opt_picker && !allow_opt_alpha_bar) || !BeginPopup(\"context\"))\r\n        return;\r\n    ImGuiContext& g = *GImGui;\r\n    if (allow_opt_picker)\r\n    {\r\n        ImVec2 picker_size(g.FontSize * 8, ImMax(g.FontSize * 8 - (GetFrameHeight() + g.Style.ItemInnerSpacing.x), 1.0f)); // FIXME: Picker size copied from main picker function\r\n        PushItemWidth(picker_size.x);\r\n        for (int picker_type = 0; picker_type < 2; picker_type++)\r\n        {\r\n            // Draw small/thumbnail version of each picker type (over an invisible button for selection)\r\n            if (picker_type > 0) Separator();\r\n            PushID(picker_type);\r\n            ImGuiColorEditFlags picker_flags = ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoOptions | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_NoSidePreview | (flags & ImGuiColorEditFlags_NoAlpha);\r\n            if (picker_type == 0) picker_flags |= ImGuiColorEditFlags_PickerHueBar;\r\n            if (picker_type == 1) picker_flags |= ImGuiColorEditFlags_PickerHueWheel;\r\n            ImVec2 backup_pos = GetCursorScreenPos();\r\n            if (Selectable(\"##selectable\", false, 0, picker_size)) // By default, Selectable() is closing popup\r\n                g.ColorEditOptions = (g.ColorEditOptions & ~ImGuiColorEditFlags_PickerMask_) | (picker_flags & ImGuiColorEditFlags_PickerMask_);\r\n            SetCursorScreenPos(backup_pos);\r\n            ImVec4 previewing_ref_col;\r\n            memcpy(&previewing_ref_col, ref_col, sizeof(float) * ((picker_flags & ImGuiColorEditFlags_NoAlpha) ? 3 : 4));\r\n            ColorPicker4(\"##previewing_picker\", &previewing_ref_col.x, picker_flags);\r\n            PopID();\r\n        }\r\n        PopItemWidth();\r\n    }\r\n    if (allow_opt_alpha_bar)\r\n    {\r\n        if (allow_opt_picker) Separator();\r\n        CheckboxFlags(\"Alpha Bar\", &g.ColorEditOptions, ImGuiColorEditFlags_AlphaBar);\r\n    }\r\n    EndPopup();\r\n}\r\n\r\n//-------------------------------------------------------------------------\r\n// [SECTION] Widgets: TreeNode, CollapsingHeader, etc.\r\n//-------------------------------------------------------------------------\r\n// - TreeNode()\r\n// - TreeNodeV()\r\n// - TreeNodeEx()\r\n// - TreeNodeExV()\r\n// - TreeNodeBehavior() [Internal]\r\n// - TreePush()\r\n// - TreePop()\r\n// - GetTreeNodeToLabelSpacing()\r\n// - SetNextItemOpen()\r\n// - CollapsingHeader()\r\n//-------------------------------------------------------------------------\r\n\r\nbool ImGui::TreeNode(const char* str_id, const char* fmt, ...)\r\n{\r\n    va_list args;\r\n    va_start(args, fmt);\r\n    bool is_open = TreeNodeExV(str_id, 0, fmt, args);\r\n    va_end(args);\r\n    return is_open;\r\n}\r\n\r\nbool ImGui::TreeNode(const void* ptr_id, const char* fmt, ...)\r\n{\r\n    va_list args;\r\n    va_start(args, fmt);\r\n    bool is_open = TreeNodeExV(ptr_id, 0, fmt, args);\r\n    va_end(args);\r\n    return is_open;\r\n}\r\n\r\nbool ImGui::TreeNode(const char* label)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return false;\r\n    return TreeNodeBehavior(window->GetID(label), 0, label, NULL);\r\n}\r\n\r\nbool ImGui::TreeNodeV(const char* str_id, const char* fmt, va_list args)\r\n{\r\n    return TreeNodeExV(str_id, 0, fmt, args);\r\n}\r\n\r\nbool ImGui::TreeNodeV(const void* ptr_id, const char* fmt, va_list args)\r\n{\r\n    return TreeNodeExV(ptr_id, 0, fmt, args);\r\n}\r\n\r\nbool ImGui::TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return false;\r\n\r\n    return TreeNodeBehavior(window->GetID(label), flags, label, NULL);\r\n}\r\n\r\nbool ImGui::TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...)\r\n{\r\n    va_list args;\r\n    va_start(args, fmt);\r\n    bool is_open = TreeNodeExV(str_id, flags, fmt, args);\r\n    va_end(args);\r\n    return is_open;\r\n}\r\n\r\nbool ImGui::TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...)\r\n{\r\n    va_list args;\r\n    va_start(args, fmt);\r\n    bool is_open = TreeNodeExV(ptr_id, flags, fmt, args);\r\n    va_end(args);\r\n    return is_open;\r\n}\r\n\r\nbool ImGui::TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return false;\r\n\r\n    ImGuiContext& g = *GImGui;\r\n    const char* label_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);\r\n    return TreeNodeBehavior(window->GetID(str_id), flags, g.TempBuffer, label_end);\r\n}\r\n\r\nbool ImGui::TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return false;\r\n\r\n    ImGuiContext& g = *GImGui;\r\n    const char* label_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);\r\n    return TreeNodeBehavior(window->GetID(ptr_id), flags, g.TempBuffer, label_end);\r\n}\r\n\r\nbool ImGui::TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags)\r\n{\r\n    if (flags & ImGuiTreeNodeFlags_Leaf)\r\n        return true;\r\n\r\n    // We only write to the tree storage if the user clicks (or explicitly use the SetNextItemOpen function)\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    ImGuiStorage* storage = window->DC.StateStorage;\r\n\r\n    bool is_open;\r\n    if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasOpen)\r\n    {\r\n        if (g.NextItemData.OpenCond & ImGuiCond_Always)\r\n        {\r\n            is_open = g.NextItemData.OpenVal;\r\n            storage->SetInt(id, is_open);\r\n        }\r\n        else\r\n        {\r\n            // We treat ImGuiCond_Once and ImGuiCond_FirstUseEver the same because tree node state are not saved persistently.\r\n            const int stored_value = storage->GetInt(id, -1);\r\n            if (stored_value == -1)\r\n            {\r\n                is_open = g.NextItemData.OpenVal;\r\n                storage->SetInt(id, is_open);\r\n            }\r\n            else\r\n            {\r\n                is_open = stored_value != 0;\r\n            }\r\n        }\r\n    }\r\n    else\r\n    {\r\n        is_open = storage->GetInt(id, (flags & ImGuiTreeNodeFlags_DefaultOpen) ? 1 : 0) != 0;\r\n    }\r\n\r\n    // When logging is enabled, we automatically expand tree nodes (but *NOT* collapsing headers.. seems like sensible behavior).\r\n    // NB- If we are above max depth we still allow manually opened nodes to be logged.\r\n    if (g.LogEnabled && !(flags & ImGuiTreeNodeFlags_NoAutoOpenOnLog) && (window->DC.TreeDepth - g.LogDepthRef) < g.LogDepthToExpand)\r\n        is_open = true;\r\n\r\n    return is_open;\r\n}\r\n\r\nbool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return false;\r\n\r\n    ImGuiContext& g = *GImGui;\r\n    const ImGuiStyle& style = g.Style;\r\n    const bool display_frame = (flags & ImGuiTreeNodeFlags_Framed) != 0;\r\n    const ImVec2 padding = (display_frame || (flags & ImGuiTreeNodeFlags_FramePadding)) ? style.FramePadding : ImVec2(style.FramePadding.x, ImMin(window->DC.CurrLineTextBaseOffset, style.FramePadding.y));\r\n\r\n    if (!label_end)\r\n        label_end = FindRenderedTextEnd(label);\r\n    const ImVec2 label_size = CalcTextSize(label, label_end, false);\r\n\r\n    // We vertically grow up to current line height up the typical widget height.\r\n    const float frame_height = ImMax(ImMin(window->DC.CurrLineSize.y, g.FontSize + style.FramePadding.y * 2), label_size.y + padding.y * 2);\r\n    ImRect frame_bb;\r\n    frame_bb.Min.x = (flags & ImGuiTreeNodeFlags_SpanFullWidth) ? window->WorkRect.Min.x : window->DC.CursorPos.x;\r\n    frame_bb.Min.y = window->DC.CursorPos.y;\r\n    frame_bb.Max.x = window->WorkRect.Max.x;\r\n    frame_bb.Max.y = window->DC.CursorPos.y + frame_height;\r\n    if (display_frame)\r\n    {\r\n        // Framed header expand a little outside the default padding, to the edge of InnerClipRect\r\n        // (FIXME: May remove this at some point and make InnerClipRect align with WindowPadding.x instead of WindowPadding.x*0.5f)\r\n        frame_bb.Min.x -= IM_FLOOR(window->WindowPadding.x * 0.5f - 1.0f);\r\n        frame_bb.Max.x += IM_FLOOR(window->WindowPadding.x * 0.5f);\r\n    }\r\n\r\n    const float text_offset_x = g.FontSize + (display_frame ? padding.x * 3 : padding.x * 2);           // Collapser arrow width + Spacing\r\n    const float text_offset_y = ImMax(padding.y, window->DC.CurrLineTextBaseOffset);                    // Latch before ItemSize changes it\r\n    const float text_width = g.FontSize + (label_size.x > 0.0f ? label_size.x + padding.x * 2 : 0.0f);  // Include collapser\r\n    ImVec2 text_pos(window->DC.CursorPos.x + text_offset_x, window->DC.CursorPos.y + text_offset_y);\r\n    ItemSize(ImVec2(text_width, frame_height), padding.y);\r\n\r\n    // For regular tree nodes, we arbitrary allow to click past 2 worth of ItemSpacing\r\n    ImRect interact_bb = frame_bb;\r\n    if (!display_frame && (flags & (ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_SpanFullWidth)) == 0)\r\n        interact_bb.Max.x = frame_bb.Min.x + text_width + style.ItemSpacing.x * 2.0f;\r\n\r\n    // Store a flag for the current depth to tell if we will allow closing this node when navigating one of its child.\r\n    // For this purpose we essentially compare if g.NavIdIsAlive went from 0 to 1 between TreeNode() and TreePop().\r\n    // This is currently only support 32 level deep and we are fine with (1 << Depth) overflowing into a zero.\r\n    const bool is_leaf = (flags & ImGuiTreeNodeFlags_Leaf) != 0;\r\n    bool is_open = TreeNodeBehaviorIsOpen(id, flags);\r\n    if (is_open && !g.NavIdIsAlive && (flags & ImGuiTreeNodeFlags_NavLeftJumpsBackHere) && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))\r\n        window->DC.TreeJumpToParentOnPopMask |= (1 << window->DC.TreeDepth);\r\n\r\n    bool item_add = ItemAdd(interact_bb, id);\r\n    g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDisplayRect;\r\n    g.LastItemData.DisplayRect = frame_bb;\r\n\r\n    if (!item_add)\r\n    {\r\n        if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))\r\n            TreePushOverrideID(id);\r\n        IMGUI_TEST_ENGINE_ITEM_INFO(g.LastItemData.ID, label, g.LastItemData.StatusFlags | (is_leaf ? 0 : ImGuiItemStatusFlags_Openable) | (is_open ? ImGuiItemStatusFlags_Opened : 0));\r\n        return is_open;\r\n    }\r\n\r\n    ImGuiButtonFlags button_flags = ImGuiTreeNodeFlags_None;\r\n    if (flags & ImGuiTreeNodeFlags_AllowItemOverlap)\r\n        button_flags |= ImGuiButtonFlags_AllowItemOverlap;\r\n    if (!is_leaf)\r\n        button_flags |= ImGuiButtonFlags_PressedOnDragDropHold;\r\n\r\n    // We allow clicking on the arrow section with keyboard modifiers held, in order to easily\r\n    // allow browsing a tree while preserving selection with code implementing multi-selection patterns.\r\n    // When clicking on the rest of the tree node we always disallow keyboard modifiers.\r\n    const float arrow_hit_x1 = (text_pos.x - text_offset_x) - style.TouchExtraPadding.x;\r\n    const float arrow_hit_x2 = (text_pos.x - text_offset_x) + (g.FontSize + padding.x * 2.0f) + style.TouchExtraPadding.x;\r\n    const bool is_mouse_x_over_arrow = (g.IO.MousePos.x >= arrow_hit_x1 && g.IO.MousePos.x < arrow_hit_x2);\r\n    if (window != g.HoveredWindow || !is_mouse_x_over_arrow)\r\n        button_flags |= ImGuiButtonFlags_NoKeyModifiers;\r\n\r\n    // Open behaviors can be altered with the _OpenOnArrow and _OnOnDoubleClick flags.\r\n    // Some alteration have subtle effects (e.g. toggle on MouseUp vs MouseDown events) due to requirements for multi-selection and drag and drop support.\r\n    // - Single-click on label = Toggle on MouseUp (default, when _OpenOnArrow=0)\r\n    // - Single-click on arrow = Toggle on MouseDown (when _OpenOnArrow=0)\r\n    // - Single-click on arrow = Toggle on MouseDown (when _OpenOnArrow=1)\r\n    // - Double-click on label = Toggle on MouseDoubleClick (when _OpenOnDoubleClick=1)\r\n    // - Double-click on arrow = Toggle on MouseDoubleClick (when _OpenOnDoubleClick=1 and _OpenOnArrow=0)\r\n    // It is rather standard that arrow click react on Down rather than Up.\r\n    // We set ImGuiButtonFlags_PressedOnClickRelease on OpenOnDoubleClick because we want the item to be active on the initial MouseDown in order for drag and drop to work.\r\n    if (is_mouse_x_over_arrow)\r\n        button_flags |= ImGuiButtonFlags_PressedOnClick;\r\n    else if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick)\r\n        button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick;\r\n    else\r\n        button_flags |= ImGuiButtonFlags_PressedOnClickRelease;\r\n\r\n    bool selected = (flags & ImGuiTreeNodeFlags_Selected) != 0;\r\n    const bool was_selected = selected;\r\n\r\n    bool hovered, held;\r\n    bool pressed = ButtonBehavior(interact_bb, id, &hovered, &held, button_flags);\r\n    bool toggled = false;\r\n    if (!is_leaf)\r\n    {\r\n        if (pressed && g.DragDropHoldJustPressedId != id)\r\n        {\r\n            if ((flags & (ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick)) == 0 || (g.NavActivateId == id))\r\n                toggled = true;\r\n            if (flags & ImGuiTreeNodeFlags_OpenOnArrow)\r\n                toggled |= is_mouse_x_over_arrow && !g.NavDisableMouseHover; // Lightweight equivalent of IsMouseHoveringRect() since ButtonBehavior() already did the job\r\n            if ((flags & ImGuiTreeNodeFlags_OpenOnDoubleClick) && g.IO.MouseClickedCount[0] == 2)\r\n                toggled = true;\r\n        }\r\n        else if (pressed && g.DragDropHoldJustPressedId == id)\r\n        {\r\n            IM_ASSERT(button_flags & ImGuiButtonFlags_PressedOnDragDropHold);\r\n            if (!is_open) // When using Drag and Drop \"hold to open\" we keep the node highlighted after opening, but never close it again.\r\n                toggled = true;\r\n        }\r\n\r\n        if (g.NavId == id && g.NavMoveDir == ImGuiDir_Left && is_open)\r\n        {\r\n            toggled = true;\r\n            NavMoveRequestCancel();\r\n        }\r\n        if (g.NavId == id && g.NavMoveDir == ImGuiDir_Right && !is_open) // If there's something upcoming on the line we may want to give it the priority?\r\n        {\r\n            toggled = true;\r\n            NavMoveRequestCancel();\r\n        }\r\n\r\n        if (toggled)\r\n        {\r\n            is_open = !is_open;\r\n            window->DC.StateStorage->SetInt(id, is_open);\r\n            g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_ToggledOpen;\r\n        }\r\n    }\r\n    if (flags & ImGuiTreeNodeFlags_AllowItemOverlap)\r\n        SetItemAllowOverlap();\r\n\r\n    // In this branch, TreeNodeBehavior() cannot toggle the selection so this will never trigger.\r\n    if (selected != was_selected) //-V547\r\n        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_ToggledSelection;\r\n\r\n    // Render\r\n    const ImU32 text_col = GetColorU32(ImGuiCol_Text);\r\n    ImGuiNavHighlightFlags nav_highlight_flags = ImGuiNavHighlightFlags_TypeThin;\r\n    if (display_frame)\r\n    {\r\n        // Framed type\r\n        const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);\r\n        RenderFrame(frame_bb.Min, frame_bb.Max, bg_col, true, style.FrameRounding);\r\n        RenderNavHighlight(frame_bb, id, nav_highlight_flags);\r\n        if (flags & ImGuiTreeNodeFlags_Bullet)\r\n            RenderBullet(window->DrawList, ImVec2(text_pos.x - text_offset_x * 0.60f, text_pos.y + g.FontSize * 0.5f), text_col);\r\n        else if (!is_leaf)\r\n            RenderArrow(window->DrawList, ImVec2(text_pos.x - text_offset_x + padding.x, text_pos.y), text_col, is_open ? ImGuiDir_Down : ImGuiDir_Right, 1.0f);\r\n        else // Leaf without bullet, left-adjusted text\r\n            text_pos.x -= text_offset_x;\r\n        if (flags & ImGuiTreeNodeFlags_ClipLabelForTrailingButton)\r\n            frame_bb.Max.x -= g.FontSize + style.FramePadding.x;\r\n\r\n        if (g.LogEnabled)\r\n            LogSetNextTextDecoration(\"###\", \"###\");\r\n        RenderTextClipped(text_pos, frame_bb.Max, label, label_end, &label_size);\r\n    }\r\n    else\r\n    {\r\n        // Unframed typed for tree nodes\r\n        if (hovered || selected)\r\n        {\r\n            const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);\r\n            RenderFrame(frame_bb.Min, frame_bb.Max, bg_col, false);\r\n        }\r\n        RenderNavHighlight(frame_bb, id, nav_highlight_flags);\r\n        if (flags & ImGuiTreeNodeFlags_Bullet)\r\n            RenderBullet(window->DrawList, ImVec2(text_pos.x - text_offset_x * 0.5f, text_pos.y + g.FontSize * 0.5f), text_col);\r\n        else if (!is_leaf)\r\n            RenderArrow(window->DrawList, ImVec2(text_pos.x - text_offset_x + padding.x, text_pos.y + g.FontSize * 0.15f), text_col, is_open ? ImGuiDir_Down : ImGuiDir_Right, 0.70f);\r\n        if (g.LogEnabled)\r\n            LogSetNextTextDecoration(\">\", NULL);\r\n        RenderText(text_pos, label, label_end, false);\r\n    }\r\n\r\n    if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))\r\n        TreePushOverrideID(id);\r\n    IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | (is_leaf ? 0 : ImGuiItemStatusFlags_Openable) | (is_open ? ImGuiItemStatusFlags_Opened : 0));\r\n    return is_open;\r\n}\r\n\r\nvoid ImGui::TreePush(const char* str_id)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    Indent();\r\n    window->DC.TreeDepth++;\r\n    PushID(str_id);\r\n}\r\n\r\nvoid ImGui::TreePush(const void* ptr_id)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    Indent();\r\n    window->DC.TreeDepth++;\r\n    PushID(ptr_id);\r\n}\r\n\r\nvoid ImGui::TreePushOverrideID(ImGuiID id)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    Indent();\r\n    window->DC.TreeDepth++;\r\n    PushOverrideID(id);\r\n}\r\n\r\nvoid ImGui::TreePop()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    Unindent();\r\n\r\n    window->DC.TreeDepth--;\r\n    ImU32 tree_depth_mask = (1 << window->DC.TreeDepth);\r\n\r\n    // Handle Left arrow to move to parent tree node (when ImGuiTreeNodeFlags_NavLeftJumpsBackHere is enabled)\r\n    if (g.NavMoveDir == ImGuiDir_Left && g.NavWindow == window && NavMoveRequestButNoResultYet())\r\n        if (g.NavIdIsAlive && (window->DC.TreeJumpToParentOnPopMask & tree_depth_mask))\r\n        {\r\n            SetNavID(window->IDStack.back(), g.NavLayer, 0, ImRect());\r\n            NavMoveRequestCancel();\r\n        }\r\n    window->DC.TreeJumpToParentOnPopMask &= tree_depth_mask - 1;\r\n\r\n    IM_ASSERT(window->IDStack.Size > 1); // There should always be 1 element in the IDStack (pushed during window creation). If this triggers you called TreePop/PopID too much.\r\n    PopID();\r\n}\r\n\r\n// Horizontal distance preceding label when using TreeNode() or Bullet()\r\nfloat ImGui::GetTreeNodeToLabelSpacing()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    return g.FontSize + (g.Style.FramePadding.x * 2.0f);\r\n}\r\n\r\n// Set next TreeNode/CollapsingHeader open state.\r\nvoid ImGui::SetNextItemOpen(bool is_open, ImGuiCond cond)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    if (g.CurrentWindow->SkipItems)\r\n        return;\r\n    g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasOpen;\r\n    g.NextItemData.OpenVal = is_open;\r\n    g.NextItemData.OpenCond = cond ? cond : ImGuiCond_Always;\r\n}\r\n\r\n// CollapsingHeader returns true when opened but do not indent nor push into the ID stack (because of the ImGuiTreeNodeFlags_NoTreePushOnOpen flag).\r\n// This is basically the same as calling TreeNodeEx(label, ImGuiTreeNodeFlags_CollapsingHeader). You can remove the _NoTreePushOnOpen flag if you want behavior closer to normal TreeNode().\r\nbool ImGui::CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return false;\r\n\r\n    return TreeNodeBehavior(window->GetID(label), flags | ImGuiTreeNodeFlags_CollapsingHeader, label);\r\n}\r\n\r\n// p_visible == NULL                        : regular collapsing header\r\n// p_visible != NULL && *p_visible == true  : show a small close button on the corner of the header, clicking the button will set *p_visible = false\r\n// p_visible != NULL && *p_visible == false : do not show the header at all\r\n// Do not mistake this with the Open state of the header itself, which you can adjust with SetNextItemOpen() or ImGuiTreeNodeFlags_DefaultOpen.\r\nbool ImGui::CollapsingHeader(const char* label, bool* p_visible, ImGuiTreeNodeFlags flags)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return false;\r\n\r\n    if (p_visible && !*p_visible)\r\n        return false;\r\n\r\n    ImGuiID id = window->GetID(label);\r\n    flags |= ImGuiTreeNodeFlags_CollapsingHeader;\r\n    if (p_visible)\r\n        flags |= ImGuiTreeNodeFlags_AllowItemOverlap | ImGuiTreeNodeFlags_ClipLabelForTrailingButton;\r\n    bool is_open = TreeNodeBehavior(id, flags, label);\r\n    if (p_visible != NULL)\r\n    {\r\n        // Create a small overlapping close button\r\n        // FIXME: We can evolve this into user accessible helpers to add extra buttons on title bars, headers, etc.\r\n        // FIXME: CloseButton can overlap into text, need find a way to clip the text somehow.\r\n        ImGuiContext& g = *GImGui;\r\n        ImGuiLastItemData last_item_backup = g.LastItemData;\r\n        float button_size = g.FontSize;\r\n        float button_x = ImMax(g.LastItemData.Rect.Min.x, g.LastItemData.Rect.Max.x - g.Style.FramePadding.x * 2.0f - button_size);\r\n        float button_y = g.LastItemData.Rect.Min.y;\r\n        ImGuiID close_button_id = GetIDWithSeed(\"#CLOSE\", NULL, id);\r\n        if (CloseButton(close_button_id, ImVec2(button_x, button_y)))\r\n            *p_visible = false;\r\n        g.LastItemData = last_item_backup;\r\n    }\r\n\r\n    return is_open;\r\n}\r\n\r\n//-------------------------------------------------------------------------\r\n// [SECTION] Widgets: Selectable\r\n//-------------------------------------------------------------------------\r\n// - Selectable()\r\n//-------------------------------------------------------------------------\r\n\r\n// Tip: pass a non-visible label (e.g. \"##hello\") then you can use the space to draw other text or image.\r\n// But you need to make sure the ID is unique, e.g. enclose calls in PushID/PopID or use ##unique_id.\r\n// With this scheme, ImGuiSelectableFlags_SpanAllColumns and ImGuiSelectableFlags_AllowItemOverlap are also frequently used flags.\r\n// FIXME: Selectable() with (size.x == 0.0f) and (SelectableTextAlign.x > 0.0f) followed by SameLine() is currently not supported.\r\nbool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags flags, const ImVec2& size_arg)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return false;\r\n\r\n    ImGuiContext& g = *GImGui;\r\n    const ImGuiStyle& style = g.Style;\r\n\r\n    // Submit label or explicit size to ItemSize(), whereas ItemAdd() will submit a larger/spanning rectangle.\r\n    ImGuiID id = window->GetID(label);\r\n    ImVec2 label_size = CalcTextSize(label, NULL, true);\r\n    ImVec2 size(size_arg.x != 0.0f ? size_arg.x : label_size.x, size_arg.y != 0.0f ? size_arg.y : label_size.y);\r\n    ImVec2 pos = window->DC.CursorPos;\r\n    pos.y += window->DC.CurrLineTextBaseOffset;\r\n    ItemSize(size, 0.0f);\r\n\r\n    // Fill horizontal space\r\n    // We don't support (size < 0.0f) in Selectable() because the ItemSpacing extension would make explicitly right-aligned sizes not visibly match other widgets.\r\n    const bool span_all_columns = (flags & ImGuiSelectableFlags_SpanAllColumns) != 0;\r\n    const float min_x = span_all_columns ? window->ParentWorkRect.Min.x : pos.x;\r\n    const float max_x = span_all_columns ? window->ParentWorkRect.Max.x : window->WorkRect.Max.x;\r\n    if (size_arg.x == 0.0f || (flags & ImGuiSelectableFlags_SpanAvailWidth))\r\n        size.x = ImMax(label_size.x, max_x - min_x);\r\n\r\n    // Text stays at the submission position, but bounding box may be extended on both sides\r\n    const ImVec2 text_min = pos;\r\n    const ImVec2 text_max(min_x + size.x, pos.y + size.y);\r\n\r\n    // Selectables are meant to be tightly packed together with no click-gap, so we extend their box to cover spacing between selectable.\r\n    ImRect bb(min_x, pos.y, text_max.x, text_max.y);\r\n    if ((flags & ImGuiSelectableFlags_NoPadWithHalfSpacing) == 0)\r\n    {\r\n        const float spacing_x = span_all_columns ? 0.0f : style.ItemSpacing.x;\r\n        const float spacing_y = style.ItemSpacing.y;\r\n        const float spacing_L = IM_FLOOR(spacing_x * 0.50f);\r\n        const float spacing_U = IM_FLOOR(spacing_y * 0.50f);\r\n        bb.Min.x -= spacing_L;\r\n        bb.Min.y -= spacing_U;\r\n        bb.Max.x += (spacing_x - spacing_L);\r\n        bb.Max.y += (spacing_y - spacing_U);\r\n    }\r\n    //if (g.IO.KeyCtrl) { GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(0, 255, 0, 255)); }\r\n\r\n    // Modify ClipRect for the ItemAdd(), faster than doing a PushColumnsBackground/PushTableBackground for every Selectable..\r\n    const float backup_clip_rect_min_x = window->ClipRect.Min.x;\r\n    const float backup_clip_rect_max_x = window->ClipRect.Max.x;\r\n    if (span_all_columns)\r\n    {\r\n        window->ClipRect.Min.x = window->ParentWorkRect.Min.x;\r\n        window->ClipRect.Max.x = window->ParentWorkRect.Max.x;\r\n    }\r\n\r\n    const bool disabled_item = (flags & ImGuiSelectableFlags_Disabled) != 0;\r\n    const bool item_add = ItemAdd(bb, id, NULL, disabled_item ? ImGuiItemFlags_Disabled : ImGuiItemFlags_None);\r\n    if (span_all_columns)\r\n    {\r\n        window->ClipRect.Min.x = backup_clip_rect_min_x;\r\n        window->ClipRect.Max.x = backup_clip_rect_max_x;\r\n    }\r\n\r\n    if (!item_add)\r\n        return false;\r\n\r\n    const bool disabled_global = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;\r\n    if (disabled_item && !disabled_global) // Only testing this as an optimization\r\n        BeginDisabled();\r\n\r\n    // FIXME: We can standardize the behavior of those two, we could also keep the fast path of override ClipRect + full push on render only,\r\n    // which would be advantageous since most selectable are not selected.\r\n    if (span_all_columns && window->DC.CurrentColumns)\r\n        PushColumnsBackground();\r\n    else if (span_all_columns && g.CurrentTable)\r\n        TablePushBackgroundChannel();\r\n\r\n    // We use NoHoldingActiveID on menus so user can click and _hold_ on a menu then drag to browse child entries\r\n    ImGuiButtonFlags button_flags = 0;\r\n    if (flags & ImGuiSelectableFlags_NoHoldingActiveID) { button_flags |= ImGuiButtonFlags_NoHoldingActiveId; }\r\n    if (flags & ImGuiSelectableFlags_SelectOnClick)     { button_flags |= ImGuiButtonFlags_PressedOnClick; }\r\n    if (flags & ImGuiSelectableFlags_SelectOnRelease)   { button_flags |= ImGuiButtonFlags_PressedOnRelease; }\r\n    if (flags & ImGuiSelectableFlags_AllowDoubleClick)  { button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick; }\r\n    if (flags & ImGuiSelectableFlags_AllowItemOverlap)  { button_flags |= ImGuiButtonFlags_AllowItemOverlap; }\r\n\r\n    const bool was_selected = selected;\r\n    bool hovered, held;\r\n    bool pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags);\r\n\r\n    // Auto-select when moved into\r\n    // - This will be more fully fleshed in the range-select branch\r\n    // - This is not exposed as it won't nicely work with some user side handling of shift/control\r\n    // - We cannot do 'if (g.NavJustMovedToId != id) { selected = false; pressed = was_selected; }' for two reasons\r\n    //   - (1) it would require focus scope to be set, need exposing PushFocusScope() or equivalent (e.g. BeginSelection() calling PushFocusScope())\r\n    //   - (2) usage will fail with clipped items\r\n    //   The multi-select API aim to fix those issues, e.g. may be replaced with a BeginSelection() API.\r\n    if ((flags & ImGuiSelectableFlags_SelectOnNav) && g.NavJustMovedToId != 0 && g.NavJustMovedToFocusScopeId == window->DC.NavFocusScopeIdCurrent)\r\n        if (g.NavJustMovedToId == id)\r\n            selected = pressed = true;\r\n\r\n    // Update NavId when clicking or when Hovering (this doesn't happen on most widgets), so navigation can be resumed with gamepad/keyboard\r\n    if (pressed || (hovered && (flags & ImGuiSelectableFlags_SetNavIdOnHover)))\r\n    {\r\n        if (!g.NavDisableMouseHover && g.NavWindow == window && g.NavLayer == window->DC.NavLayerCurrent)\r\n        {\r\n            SetNavID(id, window->DC.NavLayerCurrent, window->DC.NavFocusScopeIdCurrent, WindowRectAbsToRel(window, bb)); // (bb == NavRect)\r\n            g.NavDisableHighlight = true;\r\n        }\r\n    }\r\n    if (pressed)\r\n        MarkItemEdited(id);\r\n\r\n    if (flags & ImGuiSelectableFlags_AllowItemOverlap)\r\n        SetItemAllowOverlap();\r\n\r\n    // In this branch, Selectable() cannot toggle the selection so this will never trigger.\r\n    if (selected != was_selected) //-V547\r\n        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_ToggledSelection;\r\n\r\n    // Render\r\n    if (held && (flags & ImGuiSelectableFlags_DrawHoveredWhenHeld))\r\n        hovered = true;\r\n    if (hovered || selected)\r\n    {\r\n        const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);\r\n        RenderFrame(bb.Min, bb.Max, col, false, 0.0f);\r\n    }\r\n    RenderNavHighlight(bb, id, ImGuiNavHighlightFlags_TypeThin | ImGuiNavHighlightFlags_NoRounding);\r\n\r\n    if (span_all_columns && window->DC.CurrentColumns)\r\n        PopColumnsBackground();\r\n    else if (span_all_columns && g.CurrentTable)\r\n        TablePopBackgroundChannel();\r\n\r\n    RenderTextClipped(text_min, text_max, label, NULL, &label_size, style.SelectableTextAlign, &bb);\r\n\r\n    // Automatically close popups\r\n    if (pressed && (window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiSelectableFlags_DontClosePopups) && !(g.LastItemData.InFlags & ImGuiItemFlags_SelectableDontClosePopup))\r\n        CloseCurrentPopup();\r\n\r\n    if (disabled_item && !disabled_global)\r\n        EndDisabled();\r\n\r\n    IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags);\r\n    return pressed; //-V1020\r\n}\r\n\r\nbool ImGui::Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags, const ImVec2& size_arg)\r\n{\r\n    if (Selectable(label, *p_selected, flags, size_arg))\r\n    {\r\n        *p_selected = !*p_selected;\r\n        return true;\r\n    }\r\n    return false;\r\n}\r\n\r\n//-------------------------------------------------------------------------\r\n// [SECTION] Widgets: ListBox\r\n//-------------------------------------------------------------------------\r\n// - BeginListBox()\r\n// - EndListBox()\r\n// - ListBox()\r\n//-------------------------------------------------------------------------\r\n\r\n// Tip: To have a list filling the entire window width, use size.x = -FLT_MIN and pass an non-visible label e.g. \"##empty\"\r\n// Tip: If your vertical size is calculated from an item count (e.g. 10 * item_height) consider adding a fractional part to facilitate seeing scrolling boundaries (e.g. 10.25 * item_height).\r\nbool ImGui::BeginListBox(const char* label, const ImVec2& size_arg)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return false;\r\n\r\n    const ImGuiStyle& style = g.Style;\r\n    const ImGuiID id = GetID(label);\r\n    const ImVec2 label_size = CalcTextSize(label, NULL, true);\r\n\r\n    // Size default to hold ~7.25 items.\r\n    // Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar.\r\n    ImVec2 size = ImFloor(CalcItemSize(size_arg, CalcItemWidth(), GetTextLineHeightWithSpacing() * 7.25f + style.FramePadding.y * 2.0f));\r\n    ImVec2 frame_size = ImVec2(size.x, ImMax(size.y, label_size.y));\r\n    ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size);\r\n    ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));\r\n    g.NextItemData.ClearFlags();\r\n\r\n    if (!IsRectVisible(bb.Min, bb.Max))\r\n    {\r\n        ItemSize(bb.GetSize(), style.FramePadding.y);\r\n        ItemAdd(bb, 0, &frame_bb);\r\n        return false;\r\n    }\r\n\r\n    // FIXME-OPT: We could omit the BeginGroup() if label_size.x but would need to omit the EndGroup() as well.\r\n    BeginGroup();\r\n    if (label_size.x > 0.0f)\r\n    {\r\n        ImVec2 label_pos = ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y);\r\n        RenderText(label_pos, label);\r\n        window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, label_pos + label_size);\r\n    }\r\n\r\n    BeginChildFrame(id, frame_bb.GetSize());\r\n    return true;\r\n}\r\n\r\n#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS\r\n// OBSOLETED in 1.81 (from February 2021)\r\nbool ImGui::ListBoxHeader(const char* label, int items_count, int height_in_items)\r\n{\r\n    // If height_in_items == -1, default height is maximum 7.\r\n    ImGuiContext& g = *GImGui;\r\n    float height_in_items_f = (height_in_items < 0 ? ImMin(items_count, 7) : height_in_items) + 0.25f;\r\n    ImVec2 size;\r\n    size.x = 0.0f;\r\n    size.y = GetTextLineHeightWithSpacing() * height_in_items_f + g.Style.FramePadding.y * 2.0f;\r\n    return BeginListBox(label, size);\r\n}\r\n#endif\r\n\r\nvoid ImGui::EndListBox()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    IM_ASSERT((window->Flags & ImGuiWindowFlags_ChildWindow) && \"Mismatched BeginListBox/EndListBox calls. Did you test the return value of BeginListBox?\");\r\n    IM_UNUSED(window);\r\n\r\n    EndChildFrame();\r\n    EndGroup(); // This is only required to be able to do IsItemXXX query on the whole ListBox including label\r\n}\r\n\r\nbool ImGui::ListBox(const char* label, int* current_item, const char* const items[], int items_count, int height_items)\r\n{\r\n    const bool value_changed = ListBox(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_items);\r\n    return value_changed;\r\n}\r\n\r\n// This is merely a helper around BeginListBox(), EndListBox().\r\n// Considering using those directly to submit custom data or store selection differently.\r\nbool ImGui::ListBox(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int height_in_items)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n\r\n    // Calculate size from \"height_in_items\"\r\n    if (height_in_items < 0)\r\n        height_in_items = ImMin(items_count, 7);\r\n    float height_in_items_f = height_in_items + 0.25f;\r\n    ImVec2 size(0.0f, ImFloor(GetTextLineHeightWithSpacing() * height_in_items_f + g.Style.FramePadding.y * 2.0f));\r\n\r\n    if (!BeginListBox(label, size))\r\n        return false;\r\n\r\n    // Assume all items have even height (= 1 line of text). If you need items of different height,\r\n    // you can create a custom version of ListBox() in your code without using the clipper.\r\n    bool value_changed = false;\r\n    ImGuiListClipper clipper;\r\n    clipper.Begin(items_count, GetTextLineHeightWithSpacing()); // We know exactly our line height here so we pass it as a minor optimization, but generally you don't need to.\r\n    while (clipper.Step())\r\n        for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)\r\n        {\r\n            const char* item_text;\r\n            if (!items_getter(data, i, &item_text))\r\n                item_text = \"*Unknown item*\";\r\n\r\n            PushID(i);\r\n            const bool item_selected = (i == *current_item);\r\n            if (Selectable(item_text, item_selected))\r\n            {\r\n                *current_item = i;\r\n                value_changed = true;\r\n            }\r\n            if (item_selected)\r\n                SetItemDefaultFocus();\r\n            PopID();\r\n        }\r\n    EndListBox();\r\n\r\n    if (value_changed)\r\n        MarkItemEdited(g.LastItemData.ID);\r\n\r\n    return value_changed;\r\n}\r\n\r\n//-------------------------------------------------------------------------\r\n// [SECTION] Widgets: PlotLines, PlotHistogram\r\n//-------------------------------------------------------------------------\r\n// - PlotEx() [Internal]\r\n// - PlotLines()\r\n// - PlotHistogram()\r\n//-------------------------------------------------------------------------\r\n// Plot/Graph widgets are not very good.\r\n// Consider writing your own, or using a third-party one, see:\r\n// - ImPlot https://github.com/epezent/implot\r\n// - others https://github.com/ocornut/imgui/wiki/Useful-Extensions\r\n//-------------------------------------------------------------------------\r\n\r\nint ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 frame_size)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return -1;\r\n\r\n    const ImGuiStyle& style = g.Style;\r\n    const ImGuiID id = window->GetID(label);\r\n\r\n    const ImVec2 label_size = CalcTextSize(label, NULL, true);\r\n    if (frame_size.x == 0.0f)\r\n        frame_size.x = CalcItemWidth();\r\n    if (frame_size.y == 0.0f)\r\n        frame_size.y = label_size.y + (style.FramePadding.y * 2);\r\n\r\n    const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size);\r\n    const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding);\r\n    const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0));\r\n    ItemSize(total_bb, style.FramePadding.y);\r\n    if (!ItemAdd(total_bb, 0, &frame_bb))\r\n        return -1;\r\n    const bool hovered = ItemHoverable(frame_bb, id);\r\n\r\n    // Determine scale from values if not specified\r\n    if (scale_min == FLT_MAX || scale_max == FLT_MAX)\r\n    {\r\n        float v_min = FLT_MAX;\r\n        float v_max = -FLT_MAX;\r\n        for (int i = 0; i < values_count; i++)\r\n        {\r\n            const float v = values_getter(data, i);\r\n            if (v != v) // Ignore NaN values\r\n                continue;\r\n            v_min = ImMin(v_min, v);\r\n            v_max = ImMax(v_max, v);\r\n        }\r\n        if (scale_min == FLT_MAX)\r\n            scale_min = v_min;\r\n        if (scale_max == FLT_MAX)\r\n            scale_max = v_max;\r\n    }\r\n\r\n    RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);\r\n\r\n    const int values_count_min = (plot_type == ImGuiPlotType_Lines) ? 2 : 1;\r\n    int idx_hovered = -1;\r\n    if (values_count >= values_count_min)\r\n    {\r\n        int res_w = ImMin((int)frame_size.x, values_count) + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0);\r\n        int item_count = values_count + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0);\r\n\r\n        // Tooltip on hover\r\n        if (hovered && inner_bb.Contains(g.IO.MousePos))\r\n        {\r\n            const float t = ImClamp((g.IO.MousePos.x - inner_bb.Min.x) / (inner_bb.Max.x - inner_bb.Min.x), 0.0f, 0.9999f);\r\n            const int v_idx = (int)(t * item_count);\r\n            IM_ASSERT(v_idx >= 0 && v_idx < values_count);\r\n\r\n            const float v0 = values_getter(data, (v_idx + values_offset) % values_count);\r\n            const float v1 = values_getter(data, (v_idx + 1 + values_offset) % values_count);\r\n            if (plot_type == ImGuiPlotType_Lines)\r\n                SetTooltip(\"%d: %8.4g\\n%d: %8.4g\", v_idx, v0, v_idx + 1, v1);\r\n            else if (plot_type == ImGuiPlotType_Histogram)\r\n                SetTooltip(\"%d: %8.4g\", v_idx, v0);\r\n            idx_hovered = v_idx;\r\n        }\r\n\r\n        const float t_step = 1.0f / (float)res_w;\r\n        const float inv_scale = (scale_min == scale_max) ? 0.0f : (1.0f / (scale_max - scale_min));\r\n\r\n        float v0 = values_getter(data, (0 + values_offset) % values_count);\r\n        float t0 = 0.0f;\r\n        ImVec2 tp0 = ImVec2( t0, 1.0f - ImSaturate((v0 - scale_min) * inv_scale) );                       // Point in the normalized space of our target rectangle\r\n        float histogram_zero_line_t = (scale_min * scale_max < 0.0f) ? (1 + scale_min * inv_scale) : (scale_min < 0.0f ? 0.0f : 1.0f);   // Where does the zero line stands\r\n\r\n        const ImU32 col_base = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLines : ImGuiCol_PlotHistogram);\r\n        const ImU32 col_hovered = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLinesHovered : ImGuiCol_PlotHistogramHovered);\r\n\r\n        for (int n = 0; n < res_w; n++)\r\n        {\r\n            const float t1 = t0 + t_step;\r\n            const int v1_idx = (int)(t0 * item_count + 0.5f);\r\n            IM_ASSERT(v1_idx >= 0 && v1_idx < values_count);\r\n            const float v1 = values_getter(data, (v1_idx + values_offset + 1) % values_count);\r\n            const ImVec2 tp1 = ImVec2( t1, 1.0f - ImSaturate((v1 - scale_min) * inv_scale) );\r\n\r\n            // NB: Draw calls are merged together by the DrawList system. Still, we should render our batch are lower level to save a bit of CPU.\r\n            ImVec2 pos0 = ImLerp(inner_bb.Min, inner_bb.Max, tp0);\r\n            ImVec2 pos1 = ImLerp(inner_bb.Min, inner_bb.Max, (plot_type == ImGuiPlotType_Lines) ? tp1 : ImVec2(tp1.x, histogram_zero_line_t));\r\n            if (plot_type == ImGuiPlotType_Lines)\r\n            {\r\n                window->DrawList->AddLine(pos0, pos1, idx_hovered == v1_idx ? col_hovered : col_base);\r\n            }\r\n            else if (plot_type == ImGuiPlotType_Histogram)\r\n            {\r\n                if (pos1.x >= pos0.x + 2.0f)\r\n                    pos1.x -= 1.0f;\r\n                window->DrawList->AddRectFilled(pos0, pos1, idx_hovered == v1_idx ? col_hovered : col_base);\r\n            }\r\n\r\n            t0 = t1;\r\n            tp0 = tp1;\r\n        }\r\n    }\r\n\r\n    // Text overlay\r\n    if (overlay_text)\r\n        RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, overlay_text, NULL, NULL, ImVec2(0.5f, 0.0f));\r\n\r\n    if (label_size.x > 0.0f)\r\n        RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label);\r\n\r\n    // Return hovered index or -1 if none are hovered.\r\n    // This is currently not exposed in the public API because we need a larger redesign of the whole thing, but in the short-term we are making it available in PlotEx().\r\n    return idx_hovered;\r\n}\r\n\r\nstruct ImGuiPlotArrayGetterData\r\n{\r\n    const float* Values;\r\n    int Stride;\r\n\r\n    ImGuiPlotArrayGetterData(const float* values, int stride) { Values = values; Stride = stride; }\r\n};\r\n\r\nstatic float Plot_ArrayGetter(void* data, int idx)\r\n{\r\n    ImGuiPlotArrayGetterData* plot_data = (ImGuiPlotArrayGetterData*)data;\r\n    const float v = *(const float*)(const void*)((const unsigned char*)plot_data->Values + (size_t)idx * plot_data->Stride);\r\n    return v;\r\n}\r\n\r\nvoid ImGui::PlotLines(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride)\r\n{\r\n    ImGuiPlotArrayGetterData data(values, stride);\r\n    PlotEx(ImGuiPlotType_Lines, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);\r\n}\r\n\r\nvoid ImGui::PlotLines(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size)\r\n{\r\n    PlotEx(ImGuiPlotType_Lines, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);\r\n}\r\n\r\nvoid ImGui::PlotHistogram(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride)\r\n{\r\n    ImGuiPlotArrayGetterData data(values, stride);\r\n    PlotEx(ImGuiPlotType_Histogram, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);\r\n}\r\n\r\nvoid ImGui::PlotHistogram(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size)\r\n{\r\n    PlotEx(ImGuiPlotType_Histogram, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);\r\n}\r\n\r\n//-------------------------------------------------------------------------\r\n// [SECTION] Widgets: Value helpers\r\n// Those is not very useful, legacy API.\r\n//-------------------------------------------------------------------------\r\n// - Value()\r\n//-------------------------------------------------------------------------\r\n\r\nvoid ImGui::Value(const char* prefix, bool b)\r\n{\r\n    Text(\"%s: %s\", prefix, (b ? \"true\" : \"false\"));\r\n}\r\n\r\nvoid ImGui::Value(const char* prefix, int v)\r\n{\r\n    Text(\"%s: %d\", prefix, v);\r\n}\r\n\r\nvoid ImGui::Value(const char* prefix, unsigned int v)\r\n{\r\n    Text(\"%s: %d\", prefix, v);\r\n}\r\n\r\nvoid ImGui::Value(const char* prefix, float v, const char* float_format)\r\n{\r\n    if (float_format)\r\n    {\r\n        char fmt[64];\r\n        ImFormatString(fmt, IM_ARRAYSIZE(fmt), \"%%s: %s\", float_format);\r\n        Text(fmt, prefix, v);\r\n    }\r\n    else\r\n    {\r\n        Text(\"%s: %.3f\", prefix, v);\r\n    }\r\n}\r\n\r\n//-------------------------------------------------------------------------\r\n// [SECTION] MenuItem, BeginMenu, EndMenu, etc.\r\n//-------------------------------------------------------------------------\r\n// - ImGuiMenuColumns [Internal]\r\n// - BeginMenuBar()\r\n// - EndMenuBar()\r\n// - BeginMainMenuBar()\r\n// - EndMainMenuBar()\r\n// - BeginMenu()\r\n// - EndMenu()\r\n// - MenuItemEx() [Internal]\r\n// - MenuItem()\r\n//-------------------------------------------------------------------------\r\n\r\n// Helpers for internal use\r\nvoid ImGuiMenuColumns::Update(float spacing, bool window_reappearing)\r\n{\r\n    if (window_reappearing)\r\n        memset(Widths, 0, sizeof(Widths));\r\n    Spacing = (ImU16)spacing;\r\n    CalcNextTotalWidth(true);\r\n    memset(Widths, 0, sizeof(Widths));\r\n    TotalWidth = NextTotalWidth;\r\n    NextTotalWidth = 0;\r\n}\r\n\r\nvoid ImGuiMenuColumns::CalcNextTotalWidth(bool update_offsets)\r\n{\r\n    ImU16 offset = 0;\r\n    bool want_spacing = false;\r\n    for (int i = 0; i < IM_ARRAYSIZE(Widths); i++)\r\n    {\r\n        ImU16 width = Widths[i];\r\n        if (want_spacing && width > 0)\r\n            offset += Spacing;\r\n        want_spacing |= (width > 0);\r\n        if (update_offsets)\r\n        {\r\n            if (i == 1) { OffsetLabel = offset; }\r\n            if (i == 2) { OffsetShortcut = offset; }\r\n            if (i == 3) { OffsetMark = offset; }\r\n        }\r\n        offset += width;\r\n    }\r\n    NextTotalWidth = offset;\r\n}\r\n\r\nfloat ImGuiMenuColumns::DeclColumns(float w_icon, float w_label, float w_shortcut, float w_mark)\r\n{\r\n    Widths[0] = ImMax(Widths[0], (ImU16)w_icon);\r\n    Widths[1] = ImMax(Widths[1], (ImU16)w_label);\r\n    Widths[2] = ImMax(Widths[2], (ImU16)w_shortcut);\r\n    Widths[3] = ImMax(Widths[3], (ImU16)w_mark);\r\n    CalcNextTotalWidth(false);\r\n    return (float)ImMax(TotalWidth, NextTotalWidth);\r\n}\r\n\r\n// FIXME: Provided a rectangle perhaps e.g. a BeginMenuBarEx() could be used anywhere..\r\n// Currently the main responsibility of this function being to setup clip-rect + horizontal layout + menu navigation layer.\r\n// Ideally we also want this to be responsible for claiming space out of the main window scrolling rectangle, in which case ImGuiWindowFlags_MenuBar will become unnecessary.\r\n// Then later the same system could be used for multiple menu-bars, scrollbars, side-bars.\r\nbool ImGui::BeginMenuBar()\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return false;\r\n    if (!(window->Flags & ImGuiWindowFlags_MenuBar))\r\n        return false;\r\n\r\n    IM_ASSERT(!window->DC.MenuBarAppending);\r\n    BeginGroup(); // Backup position on layer 0 // FIXME: Misleading to use a group for that backup/restore\r\n    PushID(\"##menubar\");\r\n\r\n    // We don't clip with current window clipping rectangle as it is already set to the area below. However we clip with window full rect.\r\n    // We remove 1 worth of rounding to Max.x to that text in long menus and small windows don't tend to display over the lower-right rounded area, which looks particularly glitchy.\r\n    ImRect bar_rect = window->MenuBarRect();\r\n    ImRect clip_rect(IM_ROUND(bar_rect.Min.x + window->WindowBorderSize), IM_ROUND(bar_rect.Min.y + window->WindowBorderSize), IM_ROUND(ImMax(bar_rect.Min.x, bar_rect.Max.x - ImMax(window->WindowRounding, window->WindowBorderSize))), IM_ROUND(bar_rect.Max.y));\r\n    clip_rect.ClipWith(window->OuterRectClipped);\r\n    PushClipRect(clip_rect.Min, clip_rect.Max, false);\r\n\r\n    // We overwrite CursorMaxPos because BeginGroup sets it to CursorPos (essentially the .EmitItem hack in EndMenuBar() would need something analogous here, maybe a BeginGroupEx() with flags).\r\n    window->DC.CursorPos = window->DC.CursorMaxPos = ImVec2(bar_rect.Min.x + window->DC.MenuBarOffset.x, bar_rect.Min.y + window->DC.MenuBarOffset.y);\r\n    window->DC.LayoutType = ImGuiLayoutType_Horizontal;\r\n    window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;\r\n    window->DC.MenuBarAppending = true;\r\n    AlignTextToFramePadding();\r\n    return true;\r\n}\r\n\r\nvoid ImGui::EndMenuBar()\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return;\r\n    ImGuiContext& g = *GImGui;\r\n\r\n    // Nav: When a move request within one of our child menu failed, capture the request to navigate among our siblings.\r\n    if (NavMoveRequestButNoResultYet() && (g.NavMoveDir == ImGuiDir_Left || g.NavMoveDir == ImGuiDir_Right) && (g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))\r\n    {\r\n        // Try to find out if the request is for one of our child menu\r\n        ImGuiWindow* nav_earliest_child = g.NavWindow;\r\n        while (nav_earliest_child->ParentWindow && (nav_earliest_child->ParentWindow->Flags & ImGuiWindowFlags_ChildMenu))\r\n            nav_earliest_child = nav_earliest_child->ParentWindow;\r\n        if (nav_earliest_child->ParentWindow == window && nav_earliest_child->DC.ParentLayoutType == ImGuiLayoutType_Horizontal && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded) == 0)\r\n        {\r\n            // To do so we claim focus back, restore NavId and then process the movement request for yet another frame.\r\n            // This involve a one-frame delay which isn't very problematic in this situation. We could remove it by scoring in advance for multiple window (probably not worth bothering)\r\n            const ImGuiNavLayer layer = ImGuiNavLayer_Menu;\r\n            IM_ASSERT(window->DC.NavLayersActiveMaskNext & (1 << layer)); // Sanity check\r\n            FocusWindow(window);\r\n            SetNavID(window->NavLastIds[layer], layer, 0, window->NavRectRel[layer]);\r\n            g.NavDisableHighlight = true; // Hide highlight for the current frame so we don't see the intermediary selection.\r\n            g.NavDisableMouseHover = g.NavMousePosDirty = true;\r\n            NavMoveRequestForward(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags); // Repeat\r\n        }\r\n    }\r\n\r\n    IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive \"warning C6011: Dereferencing NULL pointer 'window'\"\r\n    IM_ASSERT(window->Flags & ImGuiWindowFlags_MenuBar);\r\n    IM_ASSERT(window->DC.MenuBarAppending);\r\n    PopClipRect();\r\n    PopID();\r\n    window->DC.MenuBarOffset.x = window->DC.CursorPos.x - window->Pos.x; // Save horizontal position so next append can reuse it. This is kinda equivalent to a per-layer CursorPos.\r\n    g.GroupStack.back().EmitItem = false;\r\n    EndGroup(); // Restore position on layer 0\r\n    window->DC.LayoutType = ImGuiLayoutType_Vertical;\r\n    window->DC.NavLayerCurrent = ImGuiNavLayer_Main;\r\n    window->DC.MenuBarAppending = false;\r\n}\r\n\r\n// Important: calling order matters!\r\n// FIXME: Somehow overlapping with docking tech.\r\n// FIXME: The \"rect-cut\" aspect of this could be formalized into a lower-level helper (rect-cut: https://halt.software/dead-simple-layouts)\r\nbool ImGui::BeginViewportSideBar(const char* name, ImGuiViewport* viewport_p, ImGuiDir dir, float axis_size, ImGuiWindowFlags window_flags)\r\n{\r\n    IM_ASSERT(dir != ImGuiDir_None);\r\n\r\n    ImGuiWindow* bar_window = FindWindowByName(name);\r\n    if (bar_window == NULL || bar_window->BeginCount == 0)\r\n    {\r\n        // Calculate and set window size/position\r\n        ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)(viewport_p ? viewport_p : GetMainViewport());\r\n        ImRect avail_rect = viewport->GetBuildWorkRect();\r\n        ImGuiAxis axis = (dir == ImGuiDir_Up || dir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;\r\n        ImVec2 pos = avail_rect.Min;\r\n        if (dir == ImGuiDir_Right || dir == ImGuiDir_Down)\r\n            pos[axis] = avail_rect.Max[axis] - axis_size;\r\n        ImVec2 size = avail_rect.GetSize();\r\n        size[axis] = axis_size;\r\n        SetNextWindowPos(pos);\r\n        SetNextWindowSize(size);\r\n\r\n        // Report our size into work area (for next frame) using actual window size\r\n        if (dir == ImGuiDir_Up || dir == ImGuiDir_Left)\r\n            viewport->BuildWorkOffsetMin[axis] += axis_size;\r\n        else if (dir == ImGuiDir_Down || dir == ImGuiDir_Right)\r\n            viewport->BuildWorkOffsetMax[axis] -= axis_size;\r\n    }\r\n\r\n    window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove;\r\n    PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);\r\n    PushStyleVar(ImGuiStyleVar_WindowMinSize, ImVec2(0, 0)); // Lift normal size constraint\r\n    bool is_open = Begin(name, NULL, window_flags);\r\n    PopStyleVar(2);\r\n\r\n    return is_open;\r\n}\r\n\r\nbool ImGui::BeginMainMenuBar()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)GetMainViewport();\r\n\r\n    // For the main menu bar, which cannot be moved, we honor g.Style.DisplaySafeAreaPadding to ensure text can be visible on a TV set.\r\n    // FIXME: This could be generalized as an opt-in way to clamp window->DC.CursorStartPos to avoid SafeArea?\r\n    // FIXME: Consider removing support for safe area down the line... it's messy. Nowadays consoles have support for TV calibration in OS settings.\r\n    g.NextWindowData.MenuBarOffsetMinVal = ImVec2(g.Style.DisplaySafeAreaPadding.x, ImMax(g.Style.DisplaySafeAreaPadding.y - g.Style.FramePadding.y, 0.0f));\r\n    ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_MenuBar;\r\n    float height = GetFrameHeight();\r\n    bool is_open = BeginViewportSideBar(\"##MainMenuBar\", viewport, ImGuiDir_Up, height, window_flags);\r\n    g.NextWindowData.MenuBarOffsetMinVal = ImVec2(0.0f, 0.0f);\r\n\r\n    if (is_open)\r\n        BeginMenuBar();\r\n    else\r\n        End();\r\n    return is_open;\r\n}\r\n\r\nvoid ImGui::EndMainMenuBar()\r\n{\r\n    EndMenuBar();\r\n\r\n    // When the user has left the menu layer (typically: closed menus through activation of an item), we restore focus to the previous window\r\n    // FIXME: With this strategy we won't be able to restore a NULL focus.\r\n    ImGuiContext& g = *GImGui;\r\n    if (g.CurrentWindow == g.NavWindow && g.NavLayer == ImGuiNavLayer_Main && !g.NavAnyRequest)\r\n        FocusTopMostWindowUnderOne(g.NavWindow, NULL);\r\n\r\n    End();\r\n}\r\n\r\nstatic bool IsRootOfOpenMenuSet()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    if ((g.OpenPopupStack.Size <= g.BeginPopupStack.Size) || (window->Flags & ImGuiWindowFlags_ChildMenu))\r\n        return false;\r\n\r\n    // Initially we used 'OpenParentId' to differentiate multiple menu sets from each others (e.g. inside menu bar vs loose menu items) based on parent ID.\r\n    // This would however prevent the use of e.g. PuhsID() user code submitting menus.\r\n    // Previously this worked between popup and a first child menu because the first child menu always had the _ChildWindow flag,\r\n    // making  hovering on parent popup possible while first child menu was focused - but this was generally a bug with other side effects.\r\n    // Instead we don't treat Popup specifically (in order to consistently support menu features in them), maybe the first child menu of a Popup\r\n    // doesn't have the _ChildWindow flag, and we rely on this IsRootOfOpenMenuSet() check to allow hovering between root window/popup and first chilld menu.\r\n    const ImGuiPopupData* upper_popup = &g.OpenPopupStack[g.BeginPopupStack.Size];\r\n    return (/*upper_popup->OpenParentId == window->IDStack.back() &&*/ upper_popup->Window && (upper_popup->Window->Flags & ImGuiWindowFlags_ChildMenu));\r\n}\r\n\r\nbool ImGui::BeginMenuEx(const char* label, const char* icon, bool enabled)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return false;\r\n\r\n    ImGuiContext& g = *GImGui;\r\n    const ImGuiStyle& style = g.Style;\r\n    const ImGuiID id = window->GetID(label);\r\n    bool menu_is_open = IsPopupOpen(id, ImGuiPopupFlags_None);\r\n\r\n    // Sub-menus are ChildWindow so that mouse can be hovering across them (otherwise top-most popup menu would steal focus and not allow hovering on parent menu)\r\n    // The first menu in a hierarchy isn't so hovering doesn't get accross (otherwise e.g. resizing borders with ImGuiButtonFlags_FlattenChildren would react), but top-most BeginMenu() will bypass that limitation.\r\n    ImGuiWindowFlags flags = ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus;\r\n    if (window->Flags & ImGuiWindowFlags_ChildMenu)\r\n        flags |= ImGuiWindowFlags_ChildWindow;\r\n\r\n    // If a menu with same the ID was already submitted, we will append to it, matching the behavior of Begin().\r\n    // We are relying on a O(N) search - so O(N log N) over the frame - which seems like the most efficient for the expected small amount of BeginMenu() calls per frame.\r\n    // If somehow this is ever becoming a problem we can switch to use e.g. ImGuiStorage mapping key to last frame used.\r\n    if (g.MenusIdSubmittedThisFrame.contains(id))\r\n    {\r\n        if (menu_is_open)\r\n            menu_is_open = BeginPopupEx(id, flags); // menu_is_open can be 'false' when the popup is completely clipped (e.g. zero size display)\r\n        else\r\n            g.NextWindowData.ClearFlags();          // we behave like Begin() and need to consume those values\r\n        return menu_is_open;\r\n    }\r\n\r\n    // Tag menu as used. Next time BeginMenu() with same ID is called it will append to existing menu\r\n    g.MenusIdSubmittedThisFrame.push_back(id);\r\n\r\n    ImVec2 label_size = CalcTextSize(label, NULL, true);\r\n\r\n    // Odd hack to allow hovering across menus of a same menu-set (otherwise we wouldn't be able to hover parent without always being a Child window)\r\n    const bool menuset_is_open = IsRootOfOpenMenuSet();\r\n    ImGuiWindow* backed_nav_window = g.NavWindow;\r\n    if (menuset_is_open)\r\n        g.NavWindow = window;\r\n\r\n    // The reference position stored in popup_pos will be used by Begin() to find a suitable position for the child menu,\r\n    // However the final position is going to be different! It is chosen by FindBestWindowPosForPopup().\r\n    // e.g. Menus tend to overlap each other horizontally to amplify relative Z-ordering.\r\n    ImVec2 popup_pos, pos = window->DC.CursorPos;\r\n    PushID(label);\r\n    if (!enabled)\r\n        BeginDisabled();\r\n    const ImGuiMenuColumns* offsets = &window->DC.MenuColumns;\r\n    bool pressed;\r\n    const ImGuiSelectableFlags selectable_flags = ImGuiSelectableFlags_NoHoldingActiveID | ImGuiSelectableFlags_SelectOnClick | ImGuiSelectableFlags_DontClosePopups;\r\n    if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)\r\n    {\r\n        // Menu inside an horizontal menu bar\r\n        // Selectable extend their highlight by half ItemSpacing in each direction.\r\n        // For ChildMenu, the popup position will be overwritten by the call to FindBestWindowPosForPopup() in Begin()\r\n        popup_pos = ImVec2(pos.x - 1.0f - IM_FLOOR(style.ItemSpacing.x * 0.5f), pos.y - style.FramePadding.y + window->MenuBarHeight());\r\n        window->DC.CursorPos.x += IM_FLOOR(style.ItemSpacing.x * 0.5f);\r\n        PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(style.ItemSpacing.x * 2.0f, style.ItemSpacing.y));\r\n        float w = label_size.x;\r\n        ImVec2 text_pos(window->DC.CursorPos.x + offsets->OffsetLabel, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset);\r\n        pressed = Selectable(\"\", menu_is_open, selectable_flags, ImVec2(w, 0.0f));\r\n        RenderText(text_pos, label);\r\n        PopStyleVar();\r\n        window->DC.CursorPos.x += IM_FLOOR(style.ItemSpacing.x * (-1.0f + 0.5f)); // -1 spacing to compensate the spacing added when Selectable() did a SameLine(). It would also work to call SameLine() ourselves after the PopStyleVar().\r\n    }\r\n    else\r\n    {\r\n        // Menu inside a regular/vertical menu\r\n        // (In a typical menu window where all items are BeginMenu() or MenuItem() calls, extra_w will always be 0.0f.\r\n        //  Only when they are other items sticking out we're going to add spacing, yet only register minimum width into the layout system.\r\n        popup_pos = ImVec2(pos.x, pos.y - style.WindowPadding.y);\r\n        float icon_w = (icon && icon[0]) ? CalcTextSize(icon, NULL).x : 0.0f;\r\n        float checkmark_w = IM_FLOOR(g.FontSize * 1.20f);\r\n        float min_w = window->DC.MenuColumns.DeclColumns(icon_w, label_size.x, 0.0f, checkmark_w); // Feedback to next frame\r\n        float extra_w = ImMax(0.0f, GetContentRegionAvail().x - min_w);\r\n        ImVec2 text_pos(window->DC.CursorPos.x + offsets->OffsetLabel, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset);\r\n        pressed = Selectable(\"\", menu_is_open, selectable_flags | ImGuiSelectableFlags_SpanAvailWidth, ImVec2(min_w, 0.0f));\r\n        RenderText(text_pos, label);\r\n        if (icon_w > 0.0f)\r\n            RenderText(pos + ImVec2(offsets->OffsetIcon, 0.0f), icon);\r\n        RenderArrow(window->DrawList, pos + ImVec2(offsets->OffsetMark + extra_w + g.FontSize * 0.30f, 0.0f), GetColorU32(ImGuiCol_Text), ImGuiDir_Right);\r\n    }\r\n    if (!enabled)\r\n        EndDisabled();\r\n\r\n    const bool hovered = (g.HoveredId == id) && enabled;\r\n    if (menuset_is_open)\r\n        g.NavWindow = backed_nav_window;\r\n\r\n    bool want_open = false;\r\n    bool want_close = false;\r\n    if (window->DC.LayoutType == ImGuiLayoutType_Vertical) // (window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu))\r\n    {\r\n        // Close menu when not hovering it anymore unless we are moving roughly in the direction of the menu\r\n        // Implement http://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown to avoid using timers, so menus feels more reactive.\r\n        bool moving_toward_other_child_menu = false;\r\n        ImGuiWindow* child_menu_window = (g.BeginPopupStack.Size < g.OpenPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].SourceWindow == window) ? g.OpenPopupStack[g.BeginPopupStack.Size].Window : NULL;\r\n        if (g.HoveredWindow == window && child_menu_window != NULL && !(window->Flags & ImGuiWindowFlags_MenuBar))\r\n        {\r\n            float ref_unit = g.FontSize; // FIXME-DPI\r\n            ImRect next_window_rect = child_menu_window->Rect();\r\n            ImVec2 ta = (g.IO.MousePos - g.IO.MouseDelta);\r\n            ImVec2 tb = (window->Pos.x < child_menu_window->Pos.x) ? next_window_rect.GetTL() : next_window_rect.GetTR();\r\n            ImVec2 tc = (window->Pos.x < child_menu_window->Pos.x) ? next_window_rect.GetBL() : next_window_rect.GetBR();\r\n            float extra = ImClamp(ImFabs(ta.x - tb.x) * 0.30f, ref_unit * 0.5f, ref_unit * 2.5f);   // add a bit of extra slack.\r\n            ta.x += (window->Pos.x < child_menu_window->Pos.x) ? -0.5f : +0.5f;                     // to avoid numerical issues (FIXME: ??)\r\n            tb.y = ta.y + ImMax((tb.y - extra) - ta.y, -ref_unit * 8.0f);                           // triangle is maximum 200 high to limit the slope and the bias toward large sub-menus // FIXME: Multiply by fb_scale?\r\n            tc.y = ta.y + ImMin((tc.y + extra) - ta.y, +ref_unit * 8.0f);\r\n            moving_toward_other_child_menu = ImTriangleContainsPoint(ta, tb, tc, g.IO.MousePos);\r\n            //GetForegroundDrawList()->AddTriangleFilled(ta, tb, tc, moving_toward_other_child_menu ? IM_COL32(0,128,0,128) : IM_COL32(128,0,0,128)); // [DEBUG]\r\n        }\r\n        if (menu_is_open && !hovered && g.HoveredWindow == window && g.HoveredIdPreviousFrame != 0 && g.HoveredIdPreviousFrame != id && !moving_toward_other_child_menu)\r\n            want_close = true;\r\n\r\n        // Open\r\n        if (!menu_is_open && pressed) // Click/activate to open\r\n            want_open = true;\r\n        else if (!menu_is_open && hovered && !moving_toward_other_child_menu) // Hover to open\r\n            want_open = true;\r\n        if (g.NavId == id && g.NavMoveDir == ImGuiDir_Right) // Nav-Right to open\r\n        {\r\n            want_open = true;\r\n            NavMoveRequestCancel();\r\n        }\r\n    }\r\n    else\r\n    {\r\n        // Menu bar\r\n        if (menu_is_open && pressed && menuset_is_open) // Click an open menu again to close it\r\n        {\r\n            want_close = true;\r\n            want_open = menu_is_open = false;\r\n        }\r\n        else if (pressed || (hovered && menuset_is_open && !menu_is_open)) // First click to open, then hover to open others\r\n        {\r\n            want_open = true;\r\n        }\r\n        else if (g.NavId == id && g.NavMoveDir == ImGuiDir_Down) // Nav-Down to open\r\n        {\r\n            want_open = true;\r\n            NavMoveRequestCancel();\r\n        }\r\n    }\r\n\r\n    if (!enabled) // explicitly close if an open menu becomes disabled, facilitate users code a lot in pattern such as 'if (BeginMenu(\"options\", has_object)) { ..use object.. }'\r\n        want_close = true;\r\n    if (want_close && IsPopupOpen(id, ImGuiPopupFlags_None))\r\n        ClosePopupToLevel(g.BeginPopupStack.Size, true);\r\n\r\n    IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Openable | (menu_is_open ? ImGuiItemStatusFlags_Opened : 0));\r\n    PopID();\r\n\r\n    if (!menu_is_open && want_open && g.OpenPopupStack.Size > g.BeginPopupStack.Size)\r\n    {\r\n        // Don't recycle same menu level in the same frame, first close the other menu and yield for a frame.\r\n        OpenPopup(label);\r\n        return false;\r\n    }\r\n\r\n    menu_is_open |= want_open;\r\n    if (want_open)\r\n        OpenPopup(label);\r\n\r\n    if (menu_is_open)\r\n    {\r\n        SetNextWindowPos(popup_pos, ImGuiCond_Always); // Note: this is super misleading! The value will serve as reference for FindBestWindowPosForPopup(), not actual pos.\r\n        PushStyleVar(ImGuiStyleVar_ChildRounding, style.PopupRounding); // First level will use _PopupRounding, subsequent will use _ChildRounding\r\n        menu_is_open = BeginPopupEx(id, flags); // menu_is_open can be 'false' when the popup is completely clipped (e.g. zero size display)\r\n        PopStyleVar();\r\n    }\r\n    else\r\n    {\r\n        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values\r\n    }\r\n\r\n    return menu_is_open;\r\n}\r\n\r\nbool ImGui::BeginMenu(const char* label, bool enabled)\r\n{\r\n    return BeginMenuEx(label, NULL, enabled);\r\n}\r\n\r\nvoid ImGui::EndMenu()\r\n{\r\n    // Nav: When a left move request _within our child menu_ failed, close ourselves (the _parent_ menu).\r\n    // A menu doesn't close itself because EndMenuBar() wants the catch the last Left<>Right inputs.\r\n    // However, it means that with the current code, a BeginMenu() from outside another menu or a menu-bar won't be closable with the Left direction.\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    if (g.NavMoveDir == ImGuiDir_Left && NavMoveRequestButNoResultYet() && window->DC.LayoutType == ImGuiLayoutType_Vertical)\r\n        if (g.NavWindow && (g.NavWindow->RootWindowForNav->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->RootWindowForNav->ParentWindow == window)\r\n        {\r\n            ClosePopupToLevel(g.BeginPopupStack.Size, true);\r\n            NavMoveRequestCancel();\r\n        }\r\n\r\n    EndPopup();\r\n}\r\n\r\nbool ImGui::MenuItemEx(const char* label, const char* icon, const char* shortcut, bool selected, bool enabled)\r\n{\r\n    ImGuiWindow* window = GetCurrentWindow();\r\n    if (window->SkipItems)\r\n        return false;\r\n\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiStyle& style = g.Style;\r\n    ImVec2 pos = window->DC.CursorPos;\r\n    ImVec2 label_size = CalcTextSize(label, NULL, true);\r\n\r\n    const bool menuset_is_open = IsRootOfOpenMenuSet();\r\n    ImGuiWindow* backed_nav_window = g.NavWindow;\r\n    if (menuset_is_open)\r\n        g.NavWindow = window;\r\n\r\n    // We've been using the equivalent of ImGuiSelectableFlags_SetNavIdOnHover on all Selectable() since early Nav system days (commit 43ee5d73),\r\n    // but I am unsure whether this should be kept at all. For now moved it to be an opt-in feature used by menus only.\r\n    bool pressed;\r\n    PushID(label);\r\n    if (!enabled)\r\n        BeginDisabled();\r\n\r\n    const ImGuiSelectableFlags selectable_flags = ImGuiSelectableFlags_SelectOnRelease | ImGuiSelectableFlags_SetNavIdOnHover;\r\n    const ImGuiMenuColumns* offsets = &window->DC.MenuColumns;\r\n    if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)\r\n    {\r\n        // Mimic the exact layout spacing of BeginMenu() to allow MenuItem() inside a menu bar, which is a little misleading but may be useful\r\n        // Note that in this situation: we don't render the shortcut, we render a highlight instead of the selected tick mark.\r\n        float w = label_size.x;\r\n        window->DC.CursorPos.x += IM_FLOOR(style.ItemSpacing.x * 0.5f);\r\n        ImVec2 text_pos(window->DC.CursorPos.x + offsets->OffsetLabel, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset);\r\n        PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(style.ItemSpacing.x * 2.0f, style.ItemSpacing.y));\r\n        pressed = Selectable(\"\", selected, selectable_flags, ImVec2(w, 0.0f));\r\n        PopStyleVar();\r\n        RenderText(text_pos, label);\r\n        window->DC.CursorPos.x += IM_FLOOR(style.ItemSpacing.x * (-1.0f + 0.5f)); // -1 spacing to compensate the spacing added when Selectable() did a SameLine(). It would also work to call SameLine() ourselves after the PopStyleVar().\r\n    }\r\n    else\r\n    {\r\n        // Menu item inside a vertical menu\r\n        // (In a typical menu window where all items are BeginMenu() or MenuItem() calls, extra_w will always be 0.0f.\r\n        //  Only when they are other items sticking out we're going to add spacing, yet only register minimum width into the layout system.\r\n        float icon_w = (icon && icon[0]) ? CalcTextSize(icon, NULL).x : 0.0f;\r\n        float shortcut_w = (shortcut && shortcut[0]) ? CalcTextSize(shortcut, NULL).x : 0.0f;\r\n        float checkmark_w = IM_FLOOR(g.FontSize * 1.20f);\r\n        float min_w = window->DC.MenuColumns.DeclColumns(icon_w, label_size.x, shortcut_w, checkmark_w); // Feedback for next frame\r\n        float stretch_w = ImMax(0.0f, GetContentRegionAvail().x - min_w);\r\n        pressed = Selectable(\"\", false, selectable_flags | ImGuiSelectableFlags_SpanAvailWidth, ImVec2(min_w, 0.0f));\r\n        RenderText(pos + ImVec2(offsets->OffsetLabel, 0.0f), label);\r\n        if (icon_w > 0.0f)\r\n            RenderText(pos + ImVec2(offsets->OffsetIcon, 0.0f), icon);\r\n        if (shortcut_w > 0.0f)\r\n        {\r\n            PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]);\r\n            RenderText(pos + ImVec2(offsets->OffsetShortcut + stretch_w, 0.0f), shortcut, NULL, false);\r\n            PopStyleColor();\r\n        }\r\n        if (selected)\r\n            RenderCheckMark(window->DrawList, pos + ImVec2(offsets->OffsetMark + stretch_w + g.FontSize * 0.40f, g.FontSize * 0.134f * 0.5f), GetColorU32(ImGuiCol_Text), g.FontSize  * 0.866f);\r\n    }\r\n    IMGUI_TEST_ENGINE_ITEM_INFO(g.LastItemData.ID, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Checkable | (selected ? ImGuiItemStatusFlags_Checked : 0));\r\n    if (!enabled)\r\n        EndDisabled();\r\n    PopID();\r\n    if (menuset_is_open)\r\n        g.NavWindow = backed_nav_window;\r\n\r\n    return pressed;\r\n}\r\n\r\nbool ImGui::MenuItem(const char* label, const char* shortcut, bool selected, bool enabled)\r\n{\r\n    return MenuItemEx(label, NULL, shortcut, selected, enabled);\r\n}\r\n\r\nbool ImGui::MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled)\r\n{\r\n    if (MenuItemEx(label, NULL, shortcut, p_selected ? *p_selected : false, enabled))\r\n    {\r\n        if (p_selected)\r\n            *p_selected = !*p_selected;\r\n        return true;\r\n    }\r\n    return false;\r\n}\r\n\r\n//-------------------------------------------------------------------------\r\n// [SECTION] Widgets: BeginTabBar, EndTabBar, etc.\r\n//-------------------------------------------------------------------------\r\n// - BeginTabBar()\r\n// - BeginTabBarEx() [Internal]\r\n// - EndTabBar()\r\n// - TabBarLayout() [Internal]\r\n// - TabBarCalcTabID() [Internal]\r\n// - TabBarCalcMaxTabWidth() [Internal]\r\n// - TabBarFindTabById() [Internal]\r\n// - TabBarRemoveTab() [Internal]\r\n// - TabBarCloseTab() [Internal]\r\n// - TabBarScrollClamp() [Internal]\r\n// - TabBarScrollToTab() [Internal]\r\n// - TabBarQueueChangeTabOrder() [Internal]\r\n// - TabBarScrollingButtons() [Internal]\r\n// - TabBarTabListPopupButton() [Internal]\r\n//-------------------------------------------------------------------------\r\n\r\nstruct ImGuiTabBarSection\r\n{\r\n    int                 TabCount;               // Number of tabs in this section.\r\n    float               Width;                  // Sum of width of tabs in this section (after shrinking down)\r\n    float               Spacing;                // Horizontal spacing at the end of the section.\r\n\r\n    ImGuiTabBarSection() { memset(this, 0, sizeof(*this)); }\r\n};\r\n\r\nnamespace ImGui\r\n{\r\n    static void             TabBarLayout(ImGuiTabBar* tab_bar);\r\n    static ImU32            TabBarCalcTabID(ImGuiTabBar* tab_bar, const char* label);\r\n    static float            TabBarCalcMaxTabWidth();\r\n    static float            TabBarScrollClamp(ImGuiTabBar* tab_bar, float scrolling);\r\n    static void             TabBarScrollToTab(ImGuiTabBar* tab_bar, ImGuiID tab_id, ImGuiTabBarSection* sections);\r\n    static ImGuiTabItem*    TabBarScrollingButtons(ImGuiTabBar* tab_bar);\r\n    static ImGuiTabItem*    TabBarTabListPopupButton(ImGuiTabBar* tab_bar);\r\n}\r\n\r\nImGuiTabBar::ImGuiTabBar()\r\n{\r\n    memset(this, 0, sizeof(*this));\r\n    CurrFrameVisible = PrevFrameVisible = -1;\r\n    LastTabItemIdx = -1;\r\n}\r\n\r\nstatic inline int TabItemGetSectionIdx(const ImGuiTabItem* tab)\r\n{\r\n    return (tab->Flags & ImGuiTabItemFlags_Leading) ? 0 : (tab->Flags & ImGuiTabItemFlags_Trailing) ? 2 : 1;\r\n}\r\n\r\nstatic int IMGUI_CDECL TabItemComparerBySection(const void* lhs, const void* rhs)\r\n{\r\n    const ImGuiTabItem* a = (const ImGuiTabItem*)lhs;\r\n    const ImGuiTabItem* b = (const ImGuiTabItem*)rhs;\r\n    const int a_section = TabItemGetSectionIdx(a);\r\n    const int b_section = TabItemGetSectionIdx(b);\r\n    if (a_section != b_section)\r\n        return a_section - b_section;\r\n    return (int)(a->IndexDuringLayout - b->IndexDuringLayout);\r\n}\r\n\r\nstatic int IMGUI_CDECL TabItemComparerByBeginOrder(const void* lhs, const void* rhs)\r\n{\r\n    const ImGuiTabItem* a = (const ImGuiTabItem*)lhs;\r\n    const ImGuiTabItem* b = (const ImGuiTabItem*)rhs;\r\n    return (int)(a->BeginOrder - b->BeginOrder);\r\n}\r\n\r\nstatic ImGuiTabBar* GetTabBarFromTabBarRef(const ImGuiPtrOrIndex& ref)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    return ref.Ptr ? (ImGuiTabBar*)ref.Ptr : g.TabBars.GetByIndex(ref.Index);\r\n}\r\n\r\nstatic ImGuiPtrOrIndex GetTabBarRefFromTabBar(ImGuiTabBar* tab_bar)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    if (g.TabBars.Contains(tab_bar))\r\n        return ImGuiPtrOrIndex(g.TabBars.GetIndex(tab_bar));\r\n    return ImGuiPtrOrIndex(tab_bar);\r\n}\r\n\r\nbool    ImGui::BeginTabBar(const char* str_id, ImGuiTabBarFlags flags)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    if (window->SkipItems)\r\n        return false;\r\n\r\n    ImGuiID id = window->GetID(str_id);\r\n    ImGuiTabBar* tab_bar = g.TabBars.GetOrAddByKey(id);\r\n    ImRect tab_bar_bb = ImRect(window->DC.CursorPos.x, window->DC.CursorPos.y, window->WorkRect.Max.x, window->DC.CursorPos.y + g.FontSize + g.Style.FramePadding.y * 2);\r\n    tab_bar->ID = id;\r\n    return BeginTabBarEx(tab_bar, tab_bar_bb, flags | ImGuiTabBarFlags_IsFocused);\r\n}\r\n\r\nbool    ImGui::BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& tab_bar_bb, ImGuiTabBarFlags flags)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    if (window->SkipItems)\r\n        return false;\r\n\r\n    if ((flags & ImGuiTabBarFlags_DockNode) == 0)\r\n        PushOverrideID(tab_bar->ID);\r\n\r\n    // Add to stack\r\n    g.CurrentTabBarStack.push_back(GetTabBarRefFromTabBar(tab_bar));\r\n    g.CurrentTabBar = tab_bar;\r\n\r\n    // Append with multiple BeginTabBar()/EndTabBar() pairs.\r\n    tab_bar->BackupCursorPos = window->DC.CursorPos;\r\n    if (tab_bar->CurrFrameVisible == g.FrameCount)\r\n    {\r\n        window->DC.CursorPos = ImVec2(tab_bar->BarRect.Min.x, tab_bar->BarRect.Max.y + tab_bar->ItemSpacingY);\r\n        tab_bar->BeginCount++;\r\n        return true;\r\n    }\r\n\r\n    // Ensure correct ordering when toggling ImGuiTabBarFlags_Reorderable flag, or when a new tab was added while being not reorderable\r\n    if ((flags & ImGuiTabBarFlags_Reorderable) != (tab_bar->Flags & ImGuiTabBarFlags_Reorderable) || (tab_bar->TabsAddedNew && !(flags & ImGuiTabBarFlags_Reorderable)))\r\n        ImQsort(tab_bar->Tabs.Data, tab_bar->Tabs.Size, sizeof(ImGuiTabItem), TabItemComparerByBeginOrder);\r\n    tab_bar->TabsAddedNew = false;\r\n\r\n    // Flags\r\n    if ((flags & ImGuiTabBarFlags_FittingPolicyMask_) == 0)\r\n        flags |= ImGuiTabBarFlags_FittingPolicyDefault_;\r\n\r\n    tab_bar->Flags = flags;\r\n    tab_bar->BarRect = tab_bar_bb;\r\n    tab_bar->WantLayout = true; // Layout will be done on the first call to ItemTab()\r\n    tab_bar->PrevFrameVisible = tab_bar->CurrFrameVisible;\r\n    tab_bar->CurrFrameVisible = g.FrameCount;\r\n    tab_bar->PrevTabsContentsHeight = tab_bar->CurrTabsContentsHeight;\r\n    tab_bar->CurrTabsContentsHeight = 0.0f;\r\n    tab_bar->ItemSpacingY = g.Style.ItemSpacing.y;\r\n    tab_bar->FramePadding = g.Style.FramePadding;\r\n    tab_bar->TabsActiveCount = 0;\r\n    tab_bar->BeginCount = 1;\r\n\r\n    // Set cursor pos in a way which only be used in the off-chance the user erroneously submits item before BeginTabItem(): items will overlap\r\n    window->DC.CursorPos = ImVec2(tab_bar->BarRect.Min.x, tab_bar->BarRect.Max.y + tab_bar->ItemSpacingY);\r\n\r\n    // Draw separator\r\n    const ImU32 col = GetColorU32((flags & ImGuiTabBarFlags_IsFocused) ? ImGuiCol_TabActive : ImGuiCol_TabUnfocusedActive);\r\n    const float y = tab_bar->BarRect.Max.y - 1.0f;\r\n    {\r\n        const float separator_min_x = tab_bar->BarRect.Min.x - IM_FLOOR(window->WindowPadding.x * 0.5f);\r\n        const float separator_max_x = tab_bar->BarRect.Max.x + IM_FLOOR(window->WindowPadding.x * 0.5f);\r\n        window->DrawList->AddLine(ImVec2(separator_min_x, y), ImVec2(separator_max_x, y), col, 1.0f);\r\n    }\r\n    return true;\r\n}\r\n\r\nvoid    ImGui::EndTabBar()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    if (window->SkipItems)\r\n        return;\r\n\r\n    ImGuiTabBar* tab_bar = g.CurrentTabBar;\r\n    if (tab_bar == NULL)\r\n    {\r\n        IM_ASSERT_USER_ERROR(tab_bar != NULL, \"Mismatched BeginTabBar()/EndTabBar()!\");\r\n        return;\r\n    }\r\n\r\n    // Fallback in case no TabItem have been submitted\r\n    if (tab_bar->WantLayout)\r\n        TabBarLayout(tab_bar);\r\n\r\n    // Restore the last visible height if no tab is visible, this reduce vertical flicker/movement when a tabs gets removed without calling SetTabItemClosed().\r\n    const bool tab_bar_appearing = (tab_bar->PrevFrameVisible + 1 < g.FrameCount);\r\n    if (tab_bar->VisibleTabWasSubmitted || tab_bar->VisibleTabId == 0 || tab_bar_appearing)\r\n    {\r\n        tab_bar->CurrTabsContentsHeight = ImMax(window->DC.CursorPos.y - tab_bar->BarRect.Max.y, tab_bar->CurrTabsContentsHeight);\r\n        window->DC.CursorPos.y = tab_bar->BarRect.Max.y + tab_bar->CurrTabsContentsHeight;\r\n    }\r\n    else\r\n    {\r\n        window->DC.CursorPos.y = tab_bar->BarRect.Max.y + tab_bar->PrevTabsContentsHeight;\r\n    }\r\n    if (tab_bar->BeginCount > 1)\r\n        window->DC.CursorPos = tab_bar->BackupCursorPos;\r\n\r\n    if ((tab_bar->Flags & ImGuiTabBarFlags_DockNode) == 0)\r\n        PopID();\r\n\r\n    g.CurrentTabBarStack.pop_back();\r\n    g.CurrentTabBar = g.CurrentTabBarStack.empty() ? NULL : GetTabBarFromTabBarRef(g.CurrentTabBarStack.back());\r\n}\r\n\r\n// This is called only once a frame before by the first call to ItemTab()\r\n// The reason we're not calling it in BeginTabBar() is to leave a chance to the user to call the SetTabItemClosed() functions.\r\nstatic void ImGui::TabBarLayout(ImGuiTabBar* tab_bar)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    tab_bar->WantLayout = false;\r\n\r\n    // Garbage collect by compacting list\r\n    // Detect if we need to sort out tab list (e.g. in rare case where a tab changed section)\r\n    int tab_dst_n = 0;\r\n    bool need_sort_by_section = false;\r\n    ImGuiTabBarSection sections[3]; // Layout sections: Leading, Central, Trailing\r\n    for (int tab_src_n = 0; tab_src_n < tab_bar->Tabs.Size; tab_src_n++)\r\n    {\r\n        ImGuiTabItem* tab = &tab_bar->Tabs[tab_src_n];\r\n        if (tab->LastFrameVisible < tab_bar->PrevFrameVisible || tab->WantClose)\r\n        {\r\n            // Remove tab\r\n            if (tab_bar->VisibleTabId == tab->ID) { tab_bar->VisibleTabId = 0; }\r\n            if (tab_bar->SelectedTabId == tab->ID) { tab_bar->SelectedTabId = 0; }\r\n            if (tab_bar->NextSelectedTabId == tab->ID) { tab_bar->NextSelectedTabId = 0; }\r\n            continue;\r\n        }\r\n        if (tab_dst_n != tab_src_n)\r\n            tab_bar->Tabs[tab_dst_n] = tab_bar->Tabs[tab_src_n];\r\n\r\n        tab = &tab_bar->Tabs[tab_dst_n];\r\n        tab->IndexDuringLayout = (ImS16)tab_dst_n;\r\n\r\n        // We will need sorting if tabs have changed section (e.g. moved from one of Leading/Central/Trailing to another)\r\n        int curr_tab_section_n = TabItemGetSectionIdx(tab);\r\n        if (tab_dst_n > 0)\r\n        {\r\n            ImGuiTabItem* prev_tab = &tab_bar->Tabs[tab_dst_n - 1];\r\n            int prev_tab_section_n = TabItemGetSectionIdx(prev_tab);\r\n            if (curr_tab_section_n == 0 && prev_tab_section_n != 0)\r\n                need_sort_by_section = true;\r\n            if (prev_tab_section_n == 2 && curr_tab_section_n != 2)\r\n                need_sort_by_section = true;\r\n        }\r\n\r\n        sections[curr_tab_section_n].TabCount++;\r\n        tab_dst_n++;\r\n    }\r\n    if (tab_bar->Tabs.Size != tab_dst_n)\r\n        tab_bar->Tabs.resize(tab_dst_n);\r\n\r\n    if (need_sort_by_section)\r\n        ImQsort(tab_bar->Tabs.Data, tab_bar->Tabs.Size, sizeof(ImGuiTabItem), TabItemComparerBySection);\r\n\r\n    // Calculate spacing between sections\r\n    sections[0].Spacing = sections[0].TabCount > 0 && (sections[1].TabCount + sections[2].TabCount) > 0 ? g.Style.ItemInnerSpacing.x : 0.0f;\r\n    sections[1].Spacing = sections[1].TabCount > 0 && sections[2].TabCount > 0 ? g.Style.ItemInnerSpacing.x : 0.0f;\r\n\r\n    // Setup next selected tab\r\n    ImGuiID scroll_to_tab_id = 0;\r\n    if (tab_bar->NextSelectedTabId)\r\n    {\r\n        tab_bar->SelectedTabId = tab_bar->NextSelectedTabId;\r\n        tab_bar->NextSelectedTabId = 0;\r\n        scroll_to_tab_id = tab_bar->SelectedTabId;\r\n    }\r\n\r\n    // Process order change request (we could probably process it when requested but it's just saner to do it in a single spot).\r\n    if (tab_bar->ReorderRequestTabId != 0)\r\n    {\r\n        if (TabBarProcessReorder(tab_bar))\r\n            if (tab_bar->ReorderRequestTabId == tab_bar->SelectedTabId)\r\n                scroll_to_tab_id = tab_bar->ReorderRequestTabId;\r\n        tab_bar->ReorderRequestTabId = 0;\r\n    }\r\n\r\n    // Tab List Popup (will alter tab_bar->BarRect and therefore the available width!)\r\n    const bool tab_list_popup_button = (tab_bar->Flags & ImGuiTabBarFlags_TabListPopupButton) != 0;\r\n    if (tab_list_popup_button)\r\n        if (ImGuiTabItem* tab_to_select = TabBarTabListPopupButton(tab_bar)) // NB: Will alter BarRect.Min.x!\r\n            scroll_to_tab_id = tab_bar->SelectedTabId = tab_to_select->ID;\r\n\r\n    // Leading/Trailing tabs will be shrink only if central one aren't visible anymore, so layout the shrink data as: leading, trailing, central\r\n    // (whereas our tabs are stored as: leading, central, trailing)\r\n    int shrink_buffer_indexes[3] = { 0, sections[0].TabCount + sections[2].TabCount, sections[0].TabCount };\r\n    g.ShrinkWidthBuffer.resize(tab_bar->Tabs.Size);\r\n\r\n    // Compute ideal tabs widths + store them into shrink buffer\r\n    ImGuiTabItem* most_recently_selected_tab = NULL;\r\n    int curr_section_n = -1;\r\n    bool found_selected_tab_id = false;\r\n    for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)\r\n    {\r\n        ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];\r\n        IM_ASSERT(tab->LastFrameVisible >= tab_bar->PrevFrameVisible);\r\n\r\n        if ((most_recently_selected_tab == NULL || most_recently_selected_tab->LastFrameSelected < tab->LastFrameSelected) && !(tab->Flags & ImGuiTabItemFlags_Button))\r\n            most_recently_selected_tab = tab;\r\n        if (tab->ID == tab_bar->SelectedTabId)\r\n            found_selected_tab_id = true;\r\n        if (scroll_to_tab_id == 0 && g.NavJustMovedToId == tab->ID)\r\n            scroll_to_tab_id = tab->ID;\r\n\r\n        // Refresh tab width immediately, otherwise changes of style e.g. style.FramePadding.x would noticeably lag in the tab bar.\r\n        // Additionally, when using TabBarAddTab() to manipulate tab bar order we occasionally insert new tabs that don't have a width yet,\r\n        // and we cannot wait for the next BeginTabItem() call. We cannot compute this width within TabBarAddTab() because font size depends on the active window.\r\n        const char* tab_name = tab_bar->GetTabName(tab);\r\n        const bool has_close_button = (tab->Flags & ImGuiTabItemFlags_NoCloseButton) ? false : true;\r\n        tab->ContentWidth = TabItemCalcSize(tab_name, has_close_button).x;\r\n\r\n        int section_n = TabItemGetSectionIdx(tab);\r\n        ImGuiTabBarSection* section = &sections[section_n];\r\n        section->Width += tab->ContentWidth + (section_n == curr_section_n ? g.Style.ItemInnerSpacing.x : 0.0f);\r\n        curr_section_n = section_n;\r\n\r\n        // Store data so we can build an array sorted by width if we need to shrink tabs down\r\n        IM_MSVC_WARNING_SUPPRESS(6385);\r\n        int shrink_buffer_index = shrink_buffer_indexes[section_n]++;\r\n        g.ShrinkWidthBuffer[shrink_buffer_index].Index = tab_n;\r\n        g.ShrinkWidthBuffer[shrink_buffer_index].Width = tab->ContentWidth;\r\n\r\n        IM_ASSERT(tab->ContentWidth > 0.0f);\r\n        tab->Width = tab->ContentWidth;\r\n    }\r\n\r\n    // Compute total ideal width (used for e.g. auto-resizing a window)\r\n    tab_bar->WidthAllTabsIdeal = 0.0f;\r\n    for (int section_n = 0; section_n < 3; section_n++)\r\n        tab_bar->WidthAllTabsIdeal += sections[section_n].Width + sections[section_n].Spacing;\r\n\r\n    // Horizontal scrolling buttons\r\n    // (note that TabBarScrollButtons() will alter BarRect.Max.x)\r\n    if ((tab_bar->WidthAllTabsIdeal > tab_bar->BarRect.GetWidth() && tab_bar->Tabs.Size > 1) && !(tab_bar->Flags & ImGuiTabBarFlags_NoTabListScrollingButtons) && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll))\r\n        if (ImGuiTabItem* scroll_and_select_tab = TabBarScrollingButtons(tab_bar))\r\n        {\r\n            scroll_to_tab_id = scroll_and_select_tab->ID;\r\n            if ((scroll_and_select_tab->Flags & ImGuiTabItemFlags_Button) == 0)\r\n                tab_bar->SelectedTabId = scroll_to_tab_id;\r\n        }\r\n\r\n    // Shrink widths if full tabs don't fit in their allocated space\r\n    float section_0_w = sections[0].Width + sections[0].Spacing;\r\n    float section_1_w = sections[1].Width + sections[1].Spacing;\r\n    float section_2_w = sections[2].Width + sections[2].Spacing;\r\n    bool central_section_is_visible = (section_0_w + section_2_w) < tab_bar->BarRect.GetWidth();\r\n    float width_excess;\r\n    if (central_section_is_visible)\r\n        width_excess = ImMax(section_1_w - (tab_bar->BarRect.GetWidth() - section_0_w - section_2_w), 0.0f); // Excess used to shrink central section\r\n    else\r\n        width_excess = (section_0_w + section_2_w) - tab_bar->BarRect.GetWidth(); // Excess used to shrink leading/trailing section\r\n\r\n    // With ImGuiTabBarFlags_FittingPolicyScroll policy, we will only shrink leading/trailing if the central section is not visible anymore\r\n    if (width_excess > 0.0f && ((tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyResizeDown) || !central_section_is_visible))\r\n    {\r\n        int shrink_data_count = (central_section_is_visible ? sections[1].TabCount : sections[0].TabCount + sections[2].TabCount);\r\n        int shrink_data_offset = (central_section_is_visible ? sections[0].TabCount + sections[2].TabCount : 0);\r\n        ShrinkWidths(g.ShrinkWidthBuffer.Data + shrink_data_offset, shrink_data_count, width_excess);\r\n\r\n        // Apply shrunk values into tabs and sections\r\n        for (int tab_n = shrink_data_offset; tab_n < shrink_data_offset + shrink_data_count; tab_n++)\r\n        {\r\n            ImGuiTabItem* tab = &tab_bar->Tabs[g.ShrinkWidthBuffer[tab_n].Index];\r\n            float shrinked_width = IM_FLOOR(g.ShrinkWidthBuffer[tab_n].Width);\r\n            if (shrinked_width < 0.0f)\r\n                continue;\r\n\r\n            int section_n = TabItemGetSectionIdx(tab);\r\n            sections[section_n].Width -= (tab->Width - shrinked_width);\r\n            tab->Width = shrinked_width;\r\n        }\r\n    }\r\n\r\n    // Layout all active tabs\r\n    int section_tab_index = 0;\r\n    float tab_offset = 0.0f;\r\n    tab_bar->WidthAllTabs = 0.0f;\r\n    for (int section_n = 0; section_n < 3; section_n++)\r\n    {\r\n        ImGuiTabBarSection* section = &sections[section_n];\r\n        if (section_n == 2)\r\n            tab_offset = ImMin(ImMax(0.0f, tab_bar->BarRect.GetWidth() - section->Width), tab_offset);\r\n\r\n        for (int tab_n = 0; tab_n < section->TabCount; tab_n++)\r\n        {\r\n            ImGuiTabItem* tab = &tab_bar->Tabs[section_tab_index + tab_n];\r\n            tab->Offset = tab_offset;\r\n            tab_offset += tab->Width + (tab_n < section->TabCount - 1 ? g.Style.ItemInnerSpacing.x : 0.0f);\r\n        }\r\n        tab_bar->WidthAllTabs += ImMax(section->Width + section->Spacing, 0.0f);\r\n        tab_offset += section->Spacing;\r\n        section_tab_index += section->TabCount;\r\n    }\r\n\r\n    // If we have lost the selected tab, select the next most recently active one\r\n    if (found_selected_tab_id == false)\r\n        tab_bar->SelectedTabId = 0;\r\n    if (tab_bar->SelectedTabId == 0 && tab_bar->NextSelectedTabId == 0 && most_recently_selected_tab != NULL)\r\n        scroll_to_tab_id = tab_bar->SelectedTabId = most_recently_selected_tab->ID;\r\n\r\n    // Lock in visible tab\r\n    tab_bar->VisibleTabId = tab_bar->SelectedTabId;\r\n    tab_bar->VisibleTabWasSubmitted = false;\r\n\r\n    // Update scrolling\r\n    if (scroll_to_tab_id != 0)\r\n        TabBarScrollToTab(tab_bar, scroll_to_tab_id, sections);\r\n    tab_bar->ScrollingAnim = TabBarScrollClamp(tab_bar, tab_bar->ScrollingAnim);\r\n    tab_bar->ScrollingTarget = TabBarScrollClamp(tab_bar, tab_bar->ScrollingTarget);\r\n    if (tab_bar->ScrollingAnim != tab_bar->ScrollingTarget)\r\n    {\r\n        // Scrolling speed adjust itself so we can always reach our target in 1/3 seconds.\r\n        // Teleport if we are aiming far off the visible line\r\n        tab_bar->ScrollingSpeed = ImMax(tab_bar->ScrollingSpeed, 70.0f * g.FontSize);\r\n        tab_bar->ScrollingSpeed = ImMax(tab_bar->ScrollingSpeed, ImFabs(tab_bar->ScrollingTarget - tab_bar->ScrollingAnim) / 0.3f);\r\n        const bool teleport = (tab_bar->PrevFrameVisible + 1 < g.FrameCount) || (tab_bar->ScrollingTargetDistToVisibility > 10.0f * g.FontSize);\r\n        tab_bar->ScrollingAnim = teleport ? tab_bar->ScrollingTarget : ImLinearSweep(tab_bar->ScrollingAnim, tab_bar->ScrollingTarget, g.IO.DeltaTime * tab_bar->ScrollingSpeed);\r\n    }\r\n    else\r\n    {\r\n        tab_bar->ScrollingSpeed = 0.0f;\r\n    }\r\n    tab_bar->ScrollingRectMinX = tab_bar->BarRect.Min.x + sections[0].Width + sections[0].Spacing;\r\n    tab_bar->ScrollingRectMaxX = tab_bar->BarRect.Max.x - sections[2].Width - sections[1].Spacing;\r\n\r\n    // Clear name buffers\r\n    if ((tab_bar->Flags & ImGuiTabBarFlags_DockNode) == 0)\r\n        tab_bar->TabsNames.Buf.resize(0);\r\n\r\n    // Actual layout in host window (we don't do it in BeginTabBar() so as not to waste an extra frame)\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    window->DC.CursorPos = tab_bar->BarRect.Min;\r\n    ItemSize(ImVec2(tab_bar->WidthAllTabs, tab_bar->BarRect.GetHeight()), tab_bar->FramePadding.y);\r\n    window->DC.IdealMaxPos.x = ImMax(window->DC.IdealMaxPos.x, tab_bar->BarRect.Min.x + tab_bar->WidthAllTabsIdeal);\r\n}\r\n\r\n// Dockables uses Name/ID in the global namespace. Non-dockable items use the ID stack.\r\nstatic ImU32   ImGui::TabBarCalcTabID(ImGuiTabBar* tab_bar, const char* label)\r\n{\r\n    if (tab_bar->Flags & ImGuiTabBarFlags_DockNode)\r\n    {\r\n        ImGuiID id = ImHashStr(label);\r\n        KeepAliveID(id);\r\n        return id;\r\n    }\r\n    else\r\n    {\r\n        ImGuiWindow* window = GImGui->CurrentWindow;\r\n        return window->GetID(label);\r\n    }\r\n}\r\n\r\nstatic float ImGui::TabBarCalcMaxTabWidth()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    return g.FontSize * 20.0f;\r\n}\r\n\r\nImGuiTabItem* ImGui::TabBarFindTabByID(ImGuiTabBar* tab_bar, ImGuiID tab_id)\r\n{\r\n    if (tab_id != 0)\r\n        for (int n = 0; n < tab_bar->Tabs.Size; n++)\r\n            if (tab_bar->Tabs[n].ID == tab_id)\r\n                return &tab_bar->Tabs[n];\r\n    return NULL;\r\n}\r\n\r\n// The *TabId fields be already set by the docking system _before_ the actual TabItem was created, so we clear them regardless.\r\nvoid ImGui::TabBarRemoveTab(ImGuiTabBar* tab_bar, ImGuiID tab_id)\r\n{\r\n    if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_id))\r\n        tab_bar->Tabs.erase(tab);\r\n    if (tab_bar->VisibleTabId == tab_id)      { tab_bar->VisibleTabId = 0; }\r\n    if (tab_bar->SelectedTabId == tab_id)     { tab_bar->SelectedTabId = 0; }\r\n    if (tab_bar->NextSelectedTabId == tab_id) { tab_bar->NextSelectedTabId = 0; }\r\n}\r\n\r\n// Called on manual closure attempt\r\nvoid ImGui::TabBarCloseTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab)\r\n{\r\n    IM_ASSERT(!(tab->Flags & ImGuiTabItemFlags_Button));\r\n    if (!(tab->Flags & ImGuiTabItemFlags_UnsavedDocument))\r\n    {\r\n        // This will remove a frame of lag for selecting another tab on closure.\r\n        // However we don't run it in the case where the 'Unsaved' flag is set, so user gets a chance to fully undo the closure\r\n        tab->WantClose = true;\r\n        if (tab_bar->VisibleTabId == tab->ID)\r\n        {\r\n            tab->LastFrameVisible = -1;\r\n            tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = 0;\r\n        }\r\n    }\r\n    else\r\n    {\r\n        // Actually select before expecting closure attempt (on an UnsavedDocument tab user is expect to e.g. show a popup)\r\n        if (tab_bar->VisibleTabId != tab->ID)\r\n            tab_bar->NextSelectedTabId = tab->ID;\r\n    }\r\n}\r\n\r\nstatic float ImGui::TabBarScrollClamp(ImGuiTabBar* tab_bar, float scrolling)\r\n{\r\n    scrolling = ImMin(scrolling, tab_bar->WidthAllTabs - tab_bar->BarRect.GetWidth());\r\n    return ImMax(scrolling, 0.0f);\r\n}\r\n\r\n// Note: we may scroll to tab that are not selected! e.g. using keyboard arrow keys\r\nstatic void ImGui::TabBarScrollToTab(ImGuiTabBar* tab_bar, ImGuiID tab_id, ImGuiTabBarSection* sections)\r\n{\r\n    ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_id);\r\n    if (tab == NULL)\r\n        return;\r\n    if (tab->Flags & ImGuiTabItemFlags_SectionMask_)\r\n        return;\r\n\r\n    ImGuiContext& g = *GImGui;\r\n    float margin = g.FontSize * 1.0f; // When to scroll to make Tab N+1 visible always make a bit of N visible to suggest more scrolling area (since we don't have a scrollbar)\r\n    int order = tab_bar->GetTabOrder(tab);\r\n\r\n    // Scrolling happens only in the central section (leading/trailing sections are not scrolling)\r\n    // FIXME: This is all confusing.\r\n    float scrollable_width = tab_bar->BarRect.GetWidth() - sections[0].Width - sections[2].Width - sections[1].Spacing;\r\n\r\n    // We make all tabs positions all relative Sections[0].Width to make code simpler\r\n    float tab_x1 = tab->Offset - sections[0].Width + (order > sections[0].TabCount - 1 ? -margin : 0.0f);\r\n    float tab_x2 = tab->Offset - sections[0].Width + tab->Width + (order + 1 < tab_bar->Tabs.Size - sections[2].TabCount ? margin : 1.0f);\r\n    tab_bar->ScrollingTargetDistToVisibility = 0.0f;\r\n    if (tab_bar->ScrollingTarget > tab_x1 || (tab_x2 - tab_x1 >= scrollable_width))\r\n    {\r\n        // Scroll to the left\r\n        tab_bar->ScrollingTargetDistToVisibility = ImMax(tab_bar->ScrollingAnim - tab_x2, 0.0f);\r\n        tab_bar->ScrollingTarget = tab_x1;\r\n    }\r\n    else if (tab_bar->ScrollingTarget < tab_x2 - scrollable_width)\r\n    {\r\n        // Scroll to the right\r\n        tab_bar->ScrollingTargetDistToVisibility = ImMax((tab_x1 - scrollable_width) - tab_bar->ScrollingAnim, 0.0f);\r\n        tab_bar->ScrollingTarget = tab_x2 - scrollable_width;\r\n    }\r\n}\r\n\r\nvoid ImGui::TabBarQueueReorder(ImGuiTabBar* tab_bar, const ImGuiTabItem* tab, int offset)\r\n{\r\n    IM_ASSERT(offset != 0);\r\n    IM_ASSERT(tab_bar->ReorderRequestTabId == 0);\r\n    tab_bar->ReorderRequestTabId = tab->ID;\r\n    tab_bar->ReorderRequestOffset = (ImS16)offset;\r\n}\r\n\r\nvoid ImGui::TabBarQueueReorderFromMousePos(ImGuiTabBar* tab_bar, const ImGuiTabItem* src_tab, ImVec2 mouse_pos)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    IM_ASSERT(tab_bar->ReorderRequestTabId == 0);\r\n    if ((tab_bar->Flags & ImGuiTabBarFlags_Reorderable) == 0)\r\n        return;\r\n\r\n    const bool is_central_section = (src_tab->Flags & ImGuiTabItemFlags_SectionMask_) == 0;\r\n    const float bar_offset = tab_bar->BarRect.Min.x - (is_central_section ? tab_bar->ScrollingTarget : 0);\r\n\r\n    // Count number of contiguous tabs we are crossing over\r\n    const int dir = (bar_offset + src_tab->Offset) > mouse_pos.x ? -1 : +1;\r\n    const int src_idx = tab_bar->Tabs.index_from_ptr(src_tab);\r\n    int dst_idx = src_idx;\r\n    for (int i = src_idx; i >= 0 && i < tab_bar->Tabs.Size; i += dir)\r\n    {\r\n        // Reordered tabs must share the same section\r\n        const ImGuiTabItem* dst_tab = &tab_bar->Tabs[i];\r\n        if (dst_tab->Flags & ImGuiTabItemFlags_NoReorder)\r\n            break;\r\n        if ((dst_tab->Flags & ImGuiTabItemFlags_SectionMask_) != (src_tab->Flags & ImGuiTabItemFlags_SectionMask_))\r\n            break;\r\n        dst_idx = i;\r\n\r\n        // Include spacing after tab, so when mouse cursor is between tabs we would not continue checking further tabs that are not hovered.\r\n        const float x1 = bar_offset + dst_tab->Offset - g.Style.ItemInnerSpacing.x;\r\n        const float x2 = bar_offset + dst_tab->Offset + dst_tab->Width + g.Style.ItemInnerSpacing.x;\r\n        //GetForegroundDrawList()->AddRect(ImVec2(x1, tab_bar->BarRect.Min.y), ImVec2(x2, tab_bar->BarRect.Max.y), IM_COL32(255, 0, 0, 255));\r\n        if ((dir < 0 && mouse_pos.x > x1) || (dir > 0 && mouse_pos.x < x2))\r\n            break;\r\n    }\r\n\r\n    if (dst_idx != src_idx)\r\n        TabBarQueueReorder(tab_bar, src_tab, dst_idx - src_idx);\r\n}\r\n\r\nbool ImGui::TabBarProcessReorder(ImGuiTabBar* tab_bar)\r\n{\r\n    ImGuiTabItem* tab1 = TabBarFindTabByID(tab_bar, tab_bar->ReorderRequestTabId);\r\n    if (tab1 == NULL || (tab1->Flags & ImGuiTabItemFlags_NoReorder))\r\n        return false;\r\n\r\n    //IM_ASSERT(tab_bar->Flags & ImGuiTabBarFlags_Reorderable); // <- this may happen when using debug tools\r\n    int tab2_order = tab_bar->GetTabOrder(tab1) + tab_bar->ReorderRequestOffset;\r\n    if (tab2_order < 0 || tab2_order >= tab_bar->Tabs.Size)\r\n        return false;\r\n\r\n    // Reordered tabs must share the same section\r\n    // (Note: TabBarQueueReorderFromMousePos() also has a similar test but since we allow direct calls to TabBarQueueReorder() we do it here too)\r\n    ImGuiTabItem* tab2 = &tab_bar->Tabs[tab2_order];\r\n    if (tab2->Flags & ImGuiTabItemFlags_NoReorder)\r\n        return false;\r\n    if ((tab1->Flags & ImGuiTabItemFlags_SectionMask_) != (tab2->Flags & ImGuiTabItemFlags_SectionMask_))\r\n        return false;\r\n\r\n    ImGuiTabItem item_tmp = *tab1;\r\n    ImGuiTabItem* src_tab = (tab_bar->ReorderRequestOffset > 0) ? tab1 + 1 : tab2;\r\n    ImGuiTabItem* dst_tab = (tab_bar->ReorderRequestOffset > 0) ? tab1 : tab2 + 1;\r\n    const int move_count = (tab_bar->ReorderRequestOffset > 0) ? tab_bar->ReorderRequestOffset : -tab_bar->ReorderRequestOffset;\r\n    memmove(dst_tab, src_tab, move_count * sizeof(ImGuiTabItem));\r\n    *tab2 = item_tmp;\r\n\r\n    if (tab_bar->Flags & ImGuiTabBarFlags_SaveSettings)\r\n        MarkIniSettingsDirty();\r\n    return true;\r\n}\r\n\r\nstatic ImGuiTabItem* ImGui::TabBarScrollingButtons(ImGuiTabBar* tab_bar)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n\r\n    const ImVec2 arrow_button_size(g.FontSize - 2.0f, g.FontSize + g.Style.FramePadding.y * 2.0f);\r\n    const float scrolling_buttons_width = arrow_button_size.x * 2.0f;\r\n\r\n    const ImVec2 backup_cursor_pos = window->DC.CursorPos;\r\n    //window->DrawList->AddRect(ImVec2(tab_bar->BarRect.Max.x - scrolling_buttons_width, tab_bar->BarRect.Min.y), ImVec2(tab_bar->BarRect.Max.x, tab_bar->BarRect.Max.y), IM_COL32(255,0,0,255));\r\n\r\n    int select_dir = 0;\r\n    ImVec4 arrow_col = g.Style.Colors[ImGuiCol_Text];\r\n    arrow_col.w *= 0.5f;\r\n\r\n    PushStyleColor(ImGuiCol_Text, arrow_col);\r\n    PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));\r\n    const float backup_repeat_delay = g.IO.KeyRepeatDelay;\r\n    const float backup_repeat_rate = g.IO.KeyRepeatRate;\r\n    g.IO.KeyRepeatDelay = 0.250f;\r\n    g.IO.KeyRepeatRate = 0.200f;\r\n    float x = ImMax(tab_bar->BarRect.Min.x, tab_bar->BarRect.Max.x - scrolling_buttons_width);\r\n    window->DC.CursorPos = ImVec2(x, tab_bar->BarRect.Min.y);\r\n    if (ArrowButtonEx(\"##<\", ImGuiDir_Left, arrow_button_size, ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_Repeat))\r\n        select_dir = -1;\r\n    window->DC.CursorPos = ImVec2(x + arrow_button_size.x, tab_bar->BarRect.Min.y);\r\n    if (ArrowButtonEx(\"##>\", ImGuiDir_Right, arrow_button_size, ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_Repeat))\r\n        select_dir = +1;\r\n    PopStyleColor(2);\r\n    g.IO.KeyRepeatRate = backup_repeat_rate;\r\n    g.IO.KeyRepeatDelay = backup_repeat_delay;\r\n\r\n    ImGuiTabItem* tab_to_scroll_to = NULL;\r\n    if (select_dir != 0)\r\n        if (ImGuiTabItem* tab_item = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId))\r\n        {\r\n            int selected_order = tab_bar->GetTabOrder(tab_item);\r\n            int target_order = selected_order + select_dir;\r\n\r\n            // Skip tab item buttons until another tab item is found or end is reached\r\n            while (tab_to_scroll_to == NULL)\r\n            {\r\n                // If we are at the end of the list, still scroll to make our tab visible\r\n                tab_to_scroll_to = &tab_bar->Tabs[(target_order >= 0 && target_order < tab_bar->Tabs.Size) ? target_order : selected_order];\r\n\r\n                // Cross through buttons\r\n                // (even if first/last item is a button, return it so we can update the scroll)\r\n                if (tab_to_scroll_to->Flags & ImGuiTabItemFlags_Button)\r\n                {\r\n                    target_order += select_dir;\r\n                    selected_order += select_dir;\r\n                    tab_to_scroll_to = (target_order < 0 || target_order >= tab_bar->Tabs.Size) ? tab_to_scroll_to : NULL;\r\n                }\r\n            }\r\n        }\r\n    window->DC.CursorPos = backup_cursor_pos;\r\n    tab_bar->BarRect.Max.x -= scrolling_buttons_width + 1.0f;\r\n\r\n    return tab_to_scroll_to;\r\n}\r\n\r\nstatic ImGuiTabItem* ImGui::TabBarTabListPopupButton(ImGuiTabBar* tab_bar)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n\r\n    // We use g.Style.FramePadding.y to match the square ArrowButton size\r\n    const float tab_list_popup_button_width = g.FontSize + g.Style.FramePadding.y;\r\n    const ImVec2 backup_cursor_pos = window->DC.CursorPos;\r\n    window->DC.CursorPos = ImVec2(tab_bar->BarRect.Min.x - g.Style.FramePadding.y, tab_bar->BarRect.Min.y);\r\n    tab_bar->BarRect.Min.x += tab_list_popup_button_width;\r\n\r\n    ImVec4 arrow_col = g.Style.Colors[ImGuiCol_Text];\r\n    arrow_col.w *= 0.5f;\r\n    PushStyleColor(ImGuiCol_Text, arrow_col);\r\n    PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));\r\n    bool open = BeginCombo(\"##v\", NULL, ImGuiComboFlags_NoPreview | ImGuiComboFlags_HeightLargest);\r\n    PopStyleColor(2);\r\n\r\n    ImGuiTabItem* tab_to_select = NULL;\r\n    if (open)\r\n    {\r\n        for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)\r\n        {\r\n            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];\r\n            if (tab->Flags & ImGuiTabItemFlags_Button)\r\n                continue;\r\n\r\n            const char* tab_name = tab_bar->GetTabName(tab);\r\n            if (Selectable(tab_name, tab_bar->SelectedTabId == tab->ID))\r\n                tab_to_select = tab;\r\n        }\r\n        EndCombo();\r\n    }\r\n\r\n    window->DC.CursorPos = backup_cursor_pos;\r\n    return tab_to_select;\r\n}\r\n\r\n//-------------------------------------------------------------------------\r\n// [SECTION] Widgets: BeginTabItem, EndTabItem, etc.\r\n//-------------------------------------------------------------------------\r\n// - BeginTabItem()\r\n// - EndTabItem()\r\n// - TabItemButton()\r\n// - TabItemEx() [Internal]\r\n// - SetTabItemClosed()\r\n// - TabItemCalcSize() [Internal]\r\n// - TabItemBackground() [Internal]\r\n// - TabItemLabelAndCloseButton() [Internal]\r\n//-------------------------------------------------------------------------\r\n\r\nbool    ImGui::BeginTabItem(const char* label, bool* p_open, ImGuiTabItemFlags flags)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    if (window->SkipItems)\r\n        return false;\r\n\r\n    ImGuiTabBar* tab_bar = g.CurrentTabBar;\r\n    if (tab_bar == NULL)\r\n    {\r\n        IM_ASSERT_USER_ERROR(tab_bar, \"Needs to be called between BeginTabBar() and EndTabBar()!\");\r\n        return false;\r\n    }\r\n    IM_ASSERT(!(flags & ImGuiTabItemFlags_Button)); // BeginTabItem() Can't be used with button flags, use TabItemButton() instead!\r\n\r\n    bool ret = TabItemEx(tab_bar, label, p_open, flags);\r\n    if (ret && !(flags & ImGuiTabItemFlags_NoPushId))\r\n    {\r\n        ImGuiTabItem* tab = &tab_bar->Tabs[tab_bar->LastTabItemIdx];\r\n        PushOverrideID(tab->ID); // We already hashed 'label' so push into the ID stack directly instead of doing another hash through PushID(label)\r\n    }\r\n    return ret;\r\n}\r\n\r\nvoid    ImGui::EndTabItem()\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    if (window->SkipItems)\r\n        return;\r\n\r\n    ImGuiTabBar* tab_bar = g.CurrentTabBar;\r\n    if (tab_bar == NULL)\r\n    {\r\n        IM_ASSERT_USER_ERROR(tab_bar != NULL, \"Needs to be called between BeginTabBar() and EndTabBar()!\");\r\n        return;\r\n    }\r\n    IM_ASSERT(tab_bar->LastTabItemIdx >= 0);\r\n    ImGuiTabItem* tab = &tab_bar->Tabs[tab_bar->LastTabItemIdx];\r\n    if (!(tab->Flags & ImGuiTabItemFlags_NoPushId))\r\n        PopID();\r\n}\r\n\r\nbool    ImGui::TabItemButton(const char* label, ImGuiTabItemFlags flags)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    if (window->SkipItems)\r\n        return false;\r\n\r\n    ImGuiTabBar* tab_bar = g.CurrentTabBar;\r\n    if (tab_bar == NULL)\r\n    {\r\n        IM_ASSERT_USER_ERROR(tab_bar != NULL, \"Needs to be called between BeginTabBar() and EndTabBar()!\");\r\n        return false;\r\n    }\r\n    return TabItemEx(tab_bar, label, NULL, flags | ImGuiTabItemFlags_Button | ImGuiTabItemFlags_NoReorder);\r\n}\r\n\r\nbool    ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, ImGuiTabItemFlags flags)\r\n{\r\n    // Layout whole tab bar if not already done\r\n    if (tab_bar->WantLayout)\r\n        TabBarLayout(tab_bar);\r\n\r\n    ImGuiContext& g = *GImGui;\r\n    ImGuiWindow* window = g.CurrentWindow;\r\n    if (window->SkipItems)\r\n        return false;\r\n\r\n    const ImGuiStyle& style = g.Style;\r\n    const ImGuiID id = TabBarCalcTabID(tab_bar, label);\r\n\r\n    // If the user called us with *p_open == false, we early out and don't render.\r\n    // We make a call to ItemAdd() so that attempts to use a contextual popup menu with an implicit ID won't use an older ID.\r\n    IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags);\r\n    if (p_open && !*p_open)\r\n    {\r\n        ItemAdd(ImRect(), id, NULL, ImGuiItemFlags_NoNav | ImGuiItemFlags_NoNavDefaultFocus);\r\n        return false;\r\n    }\r\n\r\n    IM_ASSERT(!p_open || !(flags & ImGuiTabItemFlags_Button));\r\n    IM_ASSERT((flags & (ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_Trailing)) != (ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_Trailing)); // Can't use both Leading and Trailing\r\n\r\n    // Store into ImGuiTabItemFlags_NoCloseButton, also honor ImGuiTabItemFlags_NoCloseButton passed by user (although not documented)\r\n    if (flags & ImGuiTabItemFlags_NoCloseButton)\r\n        p_open = NULL;\r\n    else if (p_open == NULL)\r\n        flags |= ImGuiTabItemFlags_NoCloseButton;\r\n\r\n    // Calculate tab contents size\r\n    ImVec2 size = TabItemCalcSize(label, p_open != NULL);\r\n\r\n    // Acquire tab data\r\n    ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, id);\r\n    bool tab_is_new = false;\r\n    if (tab == NULL)\r\n    {\r\n        tab_bar->Tabs.push_back(ImGuiTabItem());\r\n        tab = &tab_bar->Tabs.back();\r\n        tab->ID = id;\r\n        tab->Width = size.x;\r\n        tab_bar->TabsAddedNew = true;\r\n        tab_is_new = true;\r\n    }\r\n    tab_bar->LastTabItemIdx = (ImS16)tab_bar->Tabs.index_from_ptr(tab);\r\n    tab->ContentWidth = size.x;\r\n    tab->BeginOrder = tab_bar->TabsActiveCount++;\r\n\r\n    const bool tab_bar_appearing = (tab_bar->PrevFrameVisible + 1 < g.FrameCount);\r\n    const bool tab_bar_focused = (tab_bar->Flags & ImGuiTabBarFlags_IsFocused) != 0;\r\n    const bool tab_appearing = (tab->LastFrameVisible + 1 < g.FrameCount);\r\n    const bool is_tab_button = (flags & ImGuiTabItemFlags_Button) != 0;\r\n    tab->LastFrameVisible = g.FrameCount;\r\n    tab->Flags = flags;\r\n\r\n    // Append name with zero-terminator\r\n    tab->NameOffset = (ImS32)tab_bar->TabsNames.size();\r\n    tab_bar->TabsNames.append(label, label + strlen(label) + 1);\r\n\r\n    // Update selected tab\r\n    if (tab_appearing && (tab_bar->Flags & ImGuiTabBarFlags_AutoSelectNewTabs) && tab_bar->NextSelectedTabId == 0)\r\n        if (!tab_bar_appearing || tab_bar->SelectedTabId == 0)\r\n            if (!is_tab_button)\r\n                tab_bar->NextSelectedTabId = id;  // New tabs gets activated\r\n    if ((flags & ImGuiTabItemFlags_SetSelected) && (tab_bar->SelectedTabId != id)) // SetSelected can only be passed on explicit tab bar\r\n        if (!is_tab_button)\r\n            tab_bar->NextSelectedTabId = id;\r\n\r\n    // Lock visibility\r\n    // (Note: tab_contents_visible != tab_selected... because CTRL+TAB operations may preview some tabs without selecting them!)\r\n    bool tab_contents_visible = (tab_bar->VisibleTabId == id);\r\n    if (tab_contents_visible)\r\n        tab_bar->VisibleTabWasSubmitted = true;\r\n\r\n    // On the very first frame of a tab bar we let first tab contents be visible to minimize appearing glitches\r\n    if (!tab_contents_visible && tab_bar->SelectedTabId == 0 && tab_bar_appearing)\r\n        if (tab_bar->Tabs.Size == 1 && !(tab_bar->Flags & ImGuiTabBarFlags_AutoSelectNewTabs))\r\n            tab_contents_visible = true;\r\n\r\n    // Note that tab_is_new is not necessarily the same as tab_appearing! When a tab bar stops being submitted\r\n    // and then gets submitted again, the tabs will have 'tab_appearing=true' but 'tab_is_new=false'.\r\n    if (tab_appearing && (!tab_bar_appearing || tab_is_new))\r\n    {\r\n        ItemAdd(ImRect(), id, NULL, ImGuiItemFlags_NoNav | ImGuiItemFlags_NoNavDefaultFocus);\r\n        if (is_tab_button)\r\n            return false;\r\n        return tab_contents_visible;\r\n    }\r\n\r\n    if (tab_bar->SelectedTabId == id)\r\n        tab->LastFrameSelected = g.FrameCount;\r\n\r\n    // Backup current layout position\r\n    const ImVec2 backup_main_cursor_pos = window->DC.CursorPos;\r\n\r\n    // Layout\r\n    const bool is_central_section = (tab->Flags & ImGuiTabItemFlags_SectionMask_) == 0;\r\n    size.x = tab->Width;\r\n    if (is_central_section)\r\n        window->DC.CursorPos = tab_bar->BarRect.Min + ImVec2(IM_FLOOR(tab->Offset - tab_bar->ScrollingAnim), 0.0f);\r\n    else\r\n        window->DC.CursorPos = tab_bar->BarRect.Min + ImVec2(tab->Offset, 0.0f);\r\n    ImVec2 pos = window->DC.CursorPos;\r\n    ImRect bb(pos, pos + size);\r\n\r\n    // We don't have CPU clipping primitives to clip the CloseButton (until it becomes a texture), so need to add an extra draw call (temporary in the case of vertical animation)\r\n    const bool want_clip_rect = is_central_section && (bb.Min.x < tab_bar->ScrollingRectMinX || bb.Max.x > tab_bar->ScrollingRectMaxX);\r\n    if (want_clip_rect)\r\n        PushClipRect(ImVec2(ImMax(bb.Min.x, tab_bar->ScrollingRectMinX), bb.Min.y - 1), ImVec2(tab_bar->ScrollingRectMaxX, bb.Max.y), true);\r\n\r\n    ImVec2 backup_cursor_max_pos = window->DC.CursorMaxPos;\r\n    ItemSize(bb.GetSize(), style.FramePadding.y);\r\n    window->DC.CursorMaxPos = backup_cursor_max_pos;\r\n\r\n    if (!ItemAdd(bb, id))\r\n    {\r\n        if (want_clip_rect)\r\n            PopClipRect();\r\n        window->DC.CursorPos = backup_main_cursor_pos;\r\n        return tab_contents_visible;\r\n    }\r\n\r\n    // Click to Select a tab\r\n    ImGuiButtonFlags button_flags = ((is_tab_button ? ImGuiButtonFlags_PressedOnClickRelease : ImGuiButtonFlags_PressedOnClick) | ImGuiButtonFlags_AllowItemOverlap);\r\n    if (g.DragDropActive)\r\n        button_flags |= ImGuiButtonFlags_PressedOnDragDropHold;\r\n    bool hovered, held;\r\n    bool pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags);\r\n    if (pressed && !is_tab_button)\r\n        tab_bar->NextSelectedTabId = id;\r\n\r\n    // Allow the close button to overlap unless we are dragging (in which case we don't want any overlapping tabs to be hovered)\r\n    if (g.ActiveId != id)\r\n        SetItemAllowOverlap();\r\n\r\n    // Drag and drop: re-order tabs\r\n    if (held && !tab_appearing && IsMouseDragging(0))\r\n    {\r\n        if (!g.DragDropActive && (tab_bar->Flags & ImGuiTabBarFlags_Reorderable))\r\n        {\r\n            // While moving a tab it will jump on the other side of the mouse, so we also test for MouseDelta.x\r\n            if (g.IO.MouseDelta.x < 0.0f && g.IO.MousePos.x < bb.Min.x)\r\n            {\r\n                TabBarQueueReorderFromMousePos(tab_bar, tab, g.IO.MousePos);\r\n            }\r\n            else if (g.IO.MouseDelta.x > 0.0f && g.IO.MousePos.x > bb.Max.x)\r\n            {\r\n                TabBarQueueReorderFromMousePos(tab_bar, tab, g.IO.MousePos);\r\n            }\r\n        }\r\n    }\r\n\r\n#if 0\r\n    if (hovered && g.HoveredIdNotActiveTimer > TOOLTIP_DELAY && bb.GetWidth() < tab->ContentWidth)\r\n    {\r\n        // Enlarge tab display when hovering\r\n        bb.Max.x = bb.Min.x + IM_FLOOR(ImLerp(bb.GetWidth(), tab->ContentWidth, ImSaturate((g.HoveredIdNotActiveTimer - 0.40f) * 6.0f)));\r\n        display_draw_list = GetForegroundDrawList(window);\r\n        TabItemBackground(display_draw_list, bb, flags, GetColorU32(ImGuiCol_TitleBgActive));\r\n    }\r\n#endif\r\n\r\n    // Render tab shape\r\n    ImDrawList* display_draw_list = window->DrawList;\r\n    const ImU32 tab_col = GetColorU32((held || hovered) ? ImGuiCol_TabHovered : tab_contents_visible ? (tab_bar_focused ? ImGuiCol_TabActive : ImGuiCol_TabUnfocusedActive) : (tab_bar_focused ? ImGuiCol_Tab : ImGuiCol_TabUnfocused));\r\n    TabItemBackground(display_draw_list, bb, flags, tab_col);\r\n    RenderNavHighlight(bb, id);\r\n\r\n    // Select with right mouse button. This is so the common idiom for context menu automatically highlight the current widget.\r\n    const bool hovered_unblocked = IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup);\r\n    if (hovered_unblocked && (IsMouseClicked(1) || IsMouseReleased(1)))\r\n        if (!is_tab_button)\r\n            tab_bar->NextSelectedTabId = id;\r\n\r\n    if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton)\r\n        flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton;\r\n\r\n    // Render tab label, process close button\r\n    const ImGuiID close_button_id = p_open ? GetIDWithSeed(\"#CLOSE\", NULL, id) : 0;\r\n    bool just_closed;\r\n    bool text_clipped;\r\n    TabItemLabelAndCloseButton(display_draw_list, bb, flags, tab_bar->FramePadding, label, id, close_button_id, tab_contents_visible, &just_closed, &text_clipped);\r\n    if (just_closed && p_open != NULL)\r\n    {\r\n        *p_open = false;\r\n        TabBarCloseTab(tab_bar, tab);\r\n    }\r\n\r\n    // Restore main window position so user can draw there\r\n    if (want_clip_rect)\r\n        PopClipRect();\r\n    window->DC.CursorPos = backup_main_cursor_pos;\r\n\r\n    // Tooltip\r\n    // (Won't work over the close button because ItemOverlap systems messes up with HoveredIdTimer-> seems ok)\r\n    // (We test IsItemHovered() to discard e.g. when another item is active or drag and drop over the tab bar, which g.HoveredId ignores)\r\n    // FIXME: This is a mess.\r\n    // FIXME: We may want disabled tab to still display the tooltip?\r\n    if (text_clipped && g.HoveredId == id && !held && g.HoveredIdNotActiveTimer > g.TooltipSlowDelay && IsItemHovered())\r\n        if (!(tab_bar->Flags & ImGuiTabBarFlags_NoTooltip) && !(tab->Flags & ImGuiTabItemFlags_NoTooltip))\r\n            SetTooltip(\"%.*s\", (int)(FindRenderedTextEnd(label) - label), label);\r\n\r\n    IM_ASSERT(!is_tab_button || !(tab_bar->SelectedTabId == tab->ID && is_tab_button)); // TabItemButton should not be selected\r\n    if (is_tab_button)\r\n        return pressed;\r\n    return tab_contents_visible;\r\n}\r\n\r\n// [Public] This is call is 100% optional but it allows to remove some one-frame glitches when a tab has been unexpectedly removed.\r\n// To use it to need to call the function SetTabItemClosed() between BeginTabBar() and EndTabBar().\r\n// Tabs closed by the close button will automatically be flagged to avoid this issue.\r\nvoid    ImGui::SetTabItemClosed(const char* label)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    bool is_within_manual_tab_bar = g.CurrentTabBar && !(g.CurrentTabBar->Flags & ImGuiTabBarFlags_DockNode);\r\n    if (is_within_manual_tab_bar)\r\n    {\r\n        ImGuiTabBar* tab_bar = g.CurrentTabBar;\r\n        ImGuiID tab_id = TabBarCalcTabID(tab_bar, label);\r\n        if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_id))\r\n            tab->WantClose = true; // Will be processed by next call to TabBarLayout()\r\n    }\r\n}\r\n\r\nImVec2 ImGui::TabItemCalcSize(const char* label, bool has_close_button)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImVec2 label_size = CalcTextSize(label, NULL, true);\r\n    ImVec2 size = ImVec2(label_size.x + g.Style.FramePadding.x, label_size.y + g.Style.FramePadding.y * 2.0f);\r\n    if (has_close_button)\r\n        size.x += g.Style.FramePadding.x + (g.Style.ItemInnerSpacing.x + g.FontSize); // We use Y intentionally to fit the close button circle.\r\n    else\r\n        size.x += g.Style.FramePadding.x + 1.0f;\r\n    return ImVec2(ImMin(size.x, TabBarCalcMaxTabWidth()), size.y);\r\n}\r\n\r\nvoid ImGui::TabItemBackground(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImU32 col)\r\n{\r\n    // While rendering tabs, we trim 1 pixel off the top of our bounding box so they can fit within a regular frame height while looking \"detached\" from it.\r\n    ImGuiContext& g = *GImGui;\r\n    const float width = bb.GetWidth();\r\n    IM_UNUSED(flags);\r\n    IM_ASSERT(width > 0.0f);\r\n    const float rounding = ImMax(0.0f, ImMin((flags & ImGuiTabItemFlags_Button) ? g.Style.FrameRounding : g.Style.TabRounding, width * 0.5f - 1.0f));\r\n    const float y1 = bb.Min.y + 1.0f;\r\n    const float y2 = bb.Max.y - 1.0f;\r\n    draw_list->PathLineTo(ImVec2(bb.Min.x, y2));\r\n    draw_list->PathArcToFast(ImVec2(bb.Min.x + rounding, y1 + rounding), rounding, 6, 9);\r\n    draw_list->PathArcToFast(ImVec2(bb.Max.x - rounding, y1 + rounding), rounding, 9, 12);\r\n    draw_list->PathLineTo(ImVec2(bb.Max.x, y2));\r\n    draw_list->PathFillConvex(col);\r\n    if (g.Style.TabBorderSize > 0.0f)\r\n    {\r\n        draw_list->PathLineTo(ImVec2(bb.Min.x + 0.5f, y2));\r\n        draw_list->PathArcToFast(ImVec2(bb.Min.x + rounding + 0.5f, y1 + rounding + 0.5f), rounding, 6, 9);\r\n        draw_list->PathArcToFast(ImVec2(bb.Max.x - rounding - 0.5f, y1 + rounding + 0.5f), rounding, 9, 12);\r\n        draw_list->PathLineTo(ImVec2(bb.Max.x - 0.5f, y2));\r\n        draw_list->PathStroke(GetColorU32(ImGuiCol_Border), 0, g.Style.TabBorderSize);\r\n    }\r\n}\r\n\r\n// Render text label (with custom clipping) + Unsaved Document marker + Close Button logic\r\n// We tend to lock style.FramePadding for a given tab-bar, hence the 'frame_padding' parameter.\r\nvoid ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImVec2 frame_padding, const char* label, ImGuiID tab_id, ImGuiID close_button_id, bool is_contents_visible, bool* out_just_closed, bool* out_text_clipped)\r\n{\r\n    ImGuiContext& g = *GImGui;\r\n    ImVec2 label_size = CalcTextSize(label, NULL, true);\r\n\r\n    if (out_just_closed)\r\n        *out_just_closed = false;\r\n    if (out_text_clipped)\r\n        *out_text_clipped = false;\r\n\r\n    if (bb.GetWidth() <= 1.0f)\r\n        return;\r\n\r\n    // In Style V2 we'll have full override of all colors per state (e.g. focused, selected)\r\n    // But right now if you want to alter text color of tabs this is what you need to do.\r\n#if 0\r\n    const float backup_alpha = g.Style.Alpha;\r\n    if (!is_contents_visible)\r\n        g.Style.Alpha *= 0.7f;\r\n#endif\r\n\r\n    // Render text label (with clipping + alpha gradient) + unsaved marker\r\n    ImRect text_pixel_clip_bb(bb.Min.x + frame_padding.x, bb.Min.y + frame_padding.y, bb.Max.x - frame_padding.x, bb.Max.y);\r\n    ImRect text_ellipsis_clip_bb = text_pixel_clip_bb;\r\n\r\n    // Return clipped state ignoring the close button\r\n    if (out_text_clipped)\r\n    {\r\n        *out_text_clipped = (text_ellipsis_clip_bb.Min.x + label_size.x) > text_pixel_clip_bb.Max.x;\r\n        //draw_list->AddCircle(text_ellipsis_clip_bb.Min, 3.0f, *out_text_clipped ? IM_COL32(255, 0, 0, 255) : IM_COL32(0, 255, 0, 255));\r\n    }\r\n\r\n    const float button_sz = g.FontSize;\r\n    const ImVec2 button_pos(ImMax(bb.Min.x, bb.Max.x - frame_padding.x * 2.0f - button_sz), bb.Min.y);\r\n\r\n    // Close Button & Unsaved Marker\r\n    // We are relying on a subtle and confusing distinction between 'hovered' and 'g.HoveredId' which happens because we are using ImGuiButtonFlags_AllowOverlapMode + SetItemAllowOverlap()\r\n    //  'hovered' will be true when hovering the Tab but NOT when hovering the close button\r\n    //  'g.HoveredId==id' will be true when hovering the Tab including when hovering the close button\r\n    //  'g.ActiveId==close_button_id' will be true when we are holding on the close button, in which case both hovered booleans are false\r\n    bool close_button_pressed = false;\r\n    bool close_button_visible = false;\r\n    if (close_button_id != 0)\r\n        if (is_contents_visible || bb.GetWidth() >= ImMax(button_sz, g.Style.TabMinWidthForCloseButton))\r\n            if (g.HoveredId == tab_id || g.HoveredId == close_button_id || g.ActiveId == tab_id || g.ActiveId == close_button_id)\r\n                close_button_visible = true;\r\n    bool unsaved_marker_visible = (flags & ImGuiTabItemFlags_UnsavedDocument) != 0 && (button_pos.x + button_sz <= bb.Max.x);\r\n\r\n    if (close_button_visible)\r\n    {\r\n        ImGuiLastItemData last_item_backup = g.LastItemData;\r\n        PushStyleVar(ImGuiStyleVar_FramePadding, frame_padding);\r\n        if (CloseButton(close_button_id, button_pos))\r\n            close_button_pressed = true;\r\n        PopStyleVar();\r\n        g.LastItemData = last_item_backup;\r\n\r\n        // Close with middle mouse button\r\n        if (!(flags & ImGuiTabItemFlags_NoCloseWithMiddleMouseButton) && IsMouseClicked(2))\r\n            close_button_pressed = true;\r\n    }\r\n    else if (unsaved_marker_visible)\r\n    {\r\n        const ImRect bullet_bb(button_pos, button_pos + ImVec2(button_sz, button_sz) + g.Style.FramePadding * 2.0f);\r\n        RenderBullet(draw_list, bullet_bb.GetCenter(), GetColorU32(ImGuiCol_Text));\r\n    }\r\n\r\n    // This is all rather complicated\r\n    // (the main idea is that because the close button only appears on hover, we don't want it to alter the ellipsis position)\r\n    // FIXME: if FramePadding is noticeably large, ellipsis_max_x will be wrong here (e.g. #3497), maybe for consistency that parameter of RenderTextEllipsis() shouldn't exist..\r\n    float ellipsis_max_x = close_button_visible ? text_pixel_clip_bb.Max.x : bb.Max.x - 1.0f;\r\n    if (close_button_visible || unsaved_marker_visible)\r\n    {\r\n        text_pixel_clip_bb.Max.x -= close_button_visible ? (button_sz) : (button_sz * 0.80f);\r\n        text_ellipsis_clip_bb.Max.x -= unsaved_marker_visible ? (button_sz * 0.80f) : 0.0f;\r\n        ellipsis_max_x = text_pixel_clip_bb.Max.x;\r\n    }\r\n    RenderTextEllipsis(draw_list, text_ellipsis_clip_bb.Min, text_ellipsis_clip_bb.Max, text_pixel_clip_bb.Max.x, ellipsis_max_x, label, NULL, &label_size);\r\n\r\n#if 0\r\n    if (!is_contents_visible)\r\n        g.Style.Alpha = backup_alpha;\r\n#endif\r\n\r\n    if (out_just_closed)\r\n        *out_just_closed = close_button_pressed;\r\n}\r\n\r\n\r\n#endif // #ifndef IMGUI_DISABLE\r\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/imgui/imstb_rectpack.h",
    "content": "// [DEAR IMGUI]\r\n// This is a slightly modified version of stb_rect_pack.h 1.00.\r\n// Those changes would need to be pushed into nothings/stb:\r\n// - Added STBRP__CDECL\r\n// Grep for [DEAR IMGUI] to find the changes.\r\n\r\n// stb_rect_pack.h - v1.00 - public domain - rectangle packing\r\n// Sean Barrett 2014\r\n//\r\n// Useful for e.g. packing rectangular textures into an atlas.\r\n// Does not do rotation.\r\n//\r\n// Not necessarily the awesomest packing method, but better than\r\n// the totally naive one in stb_truetype (which is primarily what\r\n// this is meant to replace).\r\n//\r\n// Has only had a few tests run, may have issues.\r\n//\r\n// More docs to come.\r\n//\r\n// No memory allocations; uses qsort() and assert() from stdlib.\r\n// Can override those by defining STBRP_SORT and STBRP_ASSERT.\r\n//\r\n// This library currently uses the Skyline Bottom-Left algorithm.\r\n//\r\n// Please note: better rectangle packers are welcome! Please\r\n// implement them to the same API, but with a different init\r\n// function.\r\n//\r\n// Credits\r\n//\r\n//  Library\r\n//    Sean Barrett\r\n//  Minor features\r\n//    Martins Mozeiko\r\n//    github:IntellectualKitty\r\n//\r\n//  Bugfixes / warning fixes\r\n//    Jeremy Jaussaud\r\n//    Fabian Giesen\r\n//\r\n// Version history:\r\n//\r\n//     1.00  (2019-02-25)  avoid small space waste; gracefully fail too-wide rectangles\r\n//     0.99  (2019-02-07)  warning fixes\r\n//     0.11  (2017-03-03)  return packing success/fail result\r\n//     0.10  (2016-10-25)  remove cast-away-const to avoid warnings\r\n//     0.09  (2016-08-27)  fix compiler warnings\r\n//     0.08  (2015-09-13)  really fix bug with empty rects (w=0 or h=0)\r\n//     0.07  (2015-09-13)  fix bug with empty rects (w=0 or h=0)\r\n//     0.06  (2015-04-15)  added STBRP_SORT to allow replacing qsort\r\n//     0.05:  added STBRP_ASSERT to allow replacing assert\r\n//     0.04:  fixed minor bug in STBRP_LARGE_RECTS support\r\n//     0.01:  initial release\r\n//\r\n// LICENSE\r\n//\r\n//   See end of file for license information.\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//\r\n//       INCLUDE SECTION\r\n//\r\n\r\n#ifndef STB_INCLUDE_STB_RECT_PACK_H\r\n#define STB_INCLUDE_STB_RECT_PACK_H\r\n\r\n#define STB_RECT_PACK_VERSION  1\r\n\r\n#ifdef STBRP_STATIC\r\n#define STBRP_DEF static\r\n#else\r\n#define STBRP_DEF extern\r\n#endif\r\n\r\n#ifdef __cplusplus\r\nextern \"C\" {\r\n#endif\r\n\r\ntypedef struct stbrp_context stbrp_context;\r\ntypedef struct stbrp_node    stbrp_node;\r\ntypedef struct stbrp_rect    stbrp_rect;\r\n\r\n#ifdef STBRP_LARGE_RECTS\r\ntypedef int            stbrp_coord;\r\n#else\r\ntypedef unsigned short stbrp_coord;\r\n#endif\r\n\r\nSTBRP_DEF int stbrp_pack_rects (stbrp_context *context, stbrp_rect *rects, int num_rects);\r\n// Assign packed locations to rectangles. The rectangles are of type\r\n// 'stbrp_rect' defined below, stored in the array 'rects', and there\r\n// are 'num_rects' many of them.\r\n//\r\n// Rectangles which are successfully packed have the 'was_packed' flag\r\n// set to a non-zero value and 'x' and 'y' store the minimum location\r\n// on each axis (i.e. bottom-left in cartesian coordinates, top-left\r\n// if you imagine y increasing downwards). Rectangles which do not fit\r\n// have the 'was_packed' flag set to 0.\r\n//\r\n// You should not try to access the 'rects' array from another thread\r\n// while this function is running, as the function temporarily reorders\r\n// the array while it executes.\r\n//\r\n// To pack into another rectangle, you need to call stbrp_init_target\r\n// again. To continue packing into the same rectangle, you can call\r\n// this function again. Calling this multiple times with multiple rect\r\n// arrays will probably produce worse packing results than calling it\r\n// a single time with the full rectangle array, but the option is\r\n// available.\r\n//\r\n// The function returns 1 if all of the rectangles were successfully\r\n// packed and 0 otherwise.\r\n\r\nstruct stbrp_rect\r\n{\r\n   // reserved for your use:\r\n   int            id;\r\n\r\n   // input:\r\n   stbrp_coord    w, h;\r\n\r\n   // output:\r\n   stbrp_coord    x, y;\r\n   int            was_packed;  // non-zero if valid packing\r\n\r\n}; // 16 bytes, nominally\r\n\r\n\r\nSTBRP_DEF void stbrp_init_target (stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes);\r\n// Initialize a rectangle packer to:\r\n//    pack a rectangle that is 'width' by 'height' in dimensions\r\n//    using temporary storage provided by the array 'nodes', which is 'num_nodes' long\r\n//\r\n// You must call this function every time you start packing into a new target.\r\n//\r\n// There is no \"shutdown\" function. The 'nodes' memory must stay valid for\r\n// the following stbrp_pack_rects() call (or calls), but can be freed after\r\n// the call (or calls) finish.\r\n//\r\n// Note: to guarantee best results, either:\r\n//       1. make sure 'num_nodes' >= 'width'\r\n//   or  2. call stbrp_allow_out_of_mem() defined below with 'allow_out_of_mem = 1'\r\n//\r\n// If you don't do either of the above things, widths will be quantized to multiples\r\n// of small integers to guarantee the algorithm doesn't run out of temporary storage.\r\n//\r\n// If you do #2, then the non-quantized algorithm will be used, but the algorithm\r\n// may run out of temporary storage and be unable to pack some rectangles.\r\n\r\nSTBRP_DEF void stbrp_setup_allow_out_of_mem (stbrp_context *context, int allow_out_of_mem);\r\n// Optionally call this function after init but before doing any packing to\r\n// change the handling of the out-of-temp-memory scenario, described above.\r\n// If you call init again, this will be reset to the default (false).\r\n\r\n\r\nSTBRP_DEF void stbrp_setup_heuristic (stbrp_context *context, int heuristic);\r\n// Optionally select which packing heuristic the library should use. Different\r\n// heuristics will produce better/worse results for different data sets.\r\n// If you call init again, this will be reset to the default.\r\n\r\nenum\r\n{\r\n   STBRP_HEURISTIC_Skyline_default=0,\r\n   STBRP_HEURISTIC_Skyline_BL_sortHeight = STBRP_HEURISTIC_Skyline_default,\r\n   STBRP_HEURISTIC_Skyline_BF_sortHeight\r\n};\r\n\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//\r\n// the details of the following structures don't matter to you, but they must\r\n// be visible so you can handle the memory allocations for them\r\n\r\nstruct stbrp_node\r\n{\r\n   stbrp_coord  x,y;\r\n   stbrp_node  *next;\r\n};\r\n\r\nstruct stbrp_context\r\n{\r\n   int width;\r\n   int height;\r\n   int align;\r\n   int init_mode;\r\n   int heuristic;\r\n   int num_nodes;\r\n   stbrp_node *active_head;\r\n   stbrp_node *free_head;\r\n   stbrp_node extra[2]; // we allocate two extra nodes so optimal user-node-count is 'width' not 'width+2'\r\n};\r\n\r\n#ifdef __cplusplus\r\n}\r\n#endif\r\n\r\n#endif\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//\r\n//     IMPLEMENTATION SECTION\r\n//\r\n\r\n#ifdef STB_RECT_PACK_IMPLEMENTATION\r\n#ifndef STBRP_SORT\r\n#include <stdlib.h>\r\n#define STBRP_SORT qsort\r\n#endif\r\n\r\n#ifndef STBRP_ASSERT\r\n#include <assert.h>\r\n#define STBRP_ASSERT assert\r\n#endif\r\n\r\n// [DEAR IMGUI] Added STBRP__CDECL\r\n#ifdef _MSC_VER\r\n#define STBRP__NOTUSED(v)  (void)(v)\r\n#define STBRP__CDECL __cdecl\r\n#else\r\n#define STBRP__NOTUSED(v)  (void)sizeof(v)\r\n#define STBRP__CDECL\r\n#endif\r\n\r\nenum\r\n{\r\n   STBRP__INIT_skyline = 1\r\n};\r\n\r\nSTBRP_DEF void stbrp_setup_heuristic(stbrp_context *context, int heuristic)\r\n{\r\n   switch (context->init_mode) {\r\n      case STBRP__INIT_skyline:\r\n         STBRP_ASSERT(heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight || heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight);\r\n         context->heuristic = heuristic;\r\n         break;\r\n      default:\r\n         STBRP_ASSERT(0);\r\n   }\r\n}\r\n\r\nSTBRP_DEF void stbrp_setup_allow_out_of_mem(stbrp_context *context, int allow_out_of_mem)\r\n{\r\n   if (allow_out_of_mem)\r\n      // if it's ok to run out of memory, then don't bother aligning them;\r\n      // this gives better packing, but may fail due to OOM (even though\r\n      // the rectangles easily fit). @TODO a smarter approach would be to only\r\n      // quantize once we've hit OOM, then we could get rid of this parameter.\r\n      context->align = 1;\r\n   else {\r\n      // if it's not ok to run out of memory, then quantize the widths\r\n      // so that num_nodes is always enough nodes.\r\n      //\r\n      // I.e. num_nodes * align >= width\r\n      //                  align >= width / num_nodes\r\n      //                  align = ceil(width/num_nodes)\r\n\r\n      context->align = (context->width + context->num_nodes-1) / context->num_nodes;\r\n   }\r\n}\r\n\r\nSTBRP_DEF void stbrp_init_target(stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes)\r\n{\r\n   int i;\r\n#ifndef STBRP_LARGE_RECTS\r\n   STBRP_ASSERT(width <= 0xffff && height <= 0xffff);\r\n#endif\r\n\r\n   for (i=0; i < num_nodes-1; ++i)\r\n      nodes[i].next = &nodes[i+1];\r\n   nodes[i].next = NULL;\r\n   context->init_mode = STBRP__INIT_skyline;\r\n   context->heuristic = STBRP_HEURISTIC_Skyline_default;\r\n   context->free_head = &nodes[0];\r\n   context->active_head = &context->extra[0];\r\n   context->width = width;\r\n   context->height = height;\r\n   context->num_nodes = num_nodes;\r\n   stbrp_setup_allow_out_of_mem(context, 0);\r\n\r\n   // node 0 is the full width, node 1 is the sentinel (lets us not store width explicitly)\r\n   context->extra[0].x = 0;\r\n   context->extra[0].y = 0;\r\n   context->extra[0].next = &context->extra[1];\r\n   context->extra[1].x = (stbrp_coord) width;\r\n#ifdef STBRP_LARGE_RECTS\r\n   context->extra[1].y = (1<<30);\r\n#else\r\n   context->extra[1].y = 65535;\r\n#endif\r\n   context->extra[1].next = NULL;\r\n}\r\n\r\n// find minimum y position if it starts at x1\r\nstatic int stbrp__skyline_find_min_y(stbrp_context *c, stbrp_node *first, int x0, int width, int *pwaste)\r\n{\r\n   stbrp_node *node = first;\r\n   int x1 = x0 + width;\r\n   int min_y, visited_width, waste_area;\r\n\r\n   STBRP__NOTUSED(c);\r\n\r\n   STBRP_ASSERT(first->x <= x0);\r\n\r\n   #if 0\r\n   // skip in case we're past the node\r\n   while (node->next->x <= x0)\r\n      ++node;\r\n   #else\r\n   STBRP_ASSERT(node->next->x > x0); // we ended up handling this in the caller for efficiency\r\n   #endif\r\n\r\n   STBRP_ASSERT(node->x <= x0);\r\n\r\n   min_y = 0;\r\n   waste_area = 0;\r\n   visited_width = 0;\r\n   while (node->x < x1) {\r\n      if (node->y > min_y) {\r\n         // raise min_y higher.\r\n         // we've accounted for all waste up to min_y,\r\n         // but we'll now add more waste for everything we've visted\r\n         waste_area += visited_width * (node->y - min_y);\r\n         min_y = node->y;\r\n         // the first time through, visited_width might be reduced\r\n         if (node->x < x0)\r\n            visited_width += node->next->x - x0;\r\n         else\r\n            visited_width += node->next->x - node->x;\r\n      } else {\r\n         // add waste area\r\n         int under_width = node->next->x - node->x;\r\n         if (under_width + visited_width > width)\r\n            under_width = width - visited_width;\r\n         waste_area += under_width * (min_y - node->y);\r\n         visited_width += under_width;\r\n      }\r\n      node = node->next;\r\n   }\r\n\r\n   *pwaste = waste_area;\r\n   return min_y;\r\n}\r\n\r\ntypedef struct\r\n{\r\n   int x,y;\r\n   stbrp_node **prev_link;\r\n} stbrp__findresult;\r\n\r\nstatic stbrp__findresult stbrp__skyline_find_best_pos(stbrp_context *c, int width, int height)\r\n{\r\n   int best_waste = (1<<30), best_x, best_y = (1 << 30);\r\n   stbrp__findresult fr;\r\n   stbrp_node **prev, *node, *tail, **best = NULL;\r\n\r\n   // align to multiple of c->align\r\n   width = (width + c->align - 1);\r\n   width -= width % c->align;\r\n   STBRP_ASSERT(width % c->align == 0);\r\n\r\n   // if it can't possibly fit, bail immediately\r\n   if (width > c->width || height > c->height) {\r\n      fr.prev_link = NULL;\r\n      fr.x = fr.y = 0;\r\n      return fr;\r\n   }\r\n\r\n   node = c->active_head;\r\n   prev = &c->active_head;\r\n   while (node->x + width <= c->width) {\r\n      int y,waste;\r\n      y = stbrp__skyline_find_min_y(c, node, node->x, width, &waste);\r\n      if (c->heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight) { // actually just want to test BL\r\n         // bottom left\r\n         if (y < best_y) {\r\n            best_y = y;\r\n            best = prev;\r\n         }\r\n      } else {\r\n         // best-fit\r\n         if (y + height <= c->height) {\r\n            // can only use it if it first vertically\r\n            if (y < best_y || (y == best_y && waste < best_waste)) {\r\n               best_y = y;\r\n               best_waste = waste;\r\n               best = prev;\r\n            }\r\n         }\r\n      }\r\n      prev = &node->next;\r\n      node = node->next;\r\n   }\r\n\r\n   best_x = (best == NULL) ? 0 : (*best)->x;\r\n\r\n   // if doing best-fit (BF), we also have to try aligning right edge to each node position\r\n   //\r\n   // e.g, if fitting\r\n   //\r\n   //     ____________________\r\n   //    |____________________|\r\n   //\r\n   //            into\r\n   //\r\n   //   |                         |\r\n   //   |             ____________|\r\n   //   |____________|\r\n   //\r\n   // then right-aligned reduces waste, but bottom-left BL is always chooses left-aligned\r\n   //\r\n   // This makes BF take about 2x the time\r\n\r\n   if (c->heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight) {\r\n      tail = c->active_head;\r\n      node = c->active_head;\r\n      prev = &c->active_head;\r\n      // find first node that's admissible\r\n      while (tail->x < width)\r\n         tail = tail->next;\r\n      while (tail) {\r\n         int xpos = tail->x - width;\r\n         int y,waste;\r\n         STBRP_ASSERT(xpos >= 0);\r\n         // find the left position that matches this\r\n         while (node->next->x <= xpos) {\r\n            prev = &node->next;\r\n            node = node->next;\r\n         }\r\n         STBRP_ASSERT(node->next->x > xpos && node->x <= xpos);\r\n         y = stbrp__skyline_find_min_y(c, node, xpos, width, &waste);\r\n         if (y + height <= c->height) {\r\n            if (y <= best_y) {\r\n               if (y < best_y || waste < best_waste || (waste==best_waste && xpos < best_x)) {\r\n                  best_x = xpos;\r\n                  STBRP_ASSERT(y <= best_y);\r\n                  best_y = y;\r\n                  best_waste = waste;\r\n                  best = prev;\r\n               }\r\n            }\r\n         }\r\n         tail = tail->next;\r\n      }\r\n   }\r\n\r\n   fr.prev_link = best;\r\n   fr.x = best_x;\r\n   fr.y = best_y;\r\n   return fr;\r\n}\r\n\r\nstatic stbrp__findresult stbrp__skyline_pack_rectangle(stbrp_context *context, int width, int height)\r\n{\r\n   // find best position according to heuristic\r\n   stbrp__findresult res = stbrp__skyline_find_best_pos(context, width, height);\r\n   stbrp_node *node, *cur;\r\n\r\n   // bail if:\r\n   //    1. it failed\r\n   //    2. the best node doesn't fit (we don't always check this)\r\n   //    3. we're out of memory\r\n   if (res.prev_link == NULL || res.y + height > context->height || context->free_head == NULL) {\r\n      res.prev_link = NULL;\r\n      return res;\r\n   }\r\n\r\n   // on success, create new node\r\n   node = context->free_head;\r\n   node->x = (stbrp_coord) res.x;\r\n   node->y = (stbrp_coord) (res.y + height);\r\n\r\n   context->free_head = node->next;\r\n\r\n   // insert the new node into the right starting point, and\r\n   // let 'cur' point to the remaining nodes needing to be\r\n   // stiched back in\r\n\r\n   cur = *res.prev_link;\r\n   if (cur->x < res.x) {\r\n      // preserve the existing one, so start testing with the next one\r\n      stbrp_node *next = cur->next;\r\n      cur->next = node;\r\n      cur = next;\r\n   } else {\r\n      *res.prev_link = node;\r\n   }\r\n\r\n   // from here, traverse cur and free the nodes, until we get to one\r\n   // that shouldn't be freed\r\n   while (cur->next && cur->next->x <= res.x + width) {\r\n      stbrp_node *next = cur->next;\r\n      // move the current node to the free list\r\n      cur->next = context->free_head;\r\n      context->free_head = cur;\r\n      cur = next;\r\n   }\r\n\r\n   // stitch the list back in\r\n   node->next = cur;\r\n\r\n   if (cur->x < res.x + width)\r\n      cur->x = (stbrp_coord) (res.x + width);\r\n\r\n#ifdef _DEBUG\r\n   cur = context->active_head;\r\n   while (cur->x < context->width) {\r\n      STBRP_ASSERT(cur->x < cur->next->x);\r\n      cur = cur->next;\r\n   }\r\n   STBRP_ASSERT(cur->next == NULL);\r\n\r\n   {\r\n      int count=0;\r\n      cur = context->active_head;\r\n      while (cur) {\r\n         cur = cur->next;\r\n         ++count;\r\n      }\r\n      cur = context->free_head;\r\n      while (cur) {\r\n         cur = cur->next;\r\n         ++count;\r\n      }\r\n      STBRP_ASSERT(count == context->num_nodes+2);\r\n   }\r\n#endif\r\n\r\n   return res;\r\n}\r\n\r\n// [DEAR IMGUI] Added STBRP__CDECL\r\nstatic int STBRP__CDECL rect_height_compare(const void *a, const void *b)\r\n{\r\n   const stbrp_rect *p = (const stbrp_rect *) a;\r\n   const stbrp_rect *q = (const stbrp_rect *) b;\r\n   if (p->h > q->h)\r\n      return -1;\r\n   if (p->h < q->h)\r\n      return  1;\r\n   return (p->w > q->w) ? -1 : (p->w < q->w);\r\n}\r\n\r\n// [DEAR IMGUI] Added STBRP__CDECL\r\nstatic int STBRP__CDECL rect_original_order(const void *a, const void *b)\r\n{\r\n   const stbrp_rect *p = (const stbrp_rect *) a;\r\n   const stbrp_rect *q = (const stbrp_rect *) b;\r\n   return (p->was_packed < q->was_packed) ? -1 : (p->was_packed > q->was_packed);\r\n}\r\n\r\n#ifdef STBRP_LARGE_RECTS\r\n#define STBRP__MAXVAL  0xffffffff\r\n#else\r\n#define STBRP__MAXVAL  0xffff\r\n#endif\r\n\r\nSTBRP_DEF int stbrp_pack_rects(stbrp_context *context, stbrp_rect *rects, int num_rects)\r\n{\r\n   int i, all_rects_packed = 1;\r\n\r\n   // we use the 'was_packed' field internally to allow sorting/unsorting\r\n   for (i=0; i < num_rects; ++i) {\r\n      rects[i].was_packed = i;\r\n   }\r\n\r\n   // sort according to heuristic\r\n   STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_height_compare);\r\n\r\n   for (i=0; i < num_rects; ++i) {\r\n      if (rects[i].w == 0 || rects[i].h == 0) {\r\n         rects[i].x = rects[i].y = 0;  // empty rect needs no space\r\n      } else {\r\n         stbrp__findresult fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h);\r\n         if (fr.prev_link) {\r\n            rects[i].x = (stbrp_coord) fr.x;\r\n            rects[i].y = (stbrp_coord) fr.y;\r\n         } else {\r\n            rects[i].x = rects[i].y = STBRP__MAXVAL;\r\n         }\r\n      }\r\n   }\r\n\r\n   // unsort\r\n   STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_original_order);\r\n\r\n   // set was_packed flags and all_rects_packed status\r\n   for (i=0; i < num_rects; ++i) {\r\n      rects[i].was_packed = !(rects[i].x == STBRP__MAXVAL && rects[i].y == STBRP__MAXVAL);\r\n      if (!rects[i].was_packed)\r\n         all_rects_packed = 0;\r\n   }\r\n\r\n   // return the all_rects_packed status\r\n   return all_rects_packed;\r\n}\r\n#endif\r\n\r\n/*\r\n------------------------------------------------------------------------------\r\nThis software is available under 2 licenses -- choose whichever you prefer.\r\n------------------------------------------------------------------------------\r\nALTERNATIVE A - MIT License\r\nCopyright (c) 2017 Sean Barrett\r\nPermission is hereby granted, free of charge, to any person obtaining a copy of\r\nthis software and associated documentation files (the \"Software\"), to deal in\r\nthe Software without restriction, including without limitation the rights to\r\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\r\nof the Software, and to permit persons to whom the Software is furnished to do\r\nso, subject to the following conditions:\r\nThe above copyright notice and this permission notice shall be included in all\r\ncopies or substantial portions of the Software.\r\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\nSOFTWARE.\r\n------------------------------------------------------------------------------\r\nALTERNATIVE B - Public Domain (www.unlicense.org)\r\nThis is free and unencumbered software released into the public domain.\r\nAnyone is free to copy, modify, publish, use, compile, sell, or distribute this\r\nsoftware, either in source code form or as a compiled binary, for any purpose,\r\ncommercial or non-commercial, and by any means.\r\nIn jurisdictions that recognize copyright laws, the author or authors of this\r\nsoftware dedicate any and all copyright interest in the software to the public\r\ndomain. We make this dedication for the benefit of the public at large and to\r\nthe detriment of our heirs and successors. We intend this dedication to be an\r\novert act of relinquishment in perpetuity of all present and future rights to\r\nthis software under copyright law.\r\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\nAUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\r\nACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\r\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n------------------------------------------------------------------------------\r\n*/\r\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/imgui/imstb_textedit.h",
    "content": "// [DEAR IMGUI]\r\n// This is a slightly modified version of stb_textedit.h 1.13.\r\n// Those changes would need to be pushed into nothings/stb:\r\n// - Fix in stb_textedit_discard_redo (see https://github.com/nothings/stb/issues/321)\r\n// Grep for [DEAR IMGUI] to find the changes.\r\n\r\n// stb_textedit.h - v1.13  - public domain - Sean Barrett\r\n// Development of this library was sponsored by RAD Game Tools\r\n//\r\n// This C header file implements the guts of a multi-line text-editing\r\n// widget; you implement display, word-wrapping, and low-level string\r\n// insertion/deletion, and stb_textedit will map user inputs into\r\n// insertions & deletions, plus updates to the cursor position,\r\n// selection state, and undo state.\r\n//\r\n// It is intended for use in games and other systems that need to build\r\n// their own custom widgets and which do not have heavy text-editing\r\n// requirements (this library is not recommended for use for editing large\r\n// texts, as its performance does not scale and it has limited undo).\r\n//\r\n// Non-trivial behaviors are modelled after Windows text controls.\r\n//\r\n//\r\n// LICENSE\r\n//\r\n// See end of file for license information.\r\n//\r\n//\r\n// DEPENDENCIES\r\n//\r\n// Uses the C runtime function 'memmove', which you can override\r\n// by defining STB_TEXTEDIT_memmove before the implementation.\r\n// Uses no other functions. Performs no runtime allocations.\r\n//\r\n//\r\n// VERSION HISTORY\r\n//\r\n//   1.13 (2019-02-07) fix bug in undo size management\r\n//   1.12 (2018-01-29) user can change STB_TEXTEDIT_KEYTYPE, fix redo to avoid crash\r\n//   1.11 (2017-03-03) fix HOME on last line, dragging off single-line textfield\r\n//   1.10 (2016-10-25) supress warnings about casting away const with -Wcast-qual\r\n//   1.9  (2016-08-27) customizable move-by-word\r\n//   1.8  (2016-04-02) better keyboard handling when mouse button is down\r\n//   1.7  (2015-09-13) change y range handling in case baseline is non-0\r\n//   1.6  (2015-04-15) allow STB_TEXTEDIT_memmove\r\n//   1.5  (2014-09-10) add support for secondary keys for OS X\r\n//   1.4  (2014-08-17) fix signed/unsigned warnings\r\n//   1.3  (2014-06-19) fix mouse clicking to round to nearest char boundary\r\n//   1.2  (2014-05-27) fix some RAD types that had crept into the new code\r\n//   1.1  (2013-12-15) move-by-word (requires STB_TEXTEDIT_IS_SPACE )\r\n//   1.0  (2012-07-26) improve documentation, initial public release\r\n//   0.3  (2012-02-24) bugfixes, single-line mode; insert mode\r\n//   0.2  (2011-11-28) fixes to undo/redo\r\n//   0.1  (2010-07-08) initial version\r\n//\r\n// ADDITIONAL CONTRIBUTORS\r\n//\r\n//   Ulf Winklemann: move-by-word in 1.1\r\n//   Fabian Giesen: secondary key inputs in 1.5\r\n//   Martins Mozeiko: STB_TEXTEDIT_memmove in 1.6\r\n//\r\n//   Bugfixes:\r\n//      Scott Graham\r\n//      Daniel Keller\r\n//      Omar Cornut\r\n//      Dan Thompson\r\n//\r\n// USAGE\r\n//\r\n// This file behaves differently depending on what symbols you define\r\n// before including it.\r\n//\r\n//\r\n// Header-file mode:\r\n//\r\n//   If you do not define STB_TEXTEDIT_IMPLEMENTATION before including this,\r\n//   it will operate in \"header file\" mode. In this mode, it declares a\r\n//   single public symbol, STB_TexteditState, which encapsulates the current\r\n//   state of a text widget (except for the string, which you will store\r\n//   separately).\r\n//\r\n//   To compile in this mode, you must define STB_TEXTEDIT_CHARTYPE to a\r\n//   primitive type that defines a single character (e.g. char, wchar_t, etc).\r\n//\r\n//   To save space or increase undo-ability, you can optionally define the\r\n//   following things that are used by the undo system:\r\n//\r\n//      STB_TEXTEDIT_POSITIONTYPE         small int type encoding a valid cursor position\r\n//      STB_TEXTEDIT_UNDOSTATECOUNT       the number of undo states to allow\r\n//      STB_TEXTEDIT_UNDOCHARCOUNT        the number of characters to store in the undo buffer\r\n//\r\n//   If you don't define these, they are set to permissive types and\r\n//   moderate sizes. The undo system does no memory allocations, so\r\n//   it grows STB_TexteditState by the worst-case storage which is (in bytes):\r\n//\r\n//        [4 + 3 * sizeof(STB_TEXTEDIT_POSITIONTYPE)] * STB_TEXTEDIT_UNDOSTATE_COUNT\r\n//      +          sizeof(STB_TEXTEDIT_CHARTYPE)      * STB_TEXTEDIT_UNDOCHAR_COUNT\r\n//\r\n//\r\n// Implementation mode:\r\n//\r\n//   If you define STB_TEXTEDIT_IMPLEMENTATION before including this, it\r\n//   will compile the implementation of the text edit widget, depending\r\n//   on a large number of symbols which must be defined before the include.\r\n//\r\n//   The implementation is defined only as static functions. You will then\r\n//   need to provide your own APIs in the same file which will access the\r\n//   static functions.\r\n//\r\n//   The basic concept is that you provide a \"string\" object which\r\n//   behaves like an array of characters. stb_textedit uses indices to\r\n//   refer to positions in the string, implicitly representing positions\r\n//   in the displayed textedit. This is true for both plain text and\r\n//   rich text; even with rich text stb_truetype interacts with your\r\n//   code as if there was an array of all the displayed characters.\r\n//\r\n// Symbols that must be the same in header-file and implementation mode:\r\n//\r\n//     STB_TEXTEDIT_CHARTYPE             the character type\r\n//     STB_TEXTEDIT_POSITIONTYPE         small type that is a valid cursor position\r\n//     STB_TEXTEDIT_UNDOSTATECOUNT       the number of undo states to allow\r\n//     STB_TEXTEDIT_UNDOCHARCOUNT        the number of characters to store in the undo buffer\r\n//\r\n// Symbols you must define for implementation mode:\r\n//\r\n//    STB_TEXTEDIT_STRING               the type of object representing a string being edited,\r\n//                                      typically this is a wrapper object with other data you need\r\n//\r\n//    STB_TEXTEDIT_STRINGLEN(obj)       the length of the string (ideally O(1))\r\n//    STB_TEXTEDIT_LAYOUTROW(&r,obj,n)  returns the results of laying out a line of characters\r\n//                                        starting from character #n (see discussion below)\r\n//    STB_TEXTEDIT_GETWIDTH(obj,n,i)    returns the pixel delta from the xpos of the i'th character\r\n//                                        to the xpos of the i+1'th char for a line of characters\r\n//                                        starting at character #n (i.e. accounts for kerning\r\n//                                        with previous char)\r\n//    STB_TEXTEDIT_KEYTOTEXT(k)         maps a keyboard input to an insertable character\r\n//                                        (return type is int, -1 means not valid to insert)\r\n//    STB_TEXTEDIT_GETCHAR(obj,i)       returns the i'th character of obj, 0-based\r\n//    STB_TEXTEDIT_NEWLINE              the character returned by _GETCHAR() we recognize\r\n//                                        as manually wordwrapping for end-of-line positioning\r\n//\r\n//    STB_TEXTEDIT_DELETECHARS(obj,i,n)      delete n characters starting at i\r\n//    STB_TEXTEDIT_INSERTCHARS(obj,i,c*,n)   insert n characters at i (pointed to by STB_TEXTEDIT_CHARTYPE*)\r\n//\r\n//    STB_TEXTEDIT_K_SHIFT       a power of two that is or'd in to a keyboard input to represent the shift key\r\n//\r\n//    STB_TEXTEDIT_K_LEFT        keyboard input to move cursor left\r\n//    STB_TEXTEDIT_K_RIGHT       keyboard input to move cursor right\r\n//    STB_TEXTEDIT_K_UP          keyboard input to move cursor up\r\n//    STB_TEXTEDIT_K_DOWN        keyboard input to move cursor down\r\n//    STB_TEXTEDIT_K_PGUP        keyboard input to move cursor up a page\r\n//    STB_TEXTEDIT_K_PGDOWN      keyboard input to move cursor down a page\r\n//    STB_TEXTEDIT_K_LINESTART   keyboard input to move cursor to start of line  // e.g. HOME\r\n//    STB_TEXTEDIT_K_LINEEND     keyboard input to move cursor to end of line    // e.g. END\r\n//    STB_TEXTEDIT_K_TEXTSTART   keyboard input to move cursor to start of text  // e.g. ctrl-HOME\r\n//    STB_TEXTEDIT_K_TEXTEND     keyboard input to move cursor to end of text    // e.g. ctrl-END\r\n//    STB_TEXTEDIT_K_DELETE      keyboard input to delete selection or character under cursor\r\n//    STB_TEXTEDIT_K_BACKSPACE   keyboard input to delete selection or character left of cursor\r\n//    STB_TEXTEDIT_K_UNDO        keyboard input to perform undo\r\n//    STB_TEXTEDIT_K_REDO        keyboard input to perform redo\r\n//\r\n// Optional:\r\n//    STB_TEXTEDIT_K_INSERT              keyboard input to toggle insert mode\r\n//    STB_TEXTEDIT_IS_SPACE(ch)          true if character is whitespace (e.g. 'isspace'),\r\n//                                          required for default WORDLEFT/WORDRIGHT handlers\r\n//    STB_TEXTEDIT_MOVEWORDLEFT(obj,i)   custom handler for WORDLEFT, returns index to move cursor to\r\n//    STB_TEXTEDIT_MOVEWORDRIGHT(obj,i)  custom handler for WORDRIGHT, returns index to move cursor to\r\n//    STB_TEXTEDIT_K_WORDLEFT            keyboard input to move cursor left one word // e.g. ctrl-LEFT\r\n//    STB_TEXTEDIT_K_WORDRIGHT           keyboard input to move cursor right one word // e.g. ctrl-RIGHT\r\n//    STB_TEXTEDIT_K_LINESTART2          secondary keyboard input to move cursor to start of line\r\n//    STB_TEXTEDIT_K_LINEEND2            secondary keyboard input to move cursor to end of line\r\n//    STB_TEXTEDIT_K_TEXTSTART2          secondary keyboard input to move cursor to start of text\r\n//    STB_TEXTEDIT_K_TEXTEND2            secondary keyboard input to move cursor to end of text\r\n//\r\n// Keyboard input must be encoded as a single integer value; e.g. a character code\r\n// and some bitflags that represent shift states. to simplify the interface, SHIFT must\r\n// be a bitflag, so we can test the shifted state of cursor movements to allow selection,\r\n// i.e. (STB_TEXTEDIT_K_RIGHT|STB_TEXTEDIT_K_SHIFT) should be shifted right-arrow.\r\n//\r\n// You can encode other things, such as CONTROL or ALT, in additional bits, and\r\n// then test for their presence in e.g. STB_TEXTEDIT_K_WORDLEFT. For example,\r\n// my Windows implementations add an additional CONTROL bit, and an additional KEYDOWN\r\n// bit. Then all of the STB_TEXTEDIT_K_ values bitwise-or in the KEYDOWN bit,\r\n// and I pass both WM_KEYDOWN and WM_CHAR events to the \"key\" function in the\r\n// API below. The control keys will only match WM_KEYDOWN events because of the\r\n// keydown bit I add, and STB_TEXTEDIT_KEYTOTEXT only tests for the KEYDOWN\r\n// bit so it only decodes WM_CHAR events.\r\n//\r\n// STB_TEXTEDIT_LAYOUTROW returns information about the shape of one displayed\r\n// row of characters assuming they start on the i'th character--the width and\r\n// the height and the number of characters consumed. This allows this library\r\n// to traverse the entire layout incrementally. You need to compute word-wrapping\r\n// here.\r\n//\r\n// Each textfield keeps its own insert mode state, which is not how normal\r\n// applications work. To keep an app-wide insert mode, update/copy the\r\n// \"insert_mode\" field of STB_TexteditState before/after calling API functions.\r\n//\r\n// API\r\n//\r\n//    void stb_textedit_initialize_state(STB_TexteditState *state, int is_single_line)\r\n//\r\n//    void stb_textedit_click(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y)\r\n//    void stb_textedit_drag(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y)\r\n//    int  stb_textedit_cut(STB_TEXTEDIT_STRING *str, STB_TexteditState *state)\r\n//    int  stb_textedit_paste(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE *text, int len)\r\n//    void stb_textedit_key(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXEDIT_KEYTYPE key)\r\n//\r\n//    Each of these functions potentially updates the string and updates the\r\n//    state.\r\n//\r\n//      initialize_state:\r\n//          set the textedit state to a known good default state when initially\r\n//          constructing the textedit.\r\n//\r\n//      click:\r\n//          call this with the mouse x,y on a mouse down; it will update the cursor\r\n//          and reset the selection start/end to the cursor point. the x,y must\r\n//          be relative to the text widget, with (0,0) being the top left.\r\n//\r\n//      drag:\r\n//          call this with the mouse x,y on a mouse drag/up; it will update the\r\n//          cursor and the selection end point\r\n//\r\n//      cut:\r\n//          call this to delete the current selection; returns true if there was\r\n//          one. you should FIRST copy the current selection to the system paste buffer.\r\n//          (To copy, just copy the current selection out of the string yourself.)\r\n//\r\n//      paste:\r\n//          call this to paste text at the current cursor point or over the current\r\n//          selection if there is one.\r\n//\r\n//      key:\r\n//          call this for keyboard inputs sent to the textfield. you can use it\r\n//          for \"key down\" events or for \"translated\" key events. if you need to\r\n//          do both (as in Win32), or distinguish Unicode characters from control\r\n//          inputs, set a high bit to distinguish the two; then you can define the\r\n//          various definitions like STB_TEXTEDIT_K_LEFT have the is-key-event bit\r\n//          set, and make STB_TEXTEDIT_KEYTOCHAR check that the is-key-event bit is\r\n//          clear. STB_TEXTEDIT_KEYTYPE defaults to int, but you can #define it to\r\n//          anything other type you wante before including.\r\n//\r\n//\r\n//   When rendering, you can read the cursor position and selection state from\r\n//   the STB_TexteditState.\r\n//\r\n//\r\n// Notes:\r\n//\r\n// This is designed to be usable in IMGUI, so it allows for the possibility of\r\n// running in an IMGUI that has NOT cached the multi-line layout. For this\r\n// reason, it provides an interface that is compatible with computing the\r\n// layout incrementally--we try to make sure we make as few passes through\r\n// as possible. (For example, to locate the mouse pointer in the text, we\r\n// could define functions that return the X and Y positions of characters\r\n// and binary search Y and then X, but if we're doing dynamic layout this\r\n// will run the layout algorithm many times, so instead we manually search\r\n// forward in one pass. Similar logic applies to e.g. up-arrow and\r\n// down-arrow movement.)\r\n//\r\n// If it's run in a widget that *has* cached the layout, then this is less\r\n// efficient, but it's not horrible on modern computers. But you wouldn't\r\n// want to edit million-line files with it.\r\n\r\n\r\n////////////////////////////////////////////////////////////////////////////\r\n////////////////////////////////////////////////////////////////////////////\r\n////\r\n////   Header-file mode\r\n////\r\n////\r\n\r\n#ifndef INCLUDE_STB_TEXTEDIT_H\r\n#define INCLUDE_STB_TEXTEDIT_H\r\n\r\n////////////////////////////////////////////////////////////////////////\r\n//\r\n//     STB_TexteditState\r\n//\r\n// Definition of STB_TexteditState which you should store\r\n// per-textfield; it includes cursor position, selection state,\r\n// and undo state.\r\n//\r\n\r\n#ifndef STB_TEXTEDIT_UNDOSTATECOUNT\r\n#define STB_TEXTEDIT_UNDOSTATECOUNT   99\r\n#endif\r\n#ifndef STB_TEXTEDIT_UNDOCHARCOUNT\r\n#define STB_TEXTEDIT_UNDOCHARCOUNT   999\r\n#endif\r\n#ifndef STB_TEXTEDIT_CHARTYPE\r\n#define STB_TEXTEDIT_CHARTYPE        int\r\n#endif\r\n#ifndef STB_TEXTEDIT_POSITIONTYPE\r\n#define STB_TEXTEDIT_POSITIONTYPE    int\r\n#endif\r\n\r\ntypedef struct\r\n{\r\n   // private data\r\n   STB_TEXTEDIT_POSITIONTYPE  where;\r\n   STB_TEXTEDIT_POSITIONTYPE  insert_length;\r\n   STB_TEXTEDIT_POSITIONTYPE  delete_length;\r\n   int                        char_storage;\r\n} StbUndoRecord;\r\n\r\ntypedef struct\r\n{\r\n   // private data\r\n   StbUndoRecord          undo_rec [STB_TEXTEDIT_UNDOSTATECOUNT];\r\n   STB_TEXTEDIT_CHARTYPE  undo_char[STB_TEXTEDIT_UNDOCHARCOUNT];\r\n   short undo_point, redo_point;\r\n   int undo_char_point, redo_char_point;\r\n} StbUndoState;\r\n\r\ntypedef struct\r\n{\r\n   /////////////////////\r\n   //\r\n   // public data\r\n   //\r\n\r\n   int cursor;\r\n   // position of the text cursor within the string\r\n\r\n   int select_start;          // selection start point\r\n   int select_end;\r\n   // selection start and end point in characters; if equal, no selection.\r\n   // note that start may be less than or greater than end (e.g. when\r\n   // dragging the mouse, start is where the initial click was, and you\r\n   // can drag in either direction)\r\n\r\n   unsigned char insert_mode;\r\n   // each textfield keeps its own insert mode state. to keep an app-wide\r\n   // insert mode, copy this value in/out of the app state\r\n\r\n   int row_count_per_page;\r\n   // page size in number of row.\r\n   // this value MUST be set to >0 for pageup or pagedown in multilines documents.\r\n\r\n   /////////////////////\r\n   //\r\n   // private data\r\n   //\r\n   unsigned char cursor_at_end_of_line; // not implemented yet\r\n   unsigned char initialized;\r\n   unsigned char has_preferred_x;\r\n   unsigned char single_line;\r\n   unsigned char padding1, padding2, padding3;\r\n   float preferred_x; // this determines where the cursor up/down tries to seek to along x\r\n   StbUndoState undostate;\r\n} STB_TexteditState;\r\n\r\n\r\n////////////////////////////////////////////////////////////////////////\r\n//\r\n//     StbTexteditRow\r\n//\r\n// Result of layout query, used by stb_textedit to determine where\r\n// the text in each row is.\r\n\r\n// result of layout query\r\ntypedef struct\r\n{\r\n   float x0,x1;             // starting x location, end x location (allows for align=right, etc)\r\n   float baseline_y_delta;  // position of baseline relative to previous row's baseline\r\n   float ymin,ymax;         // height of row above and below baseline\r\n   int num_chars;\r\n} StbTexteditRow;\r\n#endif //INCLUDE_STB_TEXTEDIT_H\r\n\r\n\r\n////////////////////////////////////////////////////////////////////////////\r\n////////////////////////////////////////////////////////////////////////////\r\n////\r\n////   Implementation mode\r\n////\r\n////\r\n\r\n\r\n// implementation isn't include-guarded, since it might have indirectly\r\n// included just the \"header\" portion\r\n#ifdef STB_TEXTEDIT_IMPLEMENTATION\r\n\r\n#ifndef STB_TEXTEDIT_memmove\r\n#include <string.h>\r\n#define STB_TEXTEDIT_memmove memmove\r\n#endif\r\n\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n//\r\n//      Mouse input handling\r\n//\r\n\r\n// traverse the layout to locate the nearest character to a display position\r\nstatic int stb_text_locate_coord(STB_TEXTEDIT_STRING *str, float x, float y)\r\n{\r\n   StbTexteditRow r;\r\n   int n = STB_TEXTEDIT_STRINGLEN(str);\r\n   float base_y = 0, prev_x;\r\n   int i=0, k;\r\n\r\n   r.x0 = r.x1 = 0;\r\n   r.ymin = r.ymax = 0;\r\n   r.num_chars = 0;\r\n\r\n   // search rows to find one that straddles 'y'\r\n   while (i < n) {\r\n      STB_TEXTEDIT_LAYOUTROW(&r, str, i);\r\n      if (r.num_chars <= 0)\r\n         return n;\r\n\r\n      if (i==0 && y < base_y + r.ymin)\r\n         return 0;\r\n\r\n      if (y < base_y + r.ymax)\r\n         break;\r\n\r\n      i += r.num_chars;\r\n      base_y += r.baseline_y_delta;\r\n   }\r\n\r\n   // below all text, return 'after' last character\r\n   if (i >= n)\r\n      return n;\r\n\r\n   // check if it's before the beginning of the line\r\n   if (x < r.x0)\r\n      return i;\r\n\r\n   // check if it's before the end of the line\r\n   if (x < r.x1) {\r\n      // search characters in row for one that straddles 'x'\r\n      prev_x = r.x0;\r\n      for (k=0; k < r.num_chars; ++k) {\r\n         float w = STB_TEXTEDIT_GETWIDTH(str, i, k);\r\n         if (x < prev_x+w) {\r\n            if (x < prev_x+w/2)\r\n               return k+i;\r\n            else\r\n               return k+i+1;\r\n         }\r\n         prev_x += w;\r\n      }\r\n      // shouldn't happen, but if it does, fall through to end-of-line case\r\n   }\r\n\r\n   // if the last character is a newline, return that. otherwise return 'after' the last character\r\n   if (STB_TEXTEDIT_GETCHAR(str, i+r.num_chars-1) == STB_TEXTEDIT_NEWLINE)\r\n      return i+r.num_chars-1;\r\n   else\r\n      return i+r.num_chars;\r\n}\r\n\r\n// API click: on mouse down, move the cursor to the clicked location, and reset the selection\r\nstatic void stb_textedit_click(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y)\r\n{\r\n   // In single-line mode, just always make y = 0. This lets the drag keep working if the mouse\r\n   // goes off the top or bottom of the text\r\n   if( state->single_line )\r\n   {\r\n      StbTexteditRow r;\r\n      STB_TEXTEDIT_LAYOUTROW(&r, str, 0);\r\n      y = r.ymin;\r\n   }\r\n\r\n   state->cursor = stb_text_locate_coord(str, x, y);\r\n   state->select_start = state->cursor;\r\n   state->select_end = state->cursor;\r\n   state->has_preferred_x = 0;\r\n}\r\n\r\n// API drag: on mouse drag, move the cursor and selection endpoint to the clicked location\r\nstatic void stb_textedit_drag(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y)\r\n{\r\n   int p = 0;\r\n\r\n   // In single-line mode, just always make y = 0. This lets the drag keep working if the mouse\r\n   // goes off the top or bottom of the text\r\n   if( state->single_line )\r\n   {\r\n      StbTexteditRow r;\r\n      STB_TEXTEDIT_LAYOUTROW(&r, str, 0);\r\n      y = r.ymin;\r\n   }\r\n\r\n   if (state->select_start == state->select_end)\r\n      state->select_start = state->cursor;\r\n\r\n   p = stb_text_locate_coord(str, x, y);\r\n   state->cursor = state->select_end = p;\r\n}\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n//\r\n//      Keyboard input handling\r\n//\r\n\r\n// forward declarations\r\nstatic void stb_text_undo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state);\r\nstatic void stb_text_redo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state);\r\nstatic void stb_text_makeundo_delete(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int length);\r\nstatic void stb_text_makeundo_insert(STB_TexteditState *state, int where, int length);\r\nstatic void stb_text_makeundo_replace(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int old_length, int new_length);\r\n\r\ntypedef struct\r\n{\r\n   float x,y;    // position of n'th character\r\n   float height; // height of line\r\n   int first_char, length; // first char of row, and length\r\n   int prev_first;  // first char of previous row\r\n} StbFindState;\r\n\r\n// find the x/y location of a character, and remember info about the previous row in\r\n// case we get a move-up event (for page up, we'll have to rescan)\r\nstatic void stb_textedit_find_charpos(StbFindState *find, STB_TEXTEDIT_STRING *str, int n, int single_line)\r\n{\r\n   StbTexteditRow r;\r\n   int prev_start = 0;\r\n   int z = STB_TEXTEDIT_STRINGLEN(str);\r\n   int i=0, first;\r\n\r\n   if (n == z) {\r\n      // if it's at the end, then find the last line -- simpler than trying to\r\n      // explicitly handle this case in the regular code\r\n      if (single_line) {\r\n         STB_TEXTEDIT_LAYOUTROW(&r, str, 0);\r\n         find->y = 0;\r\n         find->first_char = 0;\r\n         find->length = z;\r\n         find->height = r.ymax - r.ymin;\r\n         find->x = r.x1;\r\n      } else {\r\n         find->y = 0;\r\n         find->x = 0;\r\n         find->height = 1;\r\n         while (i < z) {\r\n            STB_TEXTEDIT_LAYOUTROW(&r, str, i);\r\n            prev_start = i;\r\n            i += r.num_chars;\r\n         }\r\n         find->first_char = i;\r\n         find->length = 0;\r\n         find->prev_first = prev_start;\r\n      }\r\n      return;\r\n   }\r\n\r\n   // search rows to find the one that straddles character n\r\n   find->y = 0;\r\n\r\n   for(;;) {\r\n      STB_TEXTEDIT_LAYOUTROW(&r, str, i);\r\n      if (n < i + r.num_chars)\r\n         break;\r\n      prev_start = i;\r\n      i += r.num_chars;\r\n      find->y += r.baseline_y_delta;\r\n   }\r\n\r\n   find->first_char = first = i;\r\n   find->length = r.num_chars;\r\n   find->height = r.ymax - r.ymin;\r\n   find->prev_first = prev_start;\r\n\r\n   // now scan to find xpos\r\n   find->x = r.x0;\r\n   for (i=0; first+i < n; ++i)\r\n      find->x += STB_TEXTEDIT_GETWIDTH(str, first, i);\r\n}\r\n\r\n#define STB_TEXT_HAS_SELECTION(s)   ((s)->select_start != (s)->select_end)\r\n\r\n// make the selection/cursor state valid if client altered the string\r\nstatic void stb_textedit_clamp(STB_TEXTEDIT_STRING *str, STB_TexteditState *state)\r\n{\r\n   int n = STB_TEXTEDIT_STRINGLEN(str);\r\n   if (STB_TEXT_HAS_SELECTION(state)) {\r\n      if (state->select_start > n) state->select_start = n;\r\n      if (state->select_end   > n) state->select_end = n;\r\n      // if clamping forced them to be equal, move the cursor to match\r\n      if (state->select_start == state->select_end)\r\n         state->cursor = state->select_start;\r\n   }\r\n   if (state->cursor > n) state->cursor = n;\r\n}\r\n\r\n// delete characters while updating undo\r\nstatic void stb_textedit_delete(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int len)\r\n{\r\n   stb_text_makeundo_delete(str, state, where, len);\r\n   STB_TEXTEDIT_DELETECHARS(str, where, len);\r\n   state->has_preferred_x = 0;\r\n}\r\n\r\n// delete the section\r\nstatic void stb_textedit_delete_selection(STB_TEXTEDIT_STRING *str, STB_TexteditState *state)\r\n{\r\n   stb_textedit_clamp(str, state);\r\n   if (STB_TEXT_HAS_SELECTION(state)) {\r\n      if (state->select_start < state->select_end) {\r\n         stb_textedit_delete(str, state, state->select_start, state->select_end - state->select_start);\r\n         state->select_end = state->cursor = state->select_start;\r\n      } else {\r\n         stb_textedit_delete(str, state, state->select_end, state->select_start - state->select_end);\r\n         state->select_start = state->cursor = state->select_end;\r\n      }\r\n      state->has_preferred_x = 0;\r\n   }\r\n}\r\n\r\n// canoncialize the selection so start <= end\r\nstatic void stb_textedit_sortselection(STB_TexteditState *state)\r\n{\r\n   if (state->select_end < state->select_start) {\r\n      int temp = state->select_end;\r\n      state->select_end = state->select_start;\r\n      state->select_start = temp;\r\n   }\r\n}\r\n\r\n// move cursor to first character of selection\r\nstatic void stb_textedit_move_to_first(STB_TexteditState *state)\r\n{\r\n   if (STB_TEXT_HAS_SELECTION(state)) {\r\n      stb_textedit_sortselection(state);\r\n      state->cursor = state->select_start;\r\n      state->select_end = state->select_start;\r\n      state->has_preferred_x = 0;\r\n   }\r\n}\r\n\r\n// move cursor to last character of selection\r\nstatic void stb_textedit_move_to_last(STB_TEXTEDIT_STRING *str, STB_TexteditState *state)\r\n{\r\n   if (STB_TEXT_HAS_SELECTION(state)) {\r\n      stb_textedit_sortselection(state);\r\n      stb_textedit_clamp(str, state);\r\n      state->cursor = state->select_end;\r\n      state->select_start = state->select_end;\r\n      state->has_preferred_x = 0;\r\n   }\r\n}\r\n\r\n#ifdef STB_TEXTEDIT_IS_SPACE\r\nstatic int is_word_boundary( STB_TEXTEDIT_STRING *str, int idx )\r\n{\r\n   return idx > 0 ? (STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(str,idx-1) ) && !STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(str, idx) ) ) : 1;\r\n}\r\n\r\n#ifndef STB_TEXTEDIT_MOVEWORDLEFT\r\nstatic int stb_textedit_move_to_word_previous( STB_TEXTEDIT_STRING *str, int c )\r\n{\r\n   --c; // always move at least one character\r\n   while( c >= 0 && !is_word_boundary( str, c ) )\r\n      --c;\r\n\r\n   if( c < 0 )\r\n      c = 0;\r\n\r\n   return c;\r\n}\r\n#define STB_TEXTEDIT_MOVEWORDLEFT stb_textedit_move_to_word_previous\r\n#endif\r\n\r\n#ifndef STB_TEXTEDIT_MOVEWORDRIGHT\r\nstatic int stb_textedit_move_to_word_next( STB_TEXTEDIT_STRING *str, int c )\r\n{\r\n   const int len = STB_TEXTEDIT_STRINGLEN(str);\r\n   ++c; // always move at least one character\r\n   while( c < len && !is_word_boundary( str, c ) )\r\n      ++c;\r\n\r\n   if( c > len )\r\n      c = len;\r\n\r\n   return c;\r\n}\r\n#define STB_TEXTEDIT_MOVEWORDRIGHT stb_textedit_move_to_word_next\r\n#endif\r\n\r\n#endif\r\n\r\n// update selection and cursor to match each other\r\nstatic void stb_textedit_prep_selection_at_cursor(STB_TexteditState *state)\r\n{\r\n   if (!STB_TEXT_HAS_SELECTION(state))\r\n      state->select_start = state->select_end = state->cursor;\r\n   else\r\n      state->cursor = state->select_end;\r\n}\r\n\r\n// API cut: delete selection\r\nstatic int stb_textedit_cut(STB_TEXTEDIT_STRING *str, STB_TexteditState *state)\r\n{\r\n   if (STB_TEXT_HAS_SELECTION(state)) {\r\n      stb_textedit_delete_selection(str,state); // implicitly clamps\r\n      state->has_preferred_x = 0;\r\n      return 1;\r\n   }\r\n   return 0;\r\n}\r\n\r\n// API paste: replace existing selection with passed-in text\r\nstatic int stb_textedit_paste_internal(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE *text, int len)\r\n{\r\n   // if there's a selection, the paste should delete it\r\n   stb_textedit_clamp(str, state);\r\n   stb_textedit_delete_selection(str,state);\r\n   // try to insert the characters\r\n   if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, text, len)) {\r\n      stb_text_makeundo_insert(state, state->cursor, len);\r\n      state->cursor += len;\r\n      state->has_preferred_x = 0;\r\n      return 1;\r\n   }\r\n   // [DEAR IMGUI]\r\n   //// remove the undo since we didn't actually insert the characters\r\n   //if (state->undostate.undo_point)\r\n   //   --state->undostate.undo_point;\r\n   // note: paste failure will leave deleted selection, may be restored with an undo (see https://github.com/nothings/stb/issues/734 for details)\r\n   return 0;\r\n}\r\n\r\n#ifndef STB_TEXTEDIT_KEYTYPE\r\n#define STB_TEXTEDIT_KEYTYPE int\r\n#endif\r\n\r\n// API key: process a keyboard input\r\nstatic void stb_textedit_key(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_KEYTYPE key)\r\n{\r\nretry:\r\n   switch (key) {\r\n      default: {\r\n         int c = STB_TEXTEDIT_KEYTOTEXT(key);\r\n         if (c > 0) {\r\n            STB_TEXTEDIT_CHARTYPE ch = (STB_TEXTEDIT_CHARTYPE) c;\r\n\r\n            // can't add newline in single-line mode\r\n            if (c == '\\n' && state->single_line)\r\n               break;\r\n\r\n            if (state->insert_mode && !STB_TEXT_HAS_SELECTION(state) && state->cursor < STB_TEXTEDIT_STRINGLEN(str)) {\r\n               stb_text_makeundo_replace(str, state, state->cursor, 1, 1);\r\n               STB_TEXTEDIT_DELETECHARS(str, state->cursor, 1);\r\n               if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, &ch, 1)) {\r\n                  ++state->cursor;\r\n                  state->has_preferred_x = 0;\r\n               }\r\n            } else {\r\n               stb_textedit_delete_selection(str,state); // implicitly clamps\r\n               if (STB_TEXTEDIT_INSERTCHARS(str, state->cursor, &ch, 1)) {\r\n                  stb_text_makeundo_insert(state, state->cursor, 1);\r\n                  ++state->cursor;\r\n                  state->has_preferred_x = 0;\r\n               }\r\n            }\r\n         }\r\n         break;\r\n      }\r\n\r\n#ifdef STB_TEXTEDIT_K_INSERT\r\n      case STB_TEXTEDIT_K_INSERT:\r\n         state->insert_mode = !state->insert_mode;\r\n         break;\r\n#endif\r\n\r\n      case STB_TEXTEDIT_K_UNDO:\r\n         stb_text_undo(str, state);\r\n         state->has_preferred_x = 0;\r\n         break;\r\n\r\n      case STB_TEXTEDIT_K_REDO:\r\n         stb_text_redo(str, state);\r\n         state->has_preferred_x = 0;\r\n         break;\r\n\r\n      case STB_TEXTEDIT_K_LEFT:\r\n         // if currently there's a selection, move cursor to start of selection\r\n         if (STB_TEXT_HAS_SELECTION(state))\r\n            stb_textedit_move_to_first(state);\r\n         else\r\n            if (state->cursor > 0)\r\n               --state->cursor;\r\n         state->has_preferred_x = 0;\r\n         break;\r\n\r\n      case STB_TEXTEDIT_K_RIGHT:\r\n         // if currently there's a selection, move cursor to end of selection\r\n         if (STB_TEXT_HAS_SELECTION(state))\r\n            stb_textedit_move_to_last(str, state);\r\n         else\r\n            ++state->cursor;\r\n         stb_textedit_clamp(str, state);\r\n         state->has_preferred_x = 0;\r\n         break;\r\n\r\n      case STB_TEXTEDIT_K_LEFT | STB_TEXTEDIT_K_SHIFT:\r\n         stb_textedit_clamp(str, state);\r\n         stb_textedit_prep_selection_at_cursor(state);\r\n         // move selection left\r\n         if (state->select_end > 0)\r\n            --state->select_end;\r\n         state->cursor = state->select_end;\r\n         state->has_preferred_x = 0;\r\n         break;\r\n\r\n#ifdef STB_TEXTEDIT_MOVEWORDLEFT\r\n      case STB_TEXTEDIT_K_WORDLEFT:\r\n         if (STB_TEXT_HAS_SELECTION(state))\r\n            stb_textedit_move_to_first(state);\r\n         else {\r\n            state->cursor = STB_TEXTEDIT_MOVEWORDLEFT(str, state->cursor);\r\n            stb_textedit_clamp( str, state );\r\n         }\r\n         break;\r\n\r\n      case STB_TEXTEDIT_K_WORDLEFT | STB_TEXTEDIT_K_SHIFT:\r\n         if( !STB_TEXT_HAS_SELECTION( state ) )\r\n            stb_textedit_prep_selection_at_cursor(state);\r\n\r\n         state->cursor = STB_TEXTEDIT_MOVEWORDLEFT(str, state->cursor);\r\n         state->select_end = state->cursor;\r\n\r\n         stb_textedit_clamp( str, state );\r\n         break;\r\n#endif\r\n\r\n#ifdef STB_TEXTEDIT_MOVEWORDRIGHT\r\n      case STB_TEXTEDIT_K_WORDRIGHT:\r\n         if (STB_TEXT_HAS_SELECTION(state))\r\n            stb_textedit_move_to_last(str, state);\r\n         else {\r\n            state->cursor = STB_TEXTEDIT_MOVEWORDRIGHT(str, state->cursor);\r\n            stb_textedit_clamp( str, state );\r\n         }\r\n         break;\r\n\r\n      case STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT:\r\n         if( !STB_TEXT_HAS_SELECTION( state ) )\r\n            stb_textedit_prep_selection_at_cursor(state);\r\n\r\n         state->cursor = STB_TEXTEDIT_MOVEWORDRIGHT(str, state->cursor);\r\n         state->select_end = state->cursor;\r\n\r\n         stb_textedit_clamp( str, state );\r\n         break;\r\n#endif\r\n\r\n      case STB_TEXTEDIT_K_RIGHT | STB_TEXTEDIT_K_SHIFT:\r\n         stb_textedit_prep_selection_at_cursor(state);\r\n         // move selection right\r\n         ++state->select_end;\r\n         stb_textedit_clamp(str, state);\r\n         state->cursor = state->select_end;\r\n         state->has_preferred_x = 0;\r\n         break;\r\n\r\n      case STB_TEXTEDIT_K_DOWN:\r\n      case STB_TEXTEDIT_K_DOWN | STB_TEXTEDIT_K_SHIFT:\r\n      case STB_TEXTEDIT_K_PGDOWN:\r\n      case STB_TEXTEDIT_K_PGDOWN | STB_TEXTEDIT_K_SHIFT: {\r\n         StbFindState find;\r\n         StbTexteditRow row;\r\n         int i, j, sel = (key & STB_TEXTEDIT_K_SHIFT) != 0;\r\n         int is_page = (key & ~STB_TEXTEDIT_K_SHIFT) == STB_TEXTEDIT_K_PGDOWN;\r\n         int row_count = is_page ? state->row_count_per_page : 1;\r\n\r\n         if (!is_page && state->single_line) {\r\n            // on windows, up&down in single-line behave like left&right\r\n            key = STB_TEXTEDIT_K_RIGHT | (key & STB_TEXTEDIT_K_SHIFT);\r\n            goto retry;\r\n         }\r\n\r\n         if (sel)\r\n            stb_textedit_prep_selection_at_cursor(state);\r\n         else if (STB_TEXT_HAS_SELECTION(state))\r\n            stb_textedit_move_to_last(str, state);\r\n\r\n         // compute current position of cursor point\r\n         stb_textedit_clamp(str, state);\r\n         stb_textedit_find_charpos(&find, str, state->cursor, state->single_line);\r\n\r\n         for (j = 0; j < row_count; ++j) {\r\n            float x, goal_x = state->has_preferred_x ? state->preferred_x : find.x;\r\n            int start = find.first_char + find.length;\r\n\r\n            if (find.length == 0)\r\n               break;\r\n\r\n            // [DEAR IMGUI]\r\n            // going down while being on the last line shouldn't bring us to that line end\r\n            if (STB_TEXTEDIT_GETCHAR(str, find.first_char + find.length - 1) != STB_TEXTEDIT_NEWLINE)\r\n               break;\r\n\r\n            // now find character position down a row\r\n            state->cursor = start;\r\n            STB_TEXTEDIT_LAYOUTROW(&row, str, state->cursor);\r\n            x = row.x0;\r\n            for (i=0; i < row.num_chars; ++i) {\r\n               float dx = STB_TEXTEDIT_GETWIDTH(str, start, i);\r\n               #ifdef STB_TEXTEDIT_GETWIDTH_NEWLINE\r\n               if (dx == STB_TEXTEDIT_GETWIDTH_NEWLINE)\r\n                  break;\r\n               #endif\r\n               x += dx;\r\n               if (x > goal_x)\r\n                  break;\r\n               ++state->cursor;\r\n            }\r\n            stb_textedit_clamp(str, state);\r\n\r\n            state->has_preferred_x = 1;\r\n            state->preferred_x = goal_x;\r\n\r\n            if (sel)\r\n               state->select_end = state->cursor;\r\n\r\n            // go to next line\r\n            find.first_char = find.first_char + find.length;\r\n            find.length = row.num_chars;\r\n         }\r\n         break;\r\n      }\r\n\r\n      case STB_TEXTEDIT_K_UP:\r\n      case STB_TEXTEDIT_K_UP | STB_TEXTEDIT_K_SHIFT:\r\n      case STB_TEXTEDIT_K_PGUP:\r\n      case STB_TEXTEDIT_K_PGUP | STB_TEXTEDIT_K_SHIFT: {\r\n         StbFindState find;\r\n         StbTexteditRow row;\r\n         int i, j, prev_scan, sel = (key & STB_TEXTEDIT_K_SHIFT) != 0;\r\n         int is_page = (key & ~STB_TEXTEDIT_K_SHIFT) == STB_TEXTEDIT_K_PGUP;\r\n         int row_count = is_page ? state->row_count_per_page : 1;\r\n\r\n         if (!is_page && state->single_line) {\r\n            // on windows, up&down become left&right\r\n            key = STB_TEXTEDIT_K_LEFT | (key & STB_TEXTEDIT_K_SHIFT);\r\n            goto retry;\r\n         }\r\n\r\n         if (sel)\r\n            stb_textedit_prep_selection_at_cursor(state);\r\n         else if (STB_TEXT_HAS_SELECTION(state))\r\n            stb_textedit_move_to_first(state);\r\n\r\n         // compute current position of cursor point\r\n         stb_textedit_clamp(str, state);\r\n         stb_textedit_find_charpos(&find, str, state->cursor, state->single_line);\r\n\r\n         for (j = 0; j < row_count; ++j) {\r\n            float  x, goal_x = state->has_preferred_x ? state->preferred_x : find.x;\r\n\r\n            // can only go up if there's a previous row\r\n            if (find.prev_first == find.first_char)\r\n               break;\r\n\r\n            // now find character position up a row\r\n            state->cursor = find.prev_first;\r\n            STB_TEXTEDIT_LAYOUTROW(&row, str, state->cursor);\r\n            x = row.x0;\r\n            for (i=0; i < row.num_chars; ++i) {\r\n               float dx = STB_TEXTEDIT_GETWIDTH(str, find.prev_first, i);\r\n               #ifdef STB_TEXTEDIT_GETWIDTH_NEWLINE\r\n               if (dx == STB_TEXTEDIT_GETWIDTH_NEWLINE)\r\n                  break;\r\n               #endif\r\n               x += dx;\r\n               if (x > goal_x)\r\n                  break;\r\n               ++state->cursor;\r\n            }\r\n            stb_textedit_clamp(str, state);\r\n\r\n            state->has_preferred_x = 1;\r\n            state->preferred_x = goal_x;\r\n\r\n            if (sel)\r\n               state->select_end = state->cursor;\r\n\r\n            // go to previous line\r\n            // (we need to scan previous line the hard way. maybe we could expose this as a new API function?)\r\n            prev_scan = find.prev_first > 0 ? find.prev_first - 1 : 0;\r\n            while (prev_scan > 0 && STB_TEXTEDIT_GETCHAR(str, prev_scan - 1) != STB_TEXTEDIT_NEWLINE)\r\n               --prev_scan;\r\n            find.first_char = find.prev_first;\r\n            find.prev_first = prev_scan;\r\n         }\r\n         break;\r\n      }\r\n\r\n      case STB_TEXTEDIT_K_DELETE:\r\n      case STB_TEXTEDIT_K_DELETE | STB_TEXTEDIT_K_SHIFT:\r\n         if (STB_TEXT_HAS_SELECTION(state))\r\n            stb_textedit_delete_selection(str, state);\r\n         else {\r\n            int n = STB_TEXTEDIT_STRINGLEN(str);\r\n            if (state->cursor < n)\r\n               stb_textedit_delete(str, state, state->cursor, 1);\r\n         }\r\n         state->has_preferred_x = 0;\r\n         break;\r\n\r\n      case STB_TEXTEDIT_K_BACKSPACE:\r\n      case STB_TEXTEDIT_K_BACKSPACE | STB_TEXTEDIT_K_SHIFT:\r\n         if (STB_TEXT_HAS_SELECTION(state))\r\n            stb_textedit_delete_selection(str, state);\r\n         else {\r\n            stb_textedit_clamp(str, state);\r\n            if (state->cursor > 0) {\r\n               stb_textedit_delete(str, state, state->cursor-1, 1);\r\n               --state->cursor;\r\n            }\r\n         }\r\n         state->has_preferred_x = 0;\r\n         break;\r\n\r\n#ifdef STB_TEXTEDIT_K_TEXTSTART2\r\n      case STB_TEXTEDIT_K_TEXTSTART2:\r\n#endif\r\n      case STB_TEXTEDIT_K_TEXTSTART:\r\n         state->cursor = state->select_start = state->select_end = 0;\r\n         state->has_preferred_x = 0;\r\n         break;\r\n\r\n#ifdef STB_TEXTEDIT_K_TEXTEND2\r\n      case STB_TEXTEDIT_K_TEXTEND2:\r\n#endif\r\n      case STB_TEXTEDIT_K_TEXTEND:\r\n         state->cursor = STB_TEXTEDIT_STRINGLEN(str);\r\n         state->select_start = state->select_end = 0;\r\n         state->has_preferred_x = 0;\r\n         break;\r\n\r\n#ifdef STB_TEXTEDIT_K_TEXTSTART2\r\n      case STB_TEXTEDIT_K_TEXTSTART2 | STB_TEXTEDIT_K_SHIFT:\r\n#endif\r\n      case STB_TEXTEDIT_K_TEXTSTART | STB_TEXTEDIT_K_SHIFT:\r\n         stb_textedit_prep_selection_at_cursor(state);\r\n         state->cursor = state->select_end = 0;\r\n         state->has_preferred_x = 0;\r\n         break;\r\n\r\n#ifdef STB_TEXTEDIT_K_TEXTEND2\r\n      case STB_TEXTEDIT_K_TEXTEND2 | STB_TEXTEDIT_K_SHIFT:\r\n#endif\r\n      case STB_TEXTEDIT_K_TEXTEND | STB_TEXTEDIT_K_SHIFT:\r\n         stb_textedit_prep_selection_at_cursor(state);\r\n         state->cursor = state->select_end = STB_TEXTEDIT_STRINGLEN(str);\r\n         state->has_preferred_x = 0;\r\n         break;\r\n\r\n\r\n#ifdef STB_TEXTEDIT_K_LINESTART2\r\n      case STB_TEXTEDIT_K_LINESTART2:\r\n#endif\r\n      case STB_TEXTEDIT_K_LINESTART:\r\n         stb_textedit_clamp(str, state);\r\n         stb_textedit_move_to_first(state);\r\n         if (state->single_line)\r\n            state->cursor = 0;\r\n         else while (state->cursor > 0 && STB_TEXTEDIT_GETCHAR(str, state->cursor-1) != STB_TEXTEDIT_NEWLINE)\r\n            --state->cursor;\r\n         state->has_preferred_x = 0;\r\n         break;\r\n\r\n#ifdef STB_TEXTEDIT_K_LINEEND2\r\n      case STB_TEXTEDIT_K_LINEEND2:\r\n#endif\r\n      case STB_TEXTEDIT_K_LINEEND: {\r\n         int n = STB_TEXTEDIT_STRINGLEN(str);\r\n         stb_textedit_clamp(str, state);\r\n         stb_textedit_move_to_first(state);\r\n         if (state->single_line)\r\n             state->cursor = n;\r\n         else while (state->cursor < n && STB_TEXTEDIT_GETCHAR(str, state->cursor) != STB_TEXTEDIT_NEWLINE)\r\n             ++state->cursor;\r\n         state->has_preferred_x = 0;\r\n         break;\r\n      }\r\n\r\n#ifdef STB_TEXTEDIT_K_LINESTART2\r\n      case STB_TEXTEDIT_K_LINESTART2 | STB_TEXTEDIT_K_SHIFT:\r\n#endif\r\n      case STB_TEXTEDIT_K_LINESTART | STB_TEXTEDIT_K_SHIFT:\r\n         stb_textedit_clamp(str, state);\r\n         stb_textedit_prep_selection_at_cursor(state);\r\n         if (state->single_line)\r\n            state->cursor = 0;\r\n         else while (state->cursor > 0 && STB_TEXTEDIT_GETCHAR(str, state->cursor-1) != STB_TEXTEDIT_NEWLINE)\r\n            --state->cursor;\r\n         state->select_end = state->cursor;\r\n         state->has_preferred_x = 0;\r\n         break;\r\n\r\n#ifdef STB_TEXTEDIT_K_LINEEND2\r\n      case STB_TEXTEDIT_K_LINEEND2 | STB_TEXTEDIT_K_SHIFT:\r\n#endif\r\n      case STB_TEXTEDIT_K_LINEEND | STB_TEXTEDIT_K_SHIFT: {\r\n         int n = STB_TEXTEDIT_STRINGLEN(str);\r\n         stb_textedit_clamp(str, state);\r\n         stb_textedit_prep_selection_at_cursor(state);\r\n         if (state->single_line)\r\n             state->cursor = n;\r\n         else while (state->cursor < n && STB_TEXTEDIT_GETCHAR(str, state->cursor) != STB_TEXTEDIT_NEWLINE)\r\n            ++state->cursor;\r\n         state->select_end = state->cursor;\r\n         state->has_preferred_x = 0;\r\n         break;\r\n      }\r\n   }\r\n}\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n//\r\n//      Undo processing\r\n//\r\n// @OPTIMIZE: the undo/redo buffer should be circular\r\n\r\nstatic void stb_textedit_flush_redo(StbUndoState *state)\r\n{\r\n   state->redo_point = STB_TEXTEDIT_UNDOSTATECOUNT;\r\n   state->redo_char_point = STB_TEXTEDIT_UNDOCHARCOUNT;\r\n}\r\n\r\n// discard the oldest entry in the undo list\r\nstatic void stb_textedit_discard_undo(StbUndoState *state)\r\n{\r\n   if (state->undo_point > 0) {\r\n      // if the 0th undo state has characters, clean those up\r\n      if (state->undo_rec[0].char_storage >= 0) {\r\n         int n = state->undo_rec[0].insert_length, i;\r\n         // delete n characters from all other records\r\n         state->undo_char_point -= n;\r\n         STB_TEXTEDIT_memmove(state->undo_char, state->undo_char + n, (size_t) (state->undo_char_point*sizeof(STB_TEXTEDIT_CHARTYPE)));\r\n         for (i=0; i < state->undo_point; ++i)\r\n            if (state->undo_rec[i].char_storage >= 0)\r\n               state->undo_rec[i].char_storage -= n; // @OPTIMIZE: get rid of char_storage and infer it\r\n      }\r\n      --state->undo_point;\r\n      STB_TEXTEDIT_memmove(state->undo_rec, state->undo_rec+1, (size_t) (state->undo_point*sizeof(state->undo_rec[0])));\r\n   }\r\n}\r\n\r\n// discard the oldest entry in the redo list--it's bad if this\r\n// ever happens, but because undo & redo have to store the actual\r\n// characters in different cases, the redo character buffer can\r\n// fill up even though the undo buffer didn't\r\nstatic void stb_textedit_discard_redo(StbUndoState *state)\r\n{\r\n   int k = STB_TEXTEDIT_UNDOSTATECOUNT-1;\r\n\r\n   if (state->redo_point <= k) {\r\n      // if the k'th undo state has characters, clean those up\r\n      if (state->undo_rec[k].char_storage >= 0) {\r\n         int n = state->undo_rec[k].insert_length, i;\r\n         // move the remaining redo character data to the end of the buffer\r\n         state->redo_char_point += n;\r\n         STB_TEXTEDIT_memmove(state->undo_char + state->redo_char_point, state->undo_char + state->redo_char_point-n, (size_t) ((STB_TEXTEDIT_UNDOCHARCOUNT - state->redo_char_point)*sizeof(STB_TEXTEDIT_CHARTYPE)));\r\n         // adjust the position of all the other records to account for above memmove\r\n         for (i=state->redo_point; i < k; ++i)\r\n            if (state->undo_rec[i].char_storage >= 0)\r\n               state->undo_rec[i].char_storage += n;\r\n      }\r\n      // now move all the redo records towards the end of the buffer; the first one is at 'redo_point'\r\n      // [DEAR IMGUI]\r\n      size_t move_size = (size_t)((STB_TEXTEDIT_UNDOSTATECOUNT - state->redo_point - 1) * sizeof(state->undo_rec[0]));\r\n      const char* buf_begin = (char*)state->undo_rec; (void)buf_begin;\r\n      const char* buf_end   = (char*)state->undo_rec + sizeof(state->undo_rec); (void)buf_end;\r\n      IM_ASSERT(((char*)(state->undo_rec + state->redo_point)) >= buf_begin);\r\n      IM_ASSERT(((char*)(state->undo_rec + state->redo_point + 1) + move_size) <= buf_end);\r\n      STB_TEXTEDIT_memmove(state->undo_rec + state->redo_point+1, state->undo_rec + state->redo_point, move_size);\r\n\r\n      // now move redo_point to point to the new one\r\n      ++state->redo_point;\r\n   }\r\n}\r\n\r\nstatic StbUndoRecord *stb_text_create_undo_record(StbUndoState *state, int numchars)\r\n{\r\n   // any time we create a new undo record, we discard redo\r\n   stb_textedit_flush_redo(state);\r\n\r\n   // if we have no free records, we have to make room, by sliding the\r\n   // existing records down\r\n   if (state->undo_point == STB_TEXTEDIT_UNDOSTATECOUNT)\r\n      stb_textedit_discard_undo(state);\r\n\r\n   // if the characters to store won't possibly fit in the buffer, we can't undo\r\n   if (numchars > STB_TEXTEDIT_UNDOCHARCOUNT) {\r\n      state->undo_point = 0;\r\n      state->undo_char_point = 0;\r\n      return NULL;\r\n   }\r\n\r\n   // if we don't have enough free characters in the buffer, we have to make room\r\n   while (state->undo_char_point + numchars > STB_TEXTEDIT_UNDOCHARCOUNT)\r\n      stb_textedit_discard_undo(state);\r\n\r\n   return &state->undo_rec[state->undo_point++];\r\n}\r\n\r\nstatic STB_TEXTEDIT_CHARTYPE *stb_text_createundo(StbUndoState *state, int pos, int insert_len, int delete_len)\r\n{\r\n   StbUndoRecord *r = stb_text_create_undo_record(state, insert_len);\r\n   if (r == NULL)\r\n      return NULL;\r\n\r\n   r->where = pos;\r\n   r->insert_length = (STB_TEXTEDIT_POSITIONTYPE) insert_len;\r\n   r->delete_length = (STB_TEXTEDIT_POSITIONTYPE) delete_len;\r\n\r\n   if (insert_len == 0) {\r\n      r->char_storage = -1;\r\n      return NULL;\r\n   } else {\r\n      r->char_storage = state->undo_char_point;\r\n      state->undo_char_point += insert_len;\r\n      return &state->undo_char[r->char_storage];\r\n   }\r\n}\r\n\r\nstatic void stb_text_undo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state)\r\n{\r\n   StbUndoState *s = &state->undostate;\r\n   StbUndoRecord u, *r;\r\n   if (s->undo_point == 0)\r\n      return;\r\n\r\n   // we need to do two things: apply the undo record, and create a redo record\r\n   u = s->undo_rec[s->undo_point-1];\r\n   r = &s->undo_rec[s->redo_point-1];\r\n   r->char_storage = -1;\r\n\r\n   r->insert_length = u.delete_length;\r\n   r->delete_length = u.insert_length;\r\n   r->where = u.where;\r\n\r\n   if (u.delete_length) {\r\n      // if the undo record says to delete characters, then the redo record will\r\n      // need to re-insert the characters that get deleted, so we need to store\r\n      // them.\r\n\r\n      // there are three cases:\r\n      //    there's enough room to store the characters\r\n      //    characters stored for *redoing* don't leave room for redo\r\n      //    characters stored for *undoing* don't leave room for redo\r\n      // if the last is true, we have to bail\r\n\r\n      if (s->undo_char_point + u.delete_length >= STB_TEXTEDIT_UNDOCHARCOUNT) {\r\n         // the undo records take up too much character space; there's no space to store the redo characters\r\n         r->insert_length = 0;\r\n      } else {\r\n         int i;\r\n\r\n         // there's definitely room to store the characters eventually\r\n         while (s->undo_char_point + u.delete_length > s->redo_char_point) {\r\n            // should never happen:\r\n            if (s->redo_point == STB_TEXTEDIT_UNDOSTATECOUNT)\r\n               return;\r\n            // there's currently not enough room, so discard a redo record\r\n            stb_textedit_discard_redo(s);\r\n         }\r\n         r = &s->undo_rec[s->redo_point-1];\r\n\r\n         r->char_storage = s->redo_char_point - u.delete_length;\r\n         s->redo_char_point = s->redo_char_point - u.delete_length;\r\n\r\n         // now save the characters\r\n         for (i=0; i < u.delete_length; ++i)\r\n            s->undo_char[r->char_storage + i] = STB_TEXTEDIT_GETCHAR(str, u.where + i);\r\n      }\r\n\r\n      // now we can carry out the deletion\r\n      STB_TEXTEDIT_DELETECHARS(str, u.where, u.delete_length);\r\n   }\r\n\r\n   // check type of recorded action:\r\n   if (u.insert_length) {\r\n      // easy case: was a deletion, so we need to insert n characters\r\n      STB_TEXTEDIT_INSERTCHARS(str, u.where, &s->undo_char[u.char_storage], u.insert_length);\r\n      s->undo_char_point -= u.insert_length;\r\n   }\r\n\r\n   state->cursor = u.where + u.insert_length;\r\n\r\n   s->undo_point--;\r\n   s->redo_point--;\r\n}\r\n\r\nstatic void stb_text_redo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state)\r\n{\r\n   StbUndoState *s = &state->undostate;\r\n   StbUndoRecord *u, r;\r\n   if (s->redo_point == STB_TEXTEDIT_UNDOSTATECOUNT)\r\n      return;\r\n\r\n   // we need to do two things: apply the redo record, and create an undo record\r\n   u = &s->undo_rec[s->undo_point];\r\n   r = s->undo_rec[s->redo_point];\r\n\r\n   // we KNOW there must be room for the undo record, because the redo record\r\n   // was derived from an undo record\r\n\r\n   u->delete_length = r.insert_length;\r\n   u->insert_length = r.delete_length;\r\n   u->where = r.where;\r\n   u->char_storage = -1;\r\n\r\n   if (r.delete_length) {\r\n      // the redo record requires us to delete characters, so the undo record\r\n      // needs to store the characters\r\n\r\n      if (s->undo_char_point + u->insert_length > s->redo_char_point) {\r\n         u->insert_length = 0;\r\n         u->delete_length = 0;\r\n      } else {\r\n         int i;\r\n         u->char_storage = s->undo_char_point;\r\n         s->undo_char_point = s->undo_char_point + u->insert_length;\r\n\r\n         // now save the characters\r\n         for (i=0; i < u->insert_length; ++i)\r\n            s->undo_char[u->char_storage + i] = STB_TEXTEDIT_GETCHAR(str, u->where + i);\r\n      }\r\n\r\n      STB_TEXTEDIT_DELETECHARS(str, r.where, r.delete_length);\r\n   }\r\n\r\n   if (r.insert_length) {\r\n      // easy case: need to insert n characters\r\n      STB_TEXTEDIT_INSERTCHARS(str, r.where, &s->undo_char[r.char_storage], r.insert_length);\r\n      s->redo_char_point += r.insert_length;\r\n   }\r\n\r\n   state->cursor = r.where + r.insert_length;\r\n\r\n   s->undo_point++;\r\n   s->redo_point++;\r\n}\r\n\r\nstatic void stb_text_makeundo_insert(STB_TexteditState *state, int where, int length)\r\n{\r\n   stb_text_createundo(&state->undostate, where, 0, length);\r\n}\r\n\r\nstatic void stb_text_makeundo_delete(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int length)\r\n{\r\n   int i;\r\n   STB_TEXTEDIT_CHARTYPE *p = stb_text_createundo(&state->undostate, where, length, 0);\r\n   if (p) {\r\n      for (i=0; i < length; ++i)\r\n         p[i] = STB_TEXTEDIT_GETCHAR(str, where+i);\r\n   }\r\n}\r\n\r\nstatic void stb_text_makeundo_replace(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, int where, int old_length, int new_length)\r\n{\r\n   int i;\r\n   STB_TEXTEDIT_CHARTYPE *p = stb_text_createundo(&state->undostate, where, old_length, new_length);\r\n   if (p) {\r\n      for (i=0; i < old_length; ++i)\r\n         p[i] = STB_TEXTEDIT_GETCHAR(str, where+i);\r\n   }\r\n}\r\n\r\n// reset the state to default\r\nstatic void stb_textedit_clear_state(STB_TexteditState *state, int is_single_line)\r\n{\r\n   state->undostate.undo_point = 0;\r\n   state->undostate.undo_char_point = 0;\r\n   state->undostate.redo_point = STB_TEXTEDIT_UNDOSTATECOUNT;\r\n   state->undostate.redo_char_point = STB_TEXTEDIT_UNDOCHARCOUNT;\r\n   state->select_end = state->select_start = 0;\r\n   state->cursor = 0;\r\n   state->has_preferred_x = 0;\r\n   state->preferred_x = 0;\r\n   state->cursor_at_end_of_line = 0;\r\n   state->initialized = 1;\r\n   state->single_line = (unsigned char) is_single_line;\r\n   state->insert_mode = 0;\r\n   state->row_count_per_page = 0;\r\n}\r\n\r\n// API initialize\r\nstatic void stb_textedit_initialize_state(STB_TexteditState *state, int is_single_line)\r\n{\r\n   stb_textedit_clear_state(state, is_single_line);\r\n}\r\n\r\n#if defined(__GNUC__) || defined(__clang__)\r\n#pragma GCC diagnostic push\r\n#pragma GCC diagnostic ignored \"-Wcast-qual\"\r\n#endif\r\n\r\nstatic int stb_textedit_paste(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, STB_TEXTEDIT_CHARTYPE const *ctext, int len)\r\n{\r\n   return stb_textedit_paste_internal(str, state, (STB_TEXTEDIT_CHARTYPE *) ctext, len);\r\n}\r\n\r\n#if defined(__GNUC__) || defined(__clang__)\r\n#pragma GCC diagnostic pop\r\n#endif\r\n\r\n#endif//STB_TEXTEDIT_IMPLEMENTATION\r\n\r\n/*\r\n------------------------------------------------------------------------------\r\nThis software is available under 2 licenses -- choose whichever you prefer.\r\n------------------------------------------------------------------------------\r\nALTERNATIVE A - MIT License\r\nCopyright (c) 2017 Sean Barrett\r\nPermission is hereby granted, free of charge, to any person obtaining a copy of\r\nthis software and associated documentation files (the \"Software\"), to deal in\r\nthe Software without restriction, including without limitation the rights to\r\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\r\nof the Software, and to permit persons to whom the Software is furnished to do\r\nso, subject to the following conditions:\r\nThe above copyright notice and this permission notice shall be included in all\r\ncopies or substantial portions of the Software.\r\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\nSOFTWARE.\r\n------------------------------------------------------------------------------\r\nALTERNATIVE B - Public Domain (www.unlicense.org)\r\nThis is free and unencumbered software released into the public domain.\r\nAnyone is free to copy, modify, publish, use, compile, sell, or distribute this\r\nsoftware, either in source code form or as a compiled binary, for any purpose,\r\ncommercial or non-commercial, and by any means.\r\nIn jurisdictions that recognize copyright laws, the author or authors of this\r\nsoftware dedicate any and all copyright interest in the software to the public\r\ndomain. We make this dedication for the benefit of the public at large and to\r\nthe detriment of our heirs and successors. We intend this dedication to be an\r\novert act of relinquishment in perpetuity of all present and future rights to\r\nthis software under copyright law.\r\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\nAUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\r\nACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\r\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n------------------------------------------------------------------------------\r\n*/\r\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/imgui/imstb_truetype.h",
    "content": "// [DEAR IMGUI]\r\n// This is a slightly modified version of stb_truetype.h 1.20.\r\n// Mostly fixing for compiler and static analyzer warnings.\r\n// Grep for [DEAR IMGUI] to find the changes.\r\n\r\n// stb_truetype.h - v1.20 - public domain\r\n// authored from 2009-2016 by Sean Barrett / RAD Game Tools\r\n//\r\n//   This library processes TrueType files:\r\n//        parse files\r\n//        extract glyph metrics\r\n//        extract glyph shapes\r\n//        render glyphs to one-channel bitmaps with antialiasing (box filter)\r\n//        render glyphs to one-channel SDF bitmaps (signed-distance field/function)\r\n//\r\n//   Todo:\r\n//        non-MS cmaps\r\n//        crashproof on bad data\r\n//        hinting? (no longer patented)\r\n//        cleartype-style AA?\r\n//        optimize: use simple memory allocator for intermediates\r\n//        optimize: build edge-list directly from curves\r\n//        optimize: rasterize directly from curves?\r\n//\r\n// ADDITIONAL CONTRIBUTORS\r\n//\r\n//   Mikko Mononen: compound shape support, more cmap formats\r\n//   Tor Andersson: kerning, subpixel rendering\r\n//   Dougall Johnson: OpenType / Type 2 font handling\r\n//   Daniel Ribeiro Maciel: basic GPOS-based kerning\r\n//\r\n//   Misc other:\r\n//       Ryan Gordon\r\n//       Simon Glass\r\n//       github:IntellectualKitty\r\n//       Imanol Celaya\r\n//       Daniel Ribeiro Maciel\r\n//\r\n//   Bug/warning reports/fixes:\r\n//       \"Zer\" on mollyrocket       Fabian \"ryg\" Giesen\r\n//       Cass Everitt               Martins Mozeiko\r\n//       stoiko (Haemimont Games)   Cap Petschulat\r\n//       Brian Hook                 Omar Cornut\r\n//       Walter van Niftrik         github:aloucks\r\n//       David Gow                  Peter LaValle\r\n//       David Given                Sergey Popov\r\n//       Ivan-Assen Ivanov          Giumo X. Clanjor\r\n//       Anthony Pesch              Higor Euripedes\r\n//       Johan Duparc               Thomas Fields\r\n//       Hou Qiming                 Derek Vinyard\r\n//       Rob Loach                  Cort Stratton\r\n//       Kenney Phillis Jr.         github:oyvindjam\r\n//       Brian Costabile            github:vassvik\r\n//\r\n// VERSION HISTORY\r\n//\r\n//   1.20 (2019-02-07) PackFontRange skips missing codepoints; GetScaleFontVMetrics()\r\n//   1.19 (2018-02-11) GPOS kerning, STBTT_fmod\r\n//   1.18 (2018-01-29) add missing function\r\n//   1.17 (2017-07-23) make more arguments const; doc fix\r\n//   1.16 (2017-07-12) SDF support\r\n//   1.15 (2017-03-03) make more arguments const\r\n//   1.14 (2017-01-16) num-fonts-in-TTC function\r\n//   1.13 (2017-01-02) support OpenType fonts, certain Apple fonts\r\n//   1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual\r\n//   1.11 (2016-04-02) fix unused-variable warning\r\n//   1.10 (2016-04-02) user-defined fabs(); rare memory leak; remove duplicate typedef\r\n//   1.09 (2016-01-16) warning fix; avoid crash on outofmem; use allocation userdata properly\r\n//   1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges\r\n//   1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints;\r\n//                     variant PackFontRanges to pack and render in separate phases;\r\n//                     fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?);\r\n//                     fixed an assert() bug in the new rasterizer\r\n//                     replace assert() with STBTT_assert() in new rasterizer\r\n//\r\n//   Full history can be found at the end of this file.\r\n//\r\n// LICENSE\r\n//\r\n//   See end of file for license information.\r\n//\r\n// USAGE\r\n//\r\n//   Include this file in whatever places need to refer to it. In ONE C/C++\r\n//   file, write:\r\n//      #define STB_TRUETYPE_IMPLEMENTATION\r\n//   before the #include of this file. This expands out the actual\r\n//   implementation into that C/C++ file.\r\n//\r\n//   To make the implementation private to the file that generates the implementation,\r\n//      #define STBTT_STATIC\r\n//\r\n//   Simple 3D API (don't ship this, but it's fine for tools and quick start)\r\n//           stbtt_BakeFontBitmap()               -- bake a font to a bitmap for use as texture\r\n//           stbtt_GetBakedQuad()                 -- compute quad to draw for a given char\r\n//\r\n//   Improved 3D API (more shippable):\r\n//           #include \"stb_rect_pack.h\"           -- optional, but you really want it\r\n//           stbtt_PackBegin()\r\n//           stbtt_PackSetOversampling()          -- for improved quality on small fonts\r\n//           stbtt_PackFontRanges()               -- pack and renders\r\n//           stbtt_PackEnd()\r\n//           stbtt_GetPackedQuad()\r\n//\r\n//   \"Load\" a font file from a memory buffer (you have to keep the buffer loaded)\r\n//           stbtt_InitFont()\r\n//           stbtt_GetFontOffsetForIndex()        -- indexing for TTC font collections\r\n//           stbtt_GetNumberOfFonts()             -- number of fonts for TTC font collections\r\n//\r\n//   Render a unicode codepoint to a bitmap\r\n//           stbtt_GetCodepointBitmap()           -- allocates and returns a bitmap\r\n//           stbtt_MakeCodepointBitmap()          -- renders into bitmap you provide\r\n//           stbtt_GetCodepointBitmapBox()        -- how big the bitmap must be\r\n//\r\n//   Character advance/positioning\r\n//           stbtt_GetCodepointHMetrics()\r\n//           stbtt_GetFontVMetrics()\r\n//           stbtt_GetFontVMetricsOS2()\r\n//           stbtt_GetCodepointKernAdvance()\r\n//\r\n//   Starting with version 1.06, the rasterizer was replaced with a new,\r\n//   faster and generally-more-precise rasterizer. The new rasterizer more\r\n//   accurately measures pixel coverage for anti-aliasing, except in the case\r\n//   where multiple shapes overlap, in which case it overestimates the AA pixel\r\n//   coverage. Thus, anti-aliasing of intersecting shapes may look wrong. If\r\n//   this turns out to be a problem, you can re-enable the old rasterizer with\r\n//        #define STBTT_RASTERIZER_VERSION 1\r\n//   which will incur about a 15% speed hit.\r\n//\r\n// ADDITIONAL DOCUMENTATION\r\n//\r\n//   Immediately after this block comment are a series of sample programs.\r\n//\r\n//   After the sample programs is the \"header file\" section. This section\r\n//   includes documentation for each API function.\r\n//\r\n//   Some important concepts to understand to use this library:\r\n//\r\n//      Codepoint\r\n//         Characters are defined by unicode codepoints, e.g. 65 is\r\n//         uppercase A, 231 is lowercase c with a cedilla, 0x7e30 is\r\n//         the hiragana for \"ma\".\r\n//\r\n//      Glyph\r\n//         A visual character shape (every codepoint is rendered as\r\n//         some glyph)\r\n//\r\n//      Glyph index\r\n//         A font-specific integer ID representing a glyph\r\n//\r\n//      Baseline\r\n//         Glyph shapes are defined relative to a baseline, which is the\r\n//         bottom of uppercase characters. Characters extend both above\r\n//         and below the baseline.\r\n//\r\n//      Current Point\r\n//         As you draw text to the screen, you keep track of a \"current point\"\r\n//         which is the origin of each character. The current point's vertical\r\n//         position is the baseline. Even \"baked fonts\" use this model.\r\n//\r\n//      Vertical Font Metrics\r\n//         The vertical qualities of the font, used to vertically position\r\n//         and space the characters. See docs for stbtt_GetFontVMetrics.\r\n//\r\n//      Font Size in Pixels or Points\r\n//         The preferred interface for specifying font sizes in stb_truetype\r\n//         is to specify how tall the font's vertical extent should be in pixels.\r\n//         If that sounds good enough, skip the next paragraph.\r\n//\r\n//         Most font APIs instead use \"points\", which are a common typographic\r\n//         measurement for describing font size, defined as 72 points per inch.\r\n//         stb_truetype provides a point API for compatibility. However, true\r\n//         \"per inch\" conventions don't make much sense on computer displays\r\n//         since different monitors have different number of pixels per\r\n//         inch. For example, Windows traditionally uses a convention that\r\n//         there are 96 pixels per inch, thus making 'inch' measurements have\r\n//         nothing to do with inches, and thus effectively defining a point to\r\n//         be 1.333 pixels. Additionally, the TrueType font data provides\r\n//         an explicit scale factor to scale a given font's glyphs to points,\r\n//         but the author has observed that this scale factor is often wrong\r\n//         for non-commercial fonts, thus making fonts scaled in points\r\n//         according to the TrueType spec incoherently sized in practice.\r\n//\r\n// DETAILED USAGE:\r\n//\r\n//  Scale:\r\n//    Select how high you want the font to be, in points or pixels.\r\n//    Call ScaleForPixelHeight or ScaleForMappingEmToPixels to compute\r\n//    a scale factor SF that will be used by all other functions.\r\n//\r\n//  Baseline:\r\n//    You need to select a y-coordinate that is the baseline of where\r\n//    your text will appear. Call GetFontBoundingBox to get the baseline-relative\r\n//    bounding box for all characters. SF*-y0 will be the distance in pixels\r\n//    that the worst-case character could extend above the baseline, so if\r\n//    you want the top edge of characters to appear at the top of the\r\n//    screen where y=0, then you would set the baseline to SF*-y0.\r\n//\r\n//  Current point:\r\n//    Set the current point where the first character will appear. The\r\n//    first character could extend left of the current point; this is font\r\n//    dependent. You can either choose a current point that is the leftmost\r\n//    point and hope, or add some padding, or check the bounding box or\r\n//    left-side-bearing of the first character to be displayed and set\r\n//    the current point based on that.\r\n//\r\n//  Displaying a character:\r\n//    Compute the bounding box of the character. It will contain signed values\r\n//    relative to <current_point, baseline>. I.e. if it returns x0,y0,x1,y1,\r\n//    then the character should be displayed in the rectangle from\r\n//    <current_point+SF*x0, baseline+SF*y0> to <current_point+SF*x1,baseline+SF*y1).\r\n//\r\n//  Advancing for the next character:\r\n//    Call GlyphHMetrics, and compute 'current_point += SF * advance'.\r\n//\r\n//\r\n// ADVANCED USAGE\r\n//\r\n//   Quality:\r\n//\r\n//    - Use the functions with Subpixel at the end to allow your characters\r\n//      to have subpixel positioning. Since the font is anti-aliased, not\r\n//      hinted, this is very import for quality. (This is not possible with\r\n//      baked fonts.)\r\n//\r\n//    - Kerning is now supported, and if you're supporting subpixel rendering\r\n//      then kerning is worth using to give your text a polished look.\r\n//\r\n//   Performance:\r\n//\r\n//    - Convert Unicode codepoints to glyph indexes and operate on the glyphs;\r\n//      if you don't do this, stb_truetype is forced to do the conversion on\r\n//      every call.\r\n//\r\n//    - There are a lot of memory allocations. We should modify it to take\r\n//      a temp buffer and allocate from the temp buffer (without freeing),\r\n//      should help performance a lot.\r\n//\r\n// NOTES\r\n//\r\n//   The system uses the raw data found in the .ttf file without changing it\r\n//   and without building auxiliary data structures. This is a bit inefficient\r\n//   on little-endian systems (the data is big-endian), but assuming you're\r\n//   caching the bitmaps or glyph shapes this shouldn't be a big deal.\r\n//\r\n//   It appears to be very hard to programmatically determine what font a\r\n//   given file is in a general way. I provide an API for this, but I don't\r\n//   recommend it.\r\n//\r\n//\r\n// SOURCE STATISTICS (based on v0.6c, 2050 LOC)\r\n//\r\n//   Documentation & header file        520 LOC  \\___ 660 LOC documentation\r\n//   Sample code                        140 LOC  /\r\n//   Truetype parsing                   620 LOC  ---- 620 LOC TrueType\r\n//   Software rasterization             240 LOC  \\.\r\n//   Curve tessellation                 120 LOC   \\__ 550 LOC Bitmap creation\r\n//   Bitmap management                  100 LOC   /\r\n//   Baked bitmap interface              70 LOC  /\r\n//   Font name matching & access        150 LOC  ---- 150\r\n//   C runtime library abstraction       60 LOC  ----  60\r\n//\r\n//\r\n// PERFORMANCE MEASUREMENTS FOR 1.06:\r\n//\r\n//                      32-bit     64-bit\r\n//   Previous release:  8.83 s     7.68 s\r\n//   Pool allocations:  7.72 s     6.34 s\r\n//   Inline sort     :  6.54 s     5.65 s\r\n//   New rasterizer  :  5.63 s     5.00 s\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//////////////////////////////////////////////////////////////////////////////\r\n////\r\n////  SAMPLE PROGRAMS\r\n////\r\n//\r\n//  Incomplete text-in-3d-api example, which draws quads properly aligned to be lossless\r\n//\r\n#if 0\r\n#define STB_TRUETYPE_IMPLEMENTATION  // force following include to generate implementation\r\n#include \"stb_truetype.h\"\r\n\r\nunsigned char ttf_buffer[1<<20];\r\nunsigned char temp_bitmap[512*512];\r\n\r\nstbtt_bakedchar cdata[96]; // ASCII 32..126 is 95 glyphs\r\nGLuint ftex;\r\n\r\nvoid my_stbtt_initfont(void)\r\n{\r\n   fread(ttf_buffer, 1, 1<<20, fopen(\"c:/windows/fonts/times.ttf\", \"rb\"));\r\n   stbtt_BakeFontBitmap(ttf_buffer,0, 32.0, temp_bitmap,512,512, 32,96, cdata); // no guarantee this fits!\r\n   // can free ttf_buffer at this point\r\n   glGenTextures(1, &ftex);\r\n   glBindTexture(GL_TEXTURE_2D, ftex);\r\n   glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, 512,512, 0, GL_ALPHA, GL_UNSIGNED_BYTE, temp_bitmap);\r\n   // can free temp_bitmap at this point\r\n   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\r\n}\r\n\r\nvoid my_stbtt_print(float x, float y, char *text)\r\n{\r\n   // assume orthographic projection with units = screen pixels, origin at top left\r\n   glEnable(GL_TEXTURE_2D);\r\n   glBindTexture(GL_TEXTURE_2D, ftex);\r\n   glBegin(GL_QUADS);\r\n   while (*text) {\r\n      if (*text >= 32 && *text < 128) {\r\n         stbtt_aligned_quad q;\r\n         stbtt_GetBakedQuad(cdata, 512,512, *text-32, &x,&y,&q,1);//1=opengl & d3d10+,0=d3d9\r\n         glTexCoord2f(q.s0,q.t1); glVertex2f(q.x0,q.y0);\r\n         glTexCoord2f(q.s1,q.t1); glVertex2f(q.x1,q.y0);\r\n         glTexCoord2f(q.s1,q.t0); glVertex2f(q.x1,q.y1);\r\n         glTexCoord2f(q.s0,q.t0); glVertex2f(q.x0,q.y1);\r\n      }\r\n      ++text;\r\n   }\r\n   glEnd();\r\n}\r\n#endif\r\n//\r\n//\r\n//////////////////////////////////////////////////////////////////////////////\r\n//\r\n// Complete program (this compiles): get a single bitmap, print as ASCII art\r\n//\r\n#if 0\r\n#include <stdio.h>\r\n#define STB_TRUETYPE_IMPLEMENTATION  // force following include to generate implementation\r\n#include \"stb_truetype.h\"\r\n\r\nchar ttf_buffer[1<<25];\r\n\r\nint main(int argc, char **argv)\r\n{\r\n   stbtt_fontinfo font;\r\n   unsigned char *bitmap;\r\n   int w,h,i,j,c = (argc > 1 ? atoi(argv[1]) : 'a'), s = (argc > 2 ? atoi(argv[2]) : 20);\r\n\r\n   fread(ttf_buffer, 1, 1<<25, fopen(argc > 3 ? argv[3] : \"c:/windows/fonts/arialbd.ttf\", \"rb\"));\r\n\r\n   stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer,0));\r\n   bitmap = stbtt_GetCodepointBitmap(&font, 0,stbtt_ScaleForPixelHeight(&font, s), c, &w, &h, 0,0);\r\n\r\n   for (j=0; j < h; ++j) {\r\n      for (i=0; i < w; ++i)\r\n         putchar(\" .:ioVM@\"[bitmap[j*w+i]>>5]);\r\n      putchar('\\n');\r\n   }\r\n   return 0;\r\n}\r\n#endif\r\n//\r\n// Output:\r\n//\r\n//     .ii.\r\n//    @@@@@@.\r\n//   V@Mio@@o\r\n//   :i.  V@V\r\n//     :oM@@M\r\n//   :@@@MM@M\r\n//   @@o  o@M\r\n//  :@@.  M@M\r\n//   @@@o@@@@\r\n//   :M@@V:@@.\r\n//\r\n//////////////////////////////////////////////////////////////////////////////\r\n//\r\n// Complete program: print \"Hello World!\" banner, with bugs\r\n//\r\n#if 0\r\nchar buffer[24<<20];\r\nunsigned char screen[20][79];\r\n\r\nint main(int arg, char **argv)\r\n{\r\n   stbtt_fontinfo font;\r\n   int i,j,ascent,baseline,ch=0;\r\n   float scale, xpos=2; // leave a little padding in case the character extends left\r\n   char *text = \"Heljo World!\"; // intentionally misspelled to show 'lj' brokenness\r\n\r\n   fread(buffer, 1, 1000000, fopen(\"c:/windows/fonts/arialbd.ttf\", \"rb\"));\r\n   stbtt_InitFont(&font, buffer, 0);\r\n\r\n   scale = stbtt_ScaleForPixelHeight(&font, 15);\r\n   stbtt_GetFontVMetrics(&font, &ascent,0,0);\r\n   baseline = (int) (ascent*scale);\r\n\r\n   while (text[ch]) {\r\n      int advance,lsb,x0,y0,x1,y1;\r\n      float x_shift = xpos - (float) floor(xpos);\r\n      stbtt_GetCodepointHMetrics(&font, text[ch], &advance, &lsb);\r\n      stbtt_GetCodepointBitmapBoxSubpixel(&font, text[ch], scale,scale,x_shift,0, &x0,&y0,&x1,&y1);\r\n      stbtt_MakeCodepointBitmapSubpixel(&font, &screen[baseline + y0][(int) xpos + x0], x1-x0,y1-y0, 79, scale,scale,x_shift,0, text[ch]);\r\n      // note that this stomps the old data, so where character boxes overlap (e.g. 'lj') it's wrong\r\n      // because this API is really for baking character bitmaps into textures. if you want to render\r\n      // a sequence of characters, you really need to render each bitmap to a temp buffer, then\r\n      // \"alpha blend\" that into the working buffer\r\n      xpos += (advance * scale);\r\n      if (text[ch+1])\r\n         xpos += scale*stbtt_GetCodepointKernAdvance(&font, text[ch],text[ch+1]);\r\n      ++ch;\r\n   }\r\n\r\n   for (j=0; j < 20; ++j) {\r\n      for (i=0; i < 78; ++i)\r\n         putchar(\" .:ioVM@\"[screen[j][i]>>5]);\r\n      putchar('\\n');\r\n   }\r\n\r\n   return 0;\r\n}\r\n#endif\r\n\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//////////////////////////////////////////////////////////////////////////////\r\n////\r\n////   INTEGRATION WITH YOUR CODEBASE\r\n////\r\n////   The following sections allow you to supply alternate definitions\r\n////   of C library functions used by stb_truetype, e.g. if you don't\r\n////   link with the C runtime library.\r\n\r\n#ifdef STB_TRUETYPE_IMPLEMENTATION\r\n   // #define your own (u)stbtt_int8/16/32 before including to override this\r\n   #ifndef stbtt_uint8\r\n   typedef unsigned char   stbtt_uint8;\r\n   typedef signed   char   stbtt_int8;\r\n   typedef unsigned short  stbtt_uint16;\r\n   typedef signed   short  stbtt_int16;\r\n   typedef unsigned int    stbtt_uint32;\r\n   typedef signed   int    stbtt_int32;\r\n   #endif\r\n\r\n   typedef char stbtt__check_size32[sizeof(stbtt_int32)==4 ? 1 : -1];\r\n   typedef char stbtt__check_size16[sizeof(stbtt_int16)==2 ? 1 : -1];\r\n\r\n   // e.g. #define your own STBTT_ifloor/STBTT_iceil() to avoid math.h\r\n   #ifndef STBTT_ifloor\r\n   #include <math.h>\r\n   #define STBTT_ifloor(x)   ((int) floor(x))\r\n   #define STBTT_iceil(x)    ((int) ceil(x))\r\n   #endif\r\n\r\n   #ifndef STBTT_sqrt\r\n   #include <math.h>\r\n   #define STBTT_sqrt(x)      sqrt(x)\r\n   #define STBTT_pow(x,y)     pow(x,y)\r\n   #endif\r\n\r\n   #ifndef STBTT_fmod\r\n   #include <math.h>\r\n   #define STBTT_fmod(x,y)    fmod(x,y)\r\n   #endif\r\n\r\n   #ifndef STBTT_cos\r\n   #include <math.h>\r\n   #define STBTT_cos(x)       cos(x)\r\n   #define STBTT_acos(x)      acos(x)\r\n   #endif\r\n\r\n   #ifndef STBTT_fabs\r\n   #include <math.h>\r\n   #define STBTT_fabs(x)      fabs(x)\r\n   #endif\r\n\r\n   // #define your own functions \"STBTT_malloc\" / \"STBTT_free\" to avoid malloc.h\r\n   #ifndef STBTT_malloc\r\n   #include <stdlib.h>\r\n   #define STBTT_malloc(x,u)  ((void)(u),malloc(x))\r\n   #define STBTT_free(x,u)    ((void)(u),free(x))\r\n   #endif\r\n\r\n   #ifndef STBTT_assert\r\n   #include <assert.h>\r\n   #define STBTT_assert(x)    assert(x)\r\n   #endif\r\n\r\n   #ifndef STBTT_strlen\r\n   #include <string.h>\r\n   #define STBTT_strlen(x)    strlen(x)\r\n   #endif\r\n\r\n   #ifndef STBTT_memcpy\r\n   #include <string.h>\r\n   #define STBTT_memcpy       memcpy\r\n   #define STBTT_memset       memset\r\n   #endif\r\n#endif\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n///////////////////////////////////////////////////////////////////////////////\r\n////\r\n////   INTERFACE\r\n////\r\n////\r\n\r\n#ifndef __STB_INCLUDE_STB_TRUETYPE_H__\r\n#define __STB_INCLUDE_STB_TRUETYPE_H__\r\n\r\n#ifdef STBTT_STATIC\r\n#define STBTT_DEF static\r\n#else\r\n#define STBTT_DEF extern\r\n#endif\r\n\r\n#ifdef __cplusplus\r\nextern \"C\" {\r\n#endif\r\n\r\n// private structure\r\ntypedef struct\r\n{\r\n   unsigned char *data;\r\n   int cursor;\r\n   int size;\r\n} stbtt__buf;\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//\r\n// TEXTURE BAKING API\r\n//\r\n// If you use this API, you only have to call two functions ever.\r\n//\r\n\r\ntypedef struct\r\n{\r\n   unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap\r\n   float xoff,yoff,xadvance;\r\n} stbtt_bakedchar;\r\n\r\nSTBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset,  // font location (use offset=0 for plain .ttf)\r\n                                float pixel_height,                     // height of font in pixels\r\n                                unsigned char *pixels, int pw, int ph,  // bitmap to be filled in\r\n                                int first_char, int num_chars,          // characters to bake\r\n                                stbtt_bakedchar *chardata);             // you allocate this, it's num_chars long\r\n// if return is positive, the first unused row of the bitmap\r\n// if return is negative, returns the negative of the number of characters that fit\r\n// if return is 0, no characters fit and no rows were used\r\n// This uses a very crappy packing.\r\n\r\ntypedef struct\r\n{\r\n   float x0,y0,s0,t0; // top-left\r\n   float x1,y1,s1,t1; // bottom-right\r\n} stbtt_aligned_quad;\r\n\r\nSTBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph,  // same data as above\r\n                               int char_index,             // character to display\r\n                               float *xpos, float *ypos,   // pointers to current position in screen pixel space\r\n                               stbtt_aligned_quad *q,      // output: quad to draw\r\n                               int opengl_fillrule);       // true if opengl fill rule; false if DX9 or earlier\r\n// Call GetBakedQuad with char_index = 'character - first_char', and it\r\n// creates the quad you need to draw and advances the current position.\r\n//\r\n// The coordinate system used assumes y increases downwards.\r\n//\r\n// Characters will extend both above and below the current position;\r\n// see discussion of \"BASELINE\" above.\r\n//\r\n// It's inefficient; you might want to c&p it and optimize it.\r\n\r\nSTBTT_DEF void stbtt_GetScaledFontVMetrics(const unsigned char *fontdata, int index, float size, float *ascent, float *descent, float *lineGap);\r\n// Query the font vertical metrics without having to create a font first.\r\n\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//\r\n// NEW TEXTURE BAKING API\r\n//\r\n// This provides options for packing multiple fonts into one atlas, not\r\n// perfectly but better than nothing.\r\n\r\ntypedef struct\r\n{\r\n   unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap\r\n   float xoff,yoff,xadvance;\r\n   float xoff2,yoff2;\r\n} stbtt_packedchar;\r\n\r\ntypedef struct stbtt_pack_context stbtt_pack_context;\r\ntypedef struct stbtt_fontinfo stbtt_fontinfo;\r\n#ifndef STB_RECT_PACK_VERSION\r\ntypedef struct stbrp_rect stbrp_rect;\r\n#endif\r\n\r\nSTBTT_DEF int  stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int width, int height, int stride_in_bytes, int padding, void *alloc_context);\r\n// Initializes a packing context stored in the passed-in stbtt_pack_context.\r\n// Future calls using this context will pack characters into the bitmap passed\r\n// in here: a 1-channel bitmap that is width * height. stride_in_bytes is\r\n// the distance from one row to the next (or 0 to mean they are packed tightly\r\n// together). \"padding\" is the amount of padding to leave between each\r\n// character (normally you want '1' for bitmaps you'll use as textures with\r\n// bilinear filtering).\r\n//\r\n// Returns 0 on failure, 1 on success.\r\n\r\nSTBTT_DEF void stbtt_PackEnd  (stbtt_pack_context *spc);\r\n// Cleans up the packing context and frees all memory.\r\n\r\n#define STBTT_POINT_SIZE(x)   (-(x))\r\n\r\nSTBTT_DEF int  stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, float font_size,\r\n                                int first_unicode_char_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range);\r\n// Creates character bitmaps from the font_index'th font found in fontdata (use\r\n// font_index=0 if you don't know what that is). It creates num_chars_in_range\r\n// bitmaps for characters with unicode values starting at first_unicode_char_in_range\r\n// and increasing. Data for how to render them is stored in chardata_for_range;\r\n// pass these to stbtt_GetPackedQuad to get back renderable quads.\r\n//\r\n// font_size is the full height of the character from ascender to descender,\r\n// as computed by stbtt_ScaleForPixelHeight. To use a point size as computed\r\n// by stbtt_ScaleForMappingEmToPixels, wrap the point size in STBTT_POINT_SIZE()\r\n// and pass that result as 'font_size':\r\n//       ...,                  20 , ... // font max minus min y is 20 pixels tall\r\n//       ..., STBTT_POINT_SIZE(20), ... // 'M' is 20 pixels tall\r\n\r\ntypedef struct\r\n{\r\n   float font_size;\r\n   int first_unicode_codepoint_in_range;  // if non-zero, then the chars are continuous, and this is the first codepoint\r\n   int *array_of_unicode_codepoints;       // if non-zero, then this is an array of unicode codepoints\r\n   int num_chars;\r\n   stbtt_packedchar *chardata_for_range; // output\r\n   unsigned char h_oversample, v_oversample; // don't set these, they're used internally\r\n} stbtt_pack_range;\r\n\r\nSTBTT_DEF int  stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges);\r\n// Creates character bitmaps from multiple ranges of characters stored in\r\n// ranges. This will usually create a better-packed bitmap than multiple\r\n// calls to stbtt_PackFontRange. Note that you can call this multiple\r\n// times within a single PackBegin/PackEnd.\r\n\r\nSTBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample);\r\n// Oversampling a font increases the quality by allowing higher-quality subpixel\r\n// positioning, and is especially valuable at smaller text sizes.\r\n//\r\n// This function sets the amount of oversampling for all following calls to\r\n// stbtt_PackFontRange(s) or stbtt_PackFontRangesGatherRects for a given\r\n// pack context. The default (no oversampling) is achieved by h_oversample=1\r\n// and v_oversample=1. The total number of pixels required is\r\n// h_oversample*v_oversample larger than the default; for example, 2x2\r\n// oversampling requires 4x the storage of 1x1. For best results, render\r\n// oversampled textures with bilinear filtering. Look at the readme in\r\n// stb/tests/oversample for information about oversampled fonts\r\n//\r\n// To use with PackFontRangesGather etc., you must set it before calls\r\n// call to PackFontRangesGatherRects.\r\n\r\nSTBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context *spc, int skip);\r\n// If skip != 0, this tells stb_truetype to skip any codepoints for which\r\n// there is no corresponding glyph. If skip=0, which is the default, then\r\n// codepoints without a glyph recived the font's \"missing character\" glyph,\r\n// typically an empty box by convention.\r\n\r\nSTBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph,  // same data as above\r\n                               int char_index,             // character to display\r\n                               float *xpos, float *ypos,   // pointers to current position in screen pixel space\r\n                               stbtt_aligned_quad *q,      // output: quad to draw\r\n                               int align_to_integer);\r\n\r\nSTBTT_DEF int  stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects);\r\nSTBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects);\r\nSTBTT_DEF int  stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects);\r\n// Calling these functions in sequence is roughly equivalent to calling\r\n// stbtt_PackFontRanges(). If you more control over the packing of multiple\r\n// fonts, or if you want to pack custom data into a font texture, take a look\r\n// at the source to of stbtt_PackFontRanges() and create a custom version\r\n// using these functions, e.g. call GatherRects multiple times,\r\n// building up a single array of rects, then call PackRects once,\r\n// then call RenderIntoRects repeatedly. This may result in a\r\n// better packing than calling PackFontRanges multiple times\r\n// (or it may not).\r\n\r\n// this is an opaque structure that you shouldn't mess with which holds\r\n// all the context needed from PackBegin to PackEnd.\r\nstruct stbtt_pack_context {\r\n   void *user_allocator_context;\r\n   void *pack_info;\r\n   int   width;\r\n   int   height;\r\n   int   stride_in_bytes;\r\n   int   padding;\r\n   int   skip_missing;\r\n   unsigned int   h_oversample, v_oversample;\r\n   unsigned char *pixels;\r\n   void  *nodes;\r\n};\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//\r\n// FONT LOADING\r\n//\r\n//\r\n\r\nSTBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data);\r\n// This function will determine the number of fonts in a font file.  TrueType\r\n// collection (.ttc) files may contain multiple fonts, while TrueType font\r\n// (.ttf) files only contain one font. The number of fonts can be used for\r\n// indexing with the previous function where the index is between zero and one\r\n// less than the total fonts. If an error occurs, -1 is returned.\r\n\r\nSTBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index);\r\n// Each .ttf/.ttc file may have more than one font. Each font has a sequential\r\n// index number starting from 0. Call this function to get the font offset for\r\n// a given index; it returns -1 if the index is out of range. A regular .ttf\r\n// file will only define one font and it always be at offset 0, so it will\r\n// return '0' for index 0, and -1 for all other indices.\r\n\r\n// The following structure is defined publicly so you can declare one on\r\n// the stack or as a global or etc, but you should treat it as opaque.\r\nstruct stbtt_fontinfo\r\n{\r\n   void           * userdata;\r\n   unsigned char  * data;              // pointer to .ttf file\r\n   int              fontstart;         // offset of start of font\r\n\r\n   int numGlyphs;                     // number of glyphs, needed for range checking\r\n\r\n   int loca,head,glyf,hhea,hmtx,kern,gpos; // table locations as offset from start of .ttf\r\n   int index_map;                     // a cmap mapping for our chosen character encoding\r\n   int indexToLocFormat;              // format needed to map from glyph index to glyph\r\n\r\n   stbtt__buf cff;                    // cff font data\r\n   stbtt__buf charstrings;            // the charstring index\r\n   stbtt__buf gsubrs;                 // global charstring subroutines index\r\n   stbtt__buf subrs;                  // private charstring subroutines index\r\n   stbtt__buf fontdicts;              // array of font dicts\r\n   stbtt__buf fdselect;               // map from glyph to fontdict\r\n};\r\n\r\nSTBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset);\r\n// Given an offset into the file that defines a font, this function builds\r\n// the necessary cached info for the rest of the system. You must allocate\r\n// the stbtt_fontinfo yourself, and stbtt_InitFont will fill it out. You don't\r\n// need to do anything special to free it, because the contents are pure\r\n// value data with no additional data structures. Returns 0 on failure.\r\n\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//\r\n// CHARACTER TO GLYPH-INDEX CONVERSIOn\r\n\r\nSTBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint);\r\n// If you're going to perform multiple operations on the same character\r\n// and you want a speed-up, call this function with the character you're\r\n// going to process, then use glyph-based functions instead of the\r\n// codepoint-based functions.\r\n// Returns 0 if the character codepoint is not defined in the font.\r\n\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//\r\n// CHARACTER PROPERTIES\r\n//\r\n\r\nSTBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float pixels);\r\n// computes a scale factor to produce a font whose \"height\" is 'pixels' tall.\r\n// Height is measured as the distance from the highest ascender to the lowest\r\n// descender; in other words, it's equivalent to calling stbtt_GetFontVMetrics\r\n// and computing:\r\n//       scale = pixels / (ascent - descent)\r\n// so if you prefer to measure height by the ascent only, use a similar calculation.\r\n\r\nSTBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels);\r\n// computes a scale factor to produce a font whose EM size is mapped to\r\n// 'pixels' tall. This is probably what traditional APIs compute, but\r\n// I'm not positive.\r\n\r\nSTBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap);\r\n// ascent is the coordinate above the baseline the font extends; descent\r\n// is the coordinate below the baseline the font extends (i.e. it is typically negative)\r\n// lineGap is the spacing between one row's descent and the next row's ascent...\r\n// so you should advance the vertical position by \"*ascent - *descent + *lineGap\"\r\n//   these are expressed in unscaled coordinates, so you must multiply by\r\n//   the scale factor for a given size\r\n\r\nSTBTT_DEF int  stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap);\r\n// analogous to GetFontVMetrics, but returns the \"typographic\" values from the OS/2\r\n// table (specific to MS/Windows TTF files).\r\n//\r\n// Returns 1 on success (table present), 0 on failure.\r\n\r\nSTBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1);\r\n// the bounding box around all possible characters\r\n\r\nSTBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing);\r\n// leftSideBearing is the offset from the current horizontal position to the left edge of the character\r\n// advanceWidth is the offset from the current horizontal position to the next horizontal position\r\n//   these are expressed in unscaled coordinates\r\n\r\nSTBTT_DEF int  stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2);\r\n// an additional amount to add to the 'advance' value between ch1 and ch2\r\n\r\nSTBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1);\r\n// Gets the bounding box of the visible part of the glyph, in unscaled coordinates\r\n\r\nSTBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing);\r\nSTBTT_DEF int  stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2);\r\nSTBTT_DEF int  stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1);\r\n// as above, but takes one or more glyph indices for greater efficiency\r\n\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//\r\n// GLYPH SHAPES (you probably don't need these, but they have to go before\r\n// the bitmaps for C declaration-order reasons)\r\n//\r\n\r\n#ifndef STBTT_vmove // you can predefine these to use different values (but why?)\r\n   enum {\r\n      STBTT_vmove=1,\r\n      STBTT_vline,\r\n      STBTT_vcurve,\r\n      STBTT_vcubic\r\n   };\r\n#endif\r\n\r\n#ifndef stbtt_vertex // you can predefine this to use different values\r\n                   // (we share this with other code at RAD)\r\n   #define stbtt_vertex_type short // can't use stbtt_int16 because that's not visible in the header file\r\n   typedef struct\r\n   {\r\n      stbtt_vertex_type x,y,cx,cy,cx1,cy1;\r\n      unsigned char type,padding;\r\n   } stbtt_vertex;\r\n#endif\r\n\r\nSTBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index);\r\n// returns non-zero if nothing is drawn for this glyph\r\n\r\nSTBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices);\r\nSTBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **vertices);\r\n// returns # of vertices and fills *vertices with the pointer to them\r\n//   these are expressed in \"unscaled\" coordinates\r\n//\r\n// The shape is a series of contours. Each one starts with\r\n// a STBTT_moveto, then consists of a series of mixed\r\n// STBTT_lineto and STBTT_curveto segments. A lineto\r\n// draws a line from previous endpoint to its x,y; a curveto\r\n// draws a quadratic bezier from previous endpoint to\r\n// its x,y, using cx,cy as the bezier control point.\r\n\r\nSTBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *vertices);\r\n// frees the data allocated above\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//\r\n// BITMAP RENDERING\r\n//\r\n\r\nSTBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata);\r\n// frees the bitmap allocated below\r\n\r\nSTBTT_DEF unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff);\r\n// allocates a large-enough single-channel 8bpp bitmap and renders the\r\n// specified character/glyph at the specified scale into it, with\r\n// antialiasing. 0 is no coverage (transparent), 255 is fully covered (opaque).\r\n// *width & *height are filled out with the width & height of the bitmap,\r\n// which is stored left-to-right, top-to-bottom.\r\n//\r\n// xoff/yoff are the offset it pixel space from the glyph origin to the top-left of the bitmap\r\n\r\nSTBTT_DEF unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff);\r\n// the same as stbtt_GetCodepoitnBitmap, but you can specify a subpixel\r\n// shift for the character\r\n\r\nSTBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint);\r\n// the same as stbtt_GetCodepointBitmap, but you pass in storage for the bitmap\r\n// in the form of 'output', with row spacing of 'out_stride' bytes. the bitmap\r\n// is clipped to out_w/out_h bytes. Call stbtt_GetCodepointBitmapBox to get the\r\n// width and height and positioning info for it first.\r\n\r\nSTBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint);\r\n// same as stbtt_MakeCodepointBitmap, but you can specify a subpixel\r\n// shift for the character\r\n\r\nSTBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int codepoint);\r\n// same as stbtt_MakeCodepointBitmapSubpixel, but prefiltering\r\n// is performed (see stbtt_PackSetOversampling)\r\n\r\nSTBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1);\r\n// get the bbox of the bitmap centered around the glyph origin; so the\r\n// bitmap width is ix1-ix0, height is iy1-iy0, and location to place\r\n// the bitmap top left is (leftSideBearing*scale,iy0).\r\n// (Note that the bitmap uses y-increases-down, but the shape uses\r\n// y-increases-up, so CodepointBitmapBox and CodepointBox are inverted.)\r\n\r\nSTBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1);\r\n// same as stbtt_GetCodepointBitmapBox, but you can specify a subpixel\r\n// shift for the character\r\n\r\n// the following functions are equivalent to the above functions, but operate\r\n// on glyph indices instead of Unicode codepoints (for efficiency)\r\nSTBTT_DEF unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff);\r\nSTBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff);\r\nSTBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph);\r\nSTBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph);\r\nSTBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int glyph);\r\nSTBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1);\r\nSTBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1);\r\n\r\n\r\n// @TODO: don't expose this structure\r\ntypedef struct\r\n{\r\n   int w,h,stride;\r\n   unsigned char *pixels;\r\n} stbtt__bitmap;\r\n\r\n// rasterize a shape with quadratic beziers into a bitmap\r\nSTBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result,        // 1-channel bitmap to draw into\r\n                               float flatness_in_pixels,     // allowable error of curve in pixels\r\n                               stbtt_vertex *vertices,       // array of vertices defining shape\r\n                               int num_verts,                // number of vertices in above array\r\n                               float scale_x, float scale_y, // scale applied to input vertices\r\n                               float shift_x, float shift_y, // translation applied to input vertices\r\n                               int x_off, int y_off,         // another translation applied to input\r\n                               int invert,                   // if non-zero, vertically flip shape\r\n                               void *userdata);              // context for to STBTT_MALLOC\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//\r\n// Signed Distance Function (or Field) rendering\r\n\r\nSTBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata);\r\n// frees the SDF bitmap allocated below\r\n\r\nSTBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff);\r\nSTBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff);\r\n// These functions compute a discretized SDF field for a single character, suitable for storing\r\n// in a single-channel texture, sampling with bilinear filtering, and testing against\r\n// larger than some threshold to produce scalable fonts.\r\n//        info              --  the font\r\n//        scale             --  controls the size of the resulting SDF bitmap, same as it would be creating a regular bitmap\r\n//        glyph/codepoint   --  the character to generate the SDF for\r\n//        padding           --  extra \"pixels\" around the character which are filled with the distance to the character (not 0),\r\n//                                 which allows effects like bit outlines\r\n//        onedge_value      --  value 0-255 to test the SDF against to reconstruct the character (i.e. the isocontour of the character)\r\n//        pixel_dist_scale  --  what value the SDF should increase by when moving one SDF \"pixel\" away from the edge (on the 0..255 scale)\r\n//                                 if positive, > onedge_value is inside; if negative, < onedge_value is inside\r\n//        width,height      --  output height & width of the SDF bitmap (including padding)\r\n//        xoff,yoff         --  output origin of the character\r\n//        return value      --  a 2D array of bytes 0..255, width*height in size\r\n//\r\n// pixel_dist_scale & onedge_value are a scale & bias that allows you to make\r\n// optimal use of the limited 0..255 for your application, trading off precision\r\n// and special effects. SDF values outside the range 0..255 are clamped to 0..255.\r\n//\r\n// Example:\r\n//      scale = stbtt_ScaleForPixelHeight(22)\r\n//      padding = 5\r\n//      onedge_value = 180\r\n//      pixel_dist_scale = 180/5.0 = 36.0\r\n//\r\n//      This will create an SDF bitmap in which the character is about 22 pixels\r\n//      high but the whole bitmap is about 22+5+5=32 pixels high. To produce a filled\r\n//      shape, sample the SDF at each pixel and fill the pixel if the SDF value\r\n//      is greater than or equal to 180/255. (You'll actually want to antialias,\r\n//      which is beyond the scope of this example.) Additionally, you can compute\r\n//      offset outlines (e.g. to stroke the character border inside & outside,\r\n//      or only outside). For example, to fill outside the character up to 3 SDF\r\n//      pixels, you would compare against (180-36.0*3)/255 = 72/255. The above\r\n//      choice of variables maps a range from 5 pixels outside the shape to\r\n//      2 pixels inside the shape to 0..255; this is intended primarily for apply\r\n//      outside effects only (the interior range is needed to allow proper\r\n//      antialiasing of the font at *smaller* sizes)\r\n//\r\n// The function computes the SDF analytically at each SDF pixel, not by e.g.\r\n// building a higher-res bitmap and approximating it. In theory the quality\r\n// should be as high as possible for an SDF of this size & representation, but\r\n// unclear if this is true in practice (perhaps building a higher-res bitmap\r\n// and computing from that can allow drop-out prevention).\r\n//\r\n// The algorithm has not been optimized at all, so expect it to be slow\r\n// if computing lots of characters or very large sizes.\r\n\r\n\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//\r\n// Finding the right font...\r\n//\r\n// You should really just solve this offline, keep your own tables\r\n// of what font is what, and don't try to get it out of the .ttf file.\r\n// That's because getting it out of the .ttf file is really hard, because\r\n// the names in the file can appear in many possible encodings, in many\r\n// possible languages, and e.g. if you need a case-insensitive comparison,\r\n// the details of that depend on the encoding & language in a complex way\r\n// (actually underspecified in truetype, but also gigantic).\r\n//\r\n// But you can use the provided functions in two possible ways:\r\n//     stbtt_FindMatchingFont() will use *case-sensitive* comparisons on\r\n//             unicode-encoded names to try to find the font you want;\r\n//             you can run this before calling stbtt_InitFont()\r\n//\r\n//     stbtt_GetFontNameString() lets you get any of the various strings\r\n//             from the file yourself and do your own comparisons on them.\r\n//             You have to have called stbtt_InitFont() first.\r\n\r\n\r\nSTBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags);\r\n// returns the offset (not index) of the font that matches, or -1 if none\r\n//   if you use STBTT_MACSTYLE_DONTCARE, use a font name like \"Arial Bold\".\r\n//   if you use any other flag, use a font name like \"Arial\"; this checks\r\n//     the 'macStyle' header field; i don't know if fonts set this consistently\r\n#define STBTT_MACSTYLE_DONTCARE     0\r\n#define STBTT_MACSTYLE_BOLD         1\r\n#define STBTT_MACSTYLE_ITALIC       2\r\n#define STBTT_MACSTYLE_UNDERSCORE   4\r\n#define STBTT_MACSTYLE_NONE         8   // <= not same as 0, this makes us check the bitfield is 0\r\n\r\nSTBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2);\r\n// returns 1/0 whether the first string interpreted as utf8 is identical to\r\n// the second string interpreted as big-endian utf16... useful for strings from next func\r\n\r\nSTBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID);\r\n// returns the string (which may be big-endian double byte, e.g. for unicode)\r\n// and puts the length in bytes in *length.\r\n//\r\n// some of the values for the IDs are below; for more see the truetype spec:\r\n//     http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6name.html\r\n//     http://www.microsoft.com/typography/otspec/name.htm\r\n\r\nenum { // platformID\r\n   STBTT_PLATFORM_ID_UNICODE   =0,\r\n   STBTT_PLATFORM_ID_MAC       =1,\r\n   STBTT_PLATFORM_ID_ISO       =2,\r\n   STBTT_PLATFORM_ID_MICROSOFT =3\r\n};\r\n\r\nenum { // encodingID for STBTT_PLATFORM_ID_UNICODE\r\n   STBTT_UNICODE_EID_UNICODE_1_0    =0,\r\n   STBTT_UNICODE_EID_UNICODE_1_1    =1,\r\n   STBTT_UNICODE_EID_ISO_10646      =2,\r\n   STBTT_UNICODE_EID_UNICODE_2_0_BMP=3,\r\n   STBTT_UNICODE_EID_UNICODE_2_0_FULL=4\r\n};\r\n\r\nenum { // encodingID for STBTT_PLATFORM_ID_MICROSOFT\r\n   STBTT_MS_EID_SYMBOL        =0,\r\n   STBTT_MS_EID_UNICODE_BMP   =1,\r\n   STBTT_MS_EID_SHIFTJIS      =2,\r\n   STBTT_MS_EID_UNICODE_FULL  =10\r\n};\r\n\r\nenum { // encodingID for STBTT_PLATFORM_ID_MAC; same as Script Manager codes\r\n   STBTT_MAC_EID_ROMAN        =0,   STBTT_MAC_EID_ARABIC       =4,\r\n   STBTT_MAC_EID_JAPANESE     =1,   STBTT_MAC_EID_HEBREW       =5,\r\n   STBTT_MAC_EID_CHINESE_TRAD =2,   STBTT_MAC_EID_GREEK        =6,\r\n   STBTT_MAC_EID_KOREAN       =3,   STBTT_MAC_EID_RUSSIAN      =7\r\n};\r\n\r\nenum { // languageID for STBTT_PLATFORM_ID_MICROSOFT; same as LCID...\r\n       // problematic because there are e.g. 16 english LCIDs and 16 arabic LCIDs\r\n   STBTT_MS_LANG_ENGLISH     =0x0409,   STBTT_MS_LANG_ITALIAN     =0x0410,\r\n   STBTT_MS_LANG_CHINESE     =0x0804,   STBTT_MS_LANG_JAPANESE    =0x0411,\r\n   STBTT_MS_LANG_DUTCH       =0x0413,   STBTT_MS_LANG_KOREAN      =0x0412,\r\n   STBTT_MS_LANG_FRENCH      =0x040c,   STBTT_MS_LANG_RUSSIAN     =0x0419,\r\n   STBTT_MS_LANG_GERMAN      =0x0407,   STBTT_MS_LANG_SPANISH     =0x0409,\r\n   STBTT_MS_LANG_HEBREW      =0x040d,   STBTT_MS_LANG_SWEDISH     =0x041D\r\n};\r\n\r\nenum { // languageID for STBTT_PLATFORM_ID_MAC\r\n   STBTT_MAC_LANG_ENGLISH      =0 ,   STBTT_MAC_LANG_JAPANESE     =11,\r\n   STBTT_MAC_LANG_ARABIC       =12,   STBTT_MAC_LANG_KOREAN       =23,\r\n   STBTT_MAC_LANG_DUTCH        =4 ,   STBTT_MAC_LANG_RUSSIAN      =32,\r\n   STBTT_MAC_LANG_FRENCH       =1 ,   STBTT_MAC_LANG_SPANISH      =6 ,\r\n   STBTT_MAC_LANG_GERMAN       =2 ,   STBTT_MAC_LANG_SWEDISH      =5 ,\r\n   STBTT_MAC_LANG_HEBREW       =10,   STBTT_MAC_LANG_CHINESE_SIMPLIFIED =33,\r\n   STBTT_MAC_LANG_ITALIAN      =3 ,   STBTT_MAC_LANG_CHINESE_TRAD =19\r\n};\r\n\r\n#ifdef __cplusplus\r\n}\r\n#endif\r\n\r\n#endif // __STB_INCLUDE_STB_TRUETYPE_H__\r\n\r\n///////////////////////////////////////////////////////////////////////////////\r\n///////////////////////////////////////////////////////////////////////////////\r\n////\r\n////   IMPLEMENTATION\r\n////\r\n////\r\n\r\n#ifdef STB_TRUETYPE_IMPLEMENTATION\r\n\r\n#ifndef STBTT_MAX_OVERSAMPLE\r\n#define STBTT_MAX_OVERSAMPLE   8\r\n#endif\r\n\r\n#if STBTT_MAX_OVERSAMPLE > 255\r\n#error \"STBTT_MAX_OVERSAMPLE cannot be > 255\"\r\n#endif\r\n\r\ntypedef int stbtt__test_oversample_pow2[(STBTT_MAX_OVERSAMPLE & (STBTT_MAX_OVERSAMPLE-1)) == 0 ? 1 : -1];\r\n\r\n#ifndef STBTT_RASTERIZER_VERSION\r\n#define STBTT_RASTERIZER_VERSION 2\r\n#endif\r\n\r\n#ifdef _MSC_VER\r\n#define STBTT__NOTUSED(v)  (void)(v)\r\n#else\r\n#define STBTT__NOTUSED(v)  (void)sizeof(v)\r\n#endif\r\n\r\n//////////////////////////////////////////////////////////////////////////\r\n//\r\n// stbtt__buf helpers to parse data from file\r\n//\r\n\r\nstatic stbtt_uint8 stbtt__buf_get8(stbtt__buf *b)\r\n{\r\n   if (b->cursor >= b->size)\r\n      return 0;\r\n   return b->data[b->cursor++];\r\n}\r\n\r\nstatic stbtt_uint8 stbtt__buf_peek8(stbtt__buf *b)\r\n{\r\n   if (b->cursor >= b->size)\r\n      return 0;\r\n   return b->data[b->cursor];\r\n}\r\n\r\nstatic void stbtt__buf_seek(stbtt__buf *b, int o)\r\n{\r\n   STBTT_assert(!(o > b->size || o < 0));\r\n   b->cursor = (o > b->size || o < 0) ? b->size : o;\r\n}\r\n\r\nstatic void stbtt__buf_skip(stbtt__buf *b, int o)\r\n{\r\n   stbtt__buf_seek(b, b->cursor + o);\r\n}\r\n\r\nstatic stbtt_uint32 stbtt__buf_get(stbtt__buf *b, int n)\r\n{\r\n   stbtt_uint32 v = 0;\r\n   int i;\r\n   STBTT_assert(n >= 1 && n <= 4);\r\n   for (i = 0; i < n; i++)\r\n      v = (v << 8) | stbtt__buf_get8(b);\r\n   return v;\r\n}\r\n\r\nstatic stbtt__buf stbtt__new_buf(const void *p, size_t size)\r\n{\r\n   stbtt__buf r;\r\n   STBTT_assert(size < 0x40000000);\r\n   r.data = (stbtt_uint8*) p;\r\n   r.size = (int) size;\r\n   r.cursor = 0;\r\n   return r;\r\n}\r\n\r\n#define stbtt__buf_get16(b)  stbtt__buf_get((b), 2)\r\n#define stbtt__buf_get32(b)  stbtt__buf_get((b), 4)\r\n\r\nstatic stbtt__buf stbtt__buf_range(const stbtt__buf *b, int o, int s)\r\n{\r\n   stbtt__buf r = stbtt__new_buf(NULL, 0);\r\n   if (o < 0 || s < 0 || o > b->size || s > b->size - o) return r;\r\n   r.data = b->data + o;\r\n   r.size = s;\r\n   return r;\r\n}\r\n\r\nstatic stbtt__buf stbtt__cff_get_index(stbtt__buf *b)\r\n{\r\n   int count, start, offsize;\r\n   start = b->cursor;\r\n   count = stbtt__buf_get16(b);\r\n   if (count) {\r\n      offsize = stbtt__buf_get8(b);\r\n      STBTT_assert(offsize >= 1 && offsize <= 4);\r\n      stbtt__buf_skip(b, offsize * count);\r\n      stbtt__buf_skip(b, stbtt__buf_get(b, offsize) - 1);\r\n   }\r\n   return stbtt__buf_range(b, start, b->cursor - start);\r\n}\r\n\r\nstatic stbtt_uint32 stbtt__cff_int(stbtt__buf *b)\r\n{\r\n   int b0 = stbtt__buf_get8(b);\r\n   if (b0 >= 32 && b0 <= 246)       return b0 - 139;\r\n   else if (b0 >= 247 && b0 <= 250) return (b0 - 247)*256 + stbtt__buf_get8(b) + 108;\r\n   else if (b0 >= 251 && b0 <= 254) return -(b0 - 251)*256 - stbtt__buf_get8(b) - 108;\r\n   else if (b0 == 28)               return stbtt__buf_get16(b);\r\n   else if (b0 == 29)               return stbtt__buf_get32(b);\r\n   STBTT_assert(0);\r\n   return 0;\r\n}\r\n\r\nstatic void stbtt__cff_skip_operand(stbtt__buf *b) {\r\n   int v, b0 = stbtt__buf_peek8(b);\r\n   STBTT_assert(b0 >= 28);\r\n   if (b0 == 30) {\r\n      stbtt__buf_skip(b, 1);\r\n      while (b->cursor < b->size) {\r\n         v = stbtt__buf_get8(b);\r\n         if ((v & 0xF) == 0xF || (v >> 4) == 0xF)\r\n            break;\r\n      }\r\n   } else {\r\n      stbtt__cff_int(b);\r\n   }\r\n}\r\n\r\nstatic stbtt__buf stbtt__dict_get(stbtt__buf *b, int key)\r\n{\r\n   stbtt__buf_seek(b, 0);\r\n   while (b->cursor < b->size) {\r\n      int start = b->cursor, end, op;\r\n      while (stbtt__buf_peek8(b) >= 28)\r\n         stbtt__cff_skip_operand(b);\r\n      end = b->cursor;\r\n      op = stbtt__buf_get8(b);\r\n      if (op == 12)  op = stbtt__buf_get8(b) | 0x100;\r\n      if (op == key) return stbtt__buf_range(b, start, end-start);\r\n   }\r\n   return stbtt__buf_range(b, 0, 0);\r\n}\r\n\r\nstatic void stbtt__dict_get_ints(stbtt__buf *b, int key, int outcount, stbtt_uint32 *out)\r\n{\r\n   int i;\r\n   stbtt__buf operands = stbtt__dict_get(b, key);\r\n   for (i = 0; i < outcount && operands.cursor < operands.size; i++)\r\n      out[i] = stbtt__cff_int(&operands);\r\n}\r\n\r\nstatic int stbtt__cff_index_count(stbtt__buf *b)\r\n{\r\n   stbtt__buf_seek(b, 0);\r\n   return stbtt__buf_get16(b);\r\n}\r\n\r\nstatic stbtt__buf stbtt__cff_index_get(stbtt__buf b, int i)\r\n{\r\n   int count, offsize, start, end;\r\n   stbtt__buf_seek(&b, 0);\r\n   count = stbtt__buf_get16(&b);\r\n   offsize = stbtt__buf_get8(&b);\r\n   STBTT_assert(i >= 0 && i < count);\r\n   STBTT_assert(offsize >= 1 && offsize <= 4);\r\n   stbtt__buf_skip(&b, i*offsize);\r\n   start = stbtt__buf_get(&b, offsize);\r\n   end = stbtt__buf_get(&b, offsize);\r\n   return stbtt__buf_range(&b, 2+(count+1)*offsize+start, end - start);\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////\r\n//\r\n// accessors to parse data from file\r\n//\r\n\r\n// on platforms that don't allow misaligned reads, if we want to allow\r\n// truetype fonts that aren't padded to alignment, define ALLOW_UNALIGNED_TRUETYPE\r\n\r\n#define ttBYTE(p)     (* (stbtt_uint8 *) (p))\r\n#define ttCHAR(p)     (* (stbtt_int8 *) (p))\r\n#define ttFixed(p)    ttLONG(p)\r\n\r\nstatic stbtt_uint16 ttUSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; }\r\nstatic stbtt_int16 ttSHORT(stbtt_uint8 *p)   { return p[0]*256 + p[1]; }\r\nstatic stbtt_uint32 ttULONG(stbtt_uint8 *p)  { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; }\r\nstatic stbtt_int32 ttLONG(stbtt_uint8 *p)    { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; }\r\n\r\n#define stbtt_tag4(p,c0,c1,c2,c3) ((p)[0] == (c0) && (p)[1] == (c1) && (p)[2] == (c2) && (p)[3] == (c3))\r\n#define stbtt_tag(p,str)           stbtt_tag4(p,str[0],str[1],str[2],str[3])\r\n\r\nstatic int stbtt__isfont(stbtt_uint8 *font)\r\n{\r\n   // check the version number\r\n   if (stbtt_tag4(font, '1',0,0,0))  return 1; // TrueType 1\r\n   if (stbtt_tag(font, \"typ1\"))   return 1; // TrueType with type 1 font -- we don't support this!\r\n   if (stbtt_tag(font, \"OTTO\"))   return 1; // OpenType with CFF\r\n   if (stbtt_tag4(font, 0,1,0,0)) return 1; // OpenType 1.0\r\n   if (stbtt_tag(font, \"true\"))   return 1; // Apple specification for TrueType fonts\r\n   return 0;\r\n}\r\n\r\n// @OPTIMIZE: binary search\r\nstatic stbtt_uint32 stbtt__find_table(stbtt_uint8 *data, stbtt_uint32 fontstart, const char *tag)\r\n{\r\n   stbtt_int32 num_tables = ttUSHORT(data+fontstart+4);\r\n   stbtt_uint32 tabledir = fontstart + 12;\r\n   stbtt_int32 i;\r\n   for (i=0; i < num_tables; ++i) {\r\n      stbtt_uint32 loc = tabledir + 16*i;\r\n      if (stbtt_tag(data+loc+0, tag))\r\n         return ttULONG(data+loc+8);\r\n   }\r\n   return 0;\r\n}\r\n\r\nstatic int stbtt_GetFontOffsetForIndex_internal(unsigned char *font_collection, int index)\r\n{\r\n   // if it's just a font, there's only one valid index\r\n   if (stbtt__isfont(font_collection))\r\n      return index == 0 ? 0 : -1;\r\n\r\n   // check if it's a TTC\r\n   if (stbtt_tag(font_collection, \"ttcf\")) {\r\n      // version 1?\r\n      if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) {\r\n         stbtt_int32 n = ttLONG(font_collection+8);\r\n         if (index >= n)\r\n            return -1;\r\n         return ttULONG(font_collection+12+index*4);\r\n      }\r\n   }\r\n   return -1;\r\n}\r\n\r\nstatic int stbtt_GetNumberOfFonts_internal(unsigned char *font_collection)\r\n{\r\n   // if it's just a font, there's only one valid font\r\n   if (stbtt__isfont(font_collection))\r\n      return 1;\r\n\r\n   // check if it's a TTC\r\n   if (stbtt_tag(font_collection, \"ttcf\")) {\r\n      // version 1?\r\n      if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) {\r\n         return ttLONG(font_collection+8);\r\n      }\r\n   }\r\n   return 0;\r\n}\r\n\r\nstatic stbtt__buf stbtt__get_subrs(stbtt__buf cff, stbtt__buf fontdict)\r\n{\r\n   stbtt_uint32 subrsoff = 0, private_loc[2] = { 0, 0 };\r\n   stbtt__buf pdict;\r\n   stbtt__dict_get_ints(&fontdict, 18, 2, private_loc);\r\n   if (!private_loc[1] || !private_loc[0]) return stbtt__new_buf(NULL, 0);\r\n   pdict = stbtt__buf_range(&cff, private_loc[1], private_loc[0]);\r\n   stbtt__dict_get_ints(&pdict, 19, 1, &subrsoff);\r\n   if (!subrsoff) return stbtt__new_buf(NULL, 0);\r\n   stbtt__buf_seek(&cff, private_loc[1]+subrsoff);\r\n   return stbtt__cff_get_index(&cff);\r\n}\r\n\r\nstatic int stbtt_InitFont_internal(stbtt_fontinfo *info, unsigned char *data, int fontstart)\r\n{\r\n   stbtt_uint32 cmap, t;\r\n   stbtt_int32 i,numTables;\r\n\r\n   info->data = data;\r\n   info->fontstart = fontstart;\r\n   info->cff = stbtt__new_buf(NULL, 0);\r\n\r\n   cmap = stbtt__find_table(data, fontstart, \"cmap\");       // required\r\n   info->loca = stbtt__find_table(data, fontstart, \"loca\"); // required\r\n   info->head = stbtt__find_table(data, fontstart, \"head\"); // required\r\n   info->glyf = stbtt__find_table(data, fontstart, \"glyf\"); // required\r\n   info->hhea = stbtt__find_table(data, fontstart, \"hhea\"); // required\r\n   info->hmtx = stbtt__find_table(data, fontstart, \"hmtx\"); // required\r\n   info->kern = stbtt__find_table(data, fontstart, \"kern\"); // not required\r\n   info->gpos = stbtt__find_table(data, fontstart, \"GPOS\"); // not required\r\n\r\n   if (!cmap || !info->head || !info->hhea || !info->hmtx)\r\n      return 0;\r\n   if (info->glyf) {\r\n      // required for truetype\r\n      if (!info->loca) return 0;\r\n   } else {\r\n      // initialization for CFF / Type2 fonts (OTF)\r\n      stbtt__buf b, topdict, topdictidx;\r\n      stbtt_uint32 cstype = 2, charstrings = 0, fdarrayoff = 0, fdselectoff = 0;\r\n      stbtt_uint32 cff;\r\n\r\n      cff = stbtt__find_table(data, fontstart, \"CFF \");\r\n      if (!cff) return 0;\r\n\r\n      info->fontdicts = stbtt__new_buf(NULL, 0);\r\n      info->fdselect = stbtt__new_buf(NULL, 0);\r\n\r\n      // @TODO this should use size from table (not 512MB)\r\n      info->cff = stbtt__new_buf(data+cff, 512*1024*1024);\r\n      b = info->cff;\r\n\r\n      // read the header\r\n      stbtt__buf_skip(&b, 2);\r\n      stbtt__buf_seek(&b, stbtt__buf_get8(&b)); // hdrsize\r\n\r\n      // @TODO the name INDEX could list multiple fonts,\r\n      // but we just use the first one.\r\n      stbtt__cff_get_index(&b);  // name INDEX\r\n      topdictidx = stbtt__cff_get_index(&b);\r\n      topdict = stbtt__cff_index_get(topdictidx, 0);\r\n      stbtt__cff_get_index(&b);  // string INDEX\r\n      info->gsubrs = stbtt__cff_get_index(&b);\r\n\r\n      stbtt__dict_get_ints(&topdict, 17, 1, &charstrings);\r\n      stbtt__dict_get_ints(&topdict, 0x100 | 6, 1, &cstype);\r\n      stbtt__dict_get_ints(&topdict, 0x100 | 36, 1, &fdarrayoff);\r\n      stbtt__dict_get_ints(&topdict, 0x100 | 37, 1, &fdselectoff);\r\n      info->subrs = stbtt__get_subrs(b, topdict);\r\n\r\n      // we only support Type 2 charstrings\r\n      if (cstype != 2) return 0;\r\n      if (charstrings == 0) return 0;\r\n\r\n      if (fdarrayoff) {\r\n         // looks like a CID font\r\n         if (!fdselectoff) return 0;\r\n         stbtt__buf_seek(&b, fdarrayoff);\r\n         info->fontdicts = stbtt__cff_get_index(&b);\r\n         info->fdselect = stbtt__buf_range(&b, fdselectoff, b.size-fdselectoff);\r\n      }\r\n\r\n      stbtt__buf_seek(&b, charstrings);\r\n      info->charstrings = stbtt__cff_get_index(&b);\r\n   }\r\n\r\n   t = stbtt__find_table(data, fontstart, \"maxp\");\r\n   if (t)\r\n      info->numGlyphs = ttUSHORT(data+t+4);\r\n   else\r\n      info->numGlyphs = 0xffff;\r\n\r\n   // find a cmap encoding table we understand *now* to avoid searching\r\n   // later. (todo: could make this installable)\r\n   // the same regardless of glyph.\r\n   numTables = ttUSHORT(data + cmap + 2);\r\n   info->index_map = 0;\r\n   for (i=0; i < numTables; ++i) {\r\n      stbtt_uint32 encoding_record = cmap + 4 + 8 * i;\r\n      // find an encoding we understand:\r\n      switch(ttUSHORT(data+encoding_record)) {\r\n         case STBTT_PLATFORM_ID_MICROSOFT:\r\n            switch (ttUSHORT(data+encoding_record+2)) {\r\n               case STBTT_MS_EID_UNICODE_BMP:\r\n               case STBTT_MS_EID_UNICODE_FULL:\r\n                  // MS/Unicode\r\n                  info->index_map = cmap + ttULONG(data+encoding_record+4);\r\n                  break;\r\n            }\r\n            break;\r\n        case STBTT_PLATFORM_ID_UNICODE:\r\n            // Mac/iOS has these\r\n            // all the encodingIDs are unicode, so we don't bother to check it\r\n            info->index_map = cmap + ttULONG(data+encoding_record+4);\r\n            break;\r\n      }\r\n   }\r\n   if (info->index_map == 0)\r\n      return 0;\r\n\r\n   info->indexToLocFormat = ttUSHORT(data+info->head + 50);\r\n   return 1;\r\n}\r\n\r\nSTBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint)\r\n{\r\n   stbtt_uint8 *data = info->data;\r\n   stbtt_uint32 index_map = info->index_map;\r\n\r\n   stbtt_uint16 format = ttUSHORT(data + index_map + 0);\r\n   if (format == 0) { // apple byte encoding\r\n      stbtt_int32 bytes = ttUSHORT(data + index_map + 2);\r\n      if (unicode_codepoint < bytes-6)\r\n         return ttBYTE(data + index_map + 6 + unicode_codepoint);\r\n      return 0;\r\n   } else if (format == 6) {\r\n      stbtt_uint32 first = ttUSHORT(data + index_map + 6);\r\n      stbtt_uint32 count = ttUSHORT(data + index_map + 8);\r\n      if ((stbtt_uint32) unicode_codepoint >= first && (stbtt_uint32) unicode_codepoint < first+count)\r\n         return ttUSHORT(data + index_map + 10 + (unicode_codepoint - first)*2);\r\n      return 0;\r\n   } else if (format == 2) {\r\n      STBTT_assert(0); // @TODO: high-byte mapping for japanese/chinese/korean\r\n      return 0;\r\n   } else if (format == 4) { // standard mapping for windows fonts: binary search collection of ranges\r\n      stbtt_uint16 segcount = ttUSHORT(data+index_map+6) >> 1;\r\n      stbtt_uint16 searchRange = ttUSHORT(data+index_map+8) >> 1;\r\n      stbtt_uint16 entrySelector = ttUSHORT(data+index_map+10);\r\n      stbtt_uint16 rangeShift = ttUSHORT(data+index_map+12) >> 1;\r\n\r\n      // do a binary search of the segments\r\n      stbtt_uint32 endCount = index_map + 14;\r\n      stbtt_uint32 search = endCount;\r\n\r\n      if (unicode_codepoint > 0xffff)\r\n         return 0;\r\n\r\n      // they lie from endCount .. endCount + segCount\r\n      // but searchRange is the nearest power of two, so...\r\n      if (unicode_codepoint >= ttUSHORT(data + search + rangeShift*2))\r\n         search += rangeShift*2;\r\n\r\n      // now decrement to bias correctly to find smallest\r\n      search -= 2;\r\n      while (entrySelector) {\r\n         stbtt_uint16 end;\r\n         searchRange >>= 1;\r\n         end = ttUSHORT(data + search + searchRange*2);\r\n         if (unicode_codepoint > end)\r\n            search += searchRange*2;\r\n         --entrySelector;\r\n      }\r\n      search += 2;\r\n\r\n      {\r\n         stbtt_uint16 offset, start;\r\n         stbtt_uint16 item = (stbtt_uint16) ((search - endCount) >> 1);\r\n\r\n         STBTT_assert(unicode_codepoint <= ttUSHORT(data + endCount + 2*item));\r\n         start = ttUSHORT(data + index_map + 14 + segcount*2 + 2 + 2*item);\r\n         if (unicode_codepoint < start)\r\n            return 0;\r\n\r\n         offset = ttUSHORT(data + index_map + 14 + segcount*6 + 2 + 2*item);\r\n         if (offset == 0)\r\n            return (stbtt_uint16) (unicode_codepoint + ttSHORT(data + index_map + 14 + segcount*4 + 2 + 2*item));\r\n\r\n         return ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item);\r\n      }\r\n   } else if (format == 12 || format == 13) {\r\n      stbtt_uint32 ngroups = ttULONG(data+index_map+12);\r\n      stbtt_int32 low,high;\r\n      low = 0; high = (stbtt_int32)ngroups;\r\n      // Binary search the right group.\r\n      while (low < high) {\r\n         stbtt_int32 mid = low + ((high-low) >> 1); // rounds down, so low <= mid < high\r\n         stbtt_uint32 start_char = ttULONG(data+index_map+16+mid*12);\r\n         stbtt_uint32 end_char = ttULONG(data+index_map+16+mid*12+4);\r\n         if ((stbtt_uint32) unicode_codepoint < start_char)\r\n            high = mid;\r\n         else if ((stbtt_uint32) unicode_codepoint > end_char)\r\n            low = mid+1;\r\n         else {\r\n            stbtt_uint32 start_glyph = ttULONG(data+index_map+16+mid*12+8);\r\n            if (format == 12)\r\n               return start_glyph + unicode_codepoint-start_char;\r\n            else // format == 13\r\n               return start_glyph;\r\n         }\r\n      }\r\n      return 0; // not found\r\n   }\r\n   // @TODO\r\n   STBTT_assert(0);\r\n   return 0;\r\n}\r\n\r\nSTBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices)\r\n{\r\n   return stbtt_GetGlyphShape(info, stbtt_FindGlyphIndex(info, unicode_codepoint), vertices);\r\n}\r\n\r\nstatic void stbtt_setvertex(stbtt_vertex *v, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy)\r\n{\r\n   v->type = type;\r\n   v->x = (stbtt_int16) x;\r\n   v->y = (stbtt_int16) y;\r\n   v->cx = (stbtt_int16) cx;\r\n   v->cy = (stbtt_int16) cy;\r\n}\r\n\r\nstatic int stbtt__GetGlyfOffset(const stbtt_fontinfo *info, int glyph_index)\r\n{\r\n   int g1,g2;\r\n\r\n   STBTT_assert(!info->cff.size);\r\n\r\n   if (glyph_index >= info->numGlyphs) return -1; // glyph index out of range\r\n   if (info->indexToLocFormat >= 2)    return -1; // unknown index->glyph map format\r\n\r\n   if (info->indexToLocFormat == 0) {\r\n      g1 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2) * 2;\r\n      g2 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2 + 2) * 2;\r\n   } else {\r\n      g1 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4);\r\n      g2 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4 + 4);\r\n   }\r\n\r\n   return g1==g2 ? -1 : g1; // if length is 0, return -1\r\n}\r\n\r\nstatic int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1);\r\n\r\nSTBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1)\r\n{\r\n   if (info->cff.size) {\r\n      stbtt__GetGlyphInfoT2(info, glyph_index, x0, y0, x1, y1);\r\n   } else {\r\n      int g = stbtt__GetGlyfOffset(info, glyph_index);\r\n      if (g < 0) return 0;\r\n\r\n      if (x0) *x0 = ttSHORT(info->data + g + 2);\r\n      if (y0) *y0 = ttSHORT(info->data + g + 4);\r\n      if (x1) *x1 = ttSHORT(info->data + g + 6);\r\n      if (y1) *y1 = ttSHORT(info->data + g + 8);\r\n   }\r\n   return 1;\r\n}\r\n\r\nSTBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1)\r\n{\r\n   return stbtt_GetGlyphBox(info, stbtt_FindGlyphIndex(info,codepoint), x0,y0,x1,y1);\r\n}\r\n\r\nSTBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index)\r\n{\r\n   stbtt_int16 numberOfContours;\r\n   int g;\r\n   if (info->cff.size)\r\n      return stbtt__GetGlyphInfoT2(info, glyph_index, NULL, NULL, NULL, NULL) == 0;\r\n   g = stbtt__GetGlyfOffset(info, glyph_index);\r\n   if (g < 0) return 1;\r\n   numberOfContours = ttSHORT(info->data + g);\r\n   return numberOfContours == 0;\r\n}\r\n\r\nstatic int stbtt__close_shape(stbtt_vertex *vertices, int num_vertices, int was_off, int start_off,\r\n    stbtt_int32 sx, stbtt_int32 sy, stbtt_int32 scx, stbtt_int32 scy, stbtt_int32 cx, stbtt_int32 cy)\r\n{\r\n   if (start_off) {\r\n      if (was_off)\r\n         stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+scx)>>1, (cy+scy)>>1, cx,cy);\r\n      stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, sx,sy,scx,scy);\r\n   } else {\r\n      if (was_off)\r\n         stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve,sx,sy,cx,cy);\r\n      else\r\n         stbtt_setvertex(&vertices[num_vertices++], STBTT_vline,sx,sy,0,0);\r\n   }\r\n   return num_vertices;\r\n}\r\n\r\nstatic int stbtt__GetGlyphShapeTT(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices)\r\n{\r\n   stbtt_int16 numberOfContours;\r\n   stbtt_uint8 *endPtsOfContours;\r\n   stbtt_uint8 *data = info->data;\r\n   stbtt_vertex *vertices=0;\r\n   int num_vertices=0;\r\n   int g = stbtt__GetGlyfOffset(info, glyph_index);\r\n\r\n   *pvertices = NULL;\r\n\r\n   if (g < 0) return 0;\r\n\r\n   numberOfContours = ttSHORT(data + g);\r\n\r\n   if (numberOfContours > 0) {\r\n      stbtt_uint8 flags=0,flagcount;\r\n      stbtt_int32 ins, i,j=0,m,n, next_move, was_off=0, off, start_off=0;\r\n      stbtt_int32 x,y,cx,cy,sx,sy, scx,scy;\r\n      stbtt_uint8 *points;\r\n      endPtsOfContours = (data + g + 10);\r\n      ins = ttUSHORT(data + g + 10 + numberOfContours * 2);\r\n      points = data + g + 10 + numberOfContours * 2 + 2 + ins;\r\n\r\n      n = 1+ttUSHORT(endPtsOfContours + numberOfContours*2-2);\r\n\r\n      m = n + 2*numberOfContours;  // a loose bound on how many vertices we might need\r\n      vertices = (stbtt_vertex *) STBTT_malloc(m * sizeof(vertices[0]), info->userdata);\r\n      if (vertices == 0)\r\n         return 0;\r\n\r\n      next_move = 0;\r\n      flagcount=0;\r\n\r\n      // in first pass, we load uninterpreted data into the allocated array\r\n      // above, shifted to the end of the array so we won't overwrite it when\r\n      // we create our final data starting from the front\r\n\r\n      off = m - n; // starting offset for uninterpreted data, regardless of how m ends up being calculated\r\n\r\n      // first load flags\r\n\r\n      for (i=0; i < n; ++i) {\r\n         if (flagcount == 0) {\r\n            flags = *points++;\r\n            if (flags & 8)\r\n               flagcount = *points++;\r\n         } else\r\n            --flagcount;\r\n         vertices[off+i].type = flags;\r\n      }\r\n\r\n      // now load x coordinates\r\n      x=0;\r\n      for (i=0; i < n; ++i) {\r\n         flags = vertices[off+i].type;\r\n         if (flags & 2) {\r\n            stbtt_int16 dx = *points++;\r\n            x += (flags & 16) ? dx : -dx; // ???\r\n         } else {\r\n            if (!(flags & 16)) {\r\n               x = x + (stbtt_int16) (points[0]*256 + points[1]);\r\n               points += 2;\r\n            }\r\n         }\r\n         vertices[off+i].x = (stbtt_int16) x;\r\n      }\r\n\r\n      // now load y coordinates\r\n      y=0;\r\n      for (i=0; i < n; ++i) {\r\n         flags = vertices[off+i].type;\r\n         if (flags & 4) {\r\n            stbtt_int16 dy = *points++;\r\n            y += (flags & 32) ? dy : -dy; // ???\r\n         } else {\r\n            if (!(flags & 32)) {\r\n               y = y + (stbtt_int16) (points[0]*256 + points[1]);\r\n               points += 2;\r\n            }\r\n         }\r\n         vertices[off+i].y = (stbtt_int16) y;\r\n      }\r\n\r\n      // now convert them to our format\r\n      num_vertices=0;\r\n      sx = sy = cx = cy = scx = scy = 0;\r\n      for (i=0; i < n; ++i) {\r\n         flags = vertices[off+i].type;\r\n         x     = (stbtt_int16) vertices[off+i].x;\r\n         y     = (stbtt_int16) vertices[off+i].y;\r\n\r\n         if (next_move == i) {\r\n            if (i != 0)\r\n               num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy);\r\n\r\n            // now start the new one\r\n            start_off = !(flags & 1);\r\n            if (start_off) {\r\n               // if we start off with an off-curve point, then when we need to find a point on the curve\r\n               // where we can start, and we need to save some state for when we wraparound.\r\n               scx = x;\r\n               scy = y;\r\n               if (!(vertices[off+i+1].type & 1)) {\r\n                  // next point is also a curve point, so interpolate an on-point curve\r\n                  sx = (x + (stbtt_int32) vertices[off+i+1].x) >> 1;\r\n                  sy = (y + (stbtt_int32) vertices[off+i+1].y) >> 1;\r\n               } else {\r\n                  // otherwise just use the next point as our start point\r\n                  sx = (stbtt_int32) vertices[off+i+1].x;\r\n                  sy = (stbtt_int32) vertices[off+i+1].y;\r\n                  ++i; // we're using point i+1 as the starting point, so skip it\r\n               }\r\n            } else {\r\n               sx = x;\r\n               sy = y;\r\n            }\r\n            stbtt_setvertex(&vertices[num_vertices++], STBTT_vmove,sx,sy,0,0);\r\n            was_off = 0;\r\n            next_move = 1 + ttUSHORT(endPtsOfContours+j*2);\r\n            ++j;\r\n         } else {\r\n            if (!(flags & 1)) { // if it's a curve\r\n               if (was_off) // two off-curve control points in a row means interpolate an on-curve midpoint\r\n                  stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+x)>>1, (cy+y)>>1, cx, cy);\r\n               cx = x;\r\n               cy = y;\r\n               was_off = 1;\r\n            } else {\r\n               if (was_off)\r\n                  stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, x,y, cx, cy);\r\n               else\r\n                  stbtt_setvertex(&vertices[num_vertices++], STBTT_vline, x,y,0,0);\r\n               was_off = 0;\r\n            }\r\n         }\r\n      }\r\n      num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy);\r\n   } else if (numberOfContours == -1) {\r\n      // Compound shapes.\r\n      int more = 1;\r\n      stbtt_uint8 *comp = data + g + 10;\r\n      num_vertices = 0;\r\n      vertices = 0;\r\n      while (more) {\r\n         stbtt_uint16 flags, gidx;\r\n         int comp_num_verts = 0, i;\r\n         stbtt_vertex *comp_verts = 0, *tmp = 0;\r\n         float mtx[6] = {1,0,0,1,0,0}, m, n;\r\n\r\n         flags = ttSHORT(comp); comp+=2;\r\n         gidx = ttSHORT(comp); comp+=2;\r\n\r\n         if (flags & 2) { // XY values\r\n            if (flags & 1) { // shorts\r\n               mtx[4] = ttSHORT(comp); comp+=2;\r\n               mtx[5] = ttSHORT(comp); comp+=2;\r\n            } else {\r\n               mtx[4] = ttCHAR(comp); comp+=1;\r\n               mtx[5] = ttCHAR(comp); comp+=1;\r\n            }\r\n         }\r\n         else {\r\n            // @TODO handle matching point\r\n            STBTT_assert(0);\r\n         }\r\n         if (flags & (1<<3)) { // WE_HAVE_A_SCALE\r\n            mtx[0] = mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;\r\n            mtx[1] = mtx[2] = 0;\r\n         } else if (flags & (1<<6)) { // WE_HAVE_AN_X_AND_YSCALE\r\n            mtx[0] = ttSHORT(comp)/16384.0f; comp+=2;\r\n            mtx[1] = mtx[2] = 0;\r\n            mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;\r\n         } else if (flags & (1<<7)) { // WE_HAVE_A_TWO_BY_TWO\r\n            mtx[0] = ttSHORT(comp)/16384.0f; comp+=2;\r\n            mtx[1] = ttSHORT(comp)/16384.0f; comp+=2;\r\n            mtx[2] = ttSHORT(comp)/16384.0f; comp+=2;\r\n            mtx[3] = ttSHORT(comp)/16384.0f; comp+=2;\r\n         }\r\n\r\n         // Find transformation scales.\r\n         m = (float) STBTT_sqrt(mtx[0]*mtx[0] + mtx[1]*mtx[1]);\r\n         n = (float) STBTT_sqrt(mtx[2]*mtx[2] + mtx[3]*mtx[3]);\r\n\r\n         // Get indexed glyph.\r\n         comp_num_verts = stbtt_GetGlyphShape(info, gidx, &comp_verts);\r\n         if (comp_num_verts > 0) {\r\n            // Transform vertices.\r\n            for (i = 0; i < comp_num_verts; ++i) {\r\n               stbtt_vertex* v = &comp_verts[i];\r\n               stbtt_vertex_type x,y;\r\n               x=v->x; y=v->y;\r\n               v->x = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4]));\r\n               v->y = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5]));\r\n               x=v->cx; y=v->cy;\r\n               v->cx = (stbtt_vertex_type)(m * (mtx[0]*x + mtx[2]*y + mtx[4]));\r\n               v->cy = (stbtt_vertex_type)(n * (mtx[1]*x + mtx[3]*y + mtx[5]));\r\n            }\r\n            // Append vertices.\r\n            tmp = (stbtt_vertex*)STBTT_malloc((num_vertices+comp_num_verts)*sizeof(stbtt_vertex), info->userdata);\r\n            if (!tmp) {\r\n               if (vertices) STBTT_free(vertices, info->userdata);\r\n               if (comp_verts) STBTT_free(comp_verts, info->userdata);\r\n               return 0;\r\n            }\r\n            if (num_vertices > 0) STBTT_memcpy(tmp, vertices, num_vertices*sizeof(stbtt_vertex)); //-V595\r\n            STBTT_memcpy(tmp+num_vertices, comp_verts, comp_num_verts*sizeof(stbtt_vertex));\r\n            if (vertices) STBTT_free(vertices, info->userdata);\r\n            vertices = tmp;\r\n            STBTT_free(comp_verts, info->userdata);\r\n            num_vertices += comp_num_verts;\r\n         }\r\n         // More components ?\r\n         more = flags & (1<<5);\r\n      }\r\n   } else if (numberOfContours < 0) {\r\n      // @TODO other compound variations?\r\n      STBTT_assert(0);\r\n   } else {\r\n      // numberOfCounters == 0, do nothing\r\n   }\r\n\r\n   *pvertices = vertices;\r\n   return num_vertices;\r\n}\r\n\r\ntypedef struct\r\n{\r\n   int bounds;\r\n   int started;\r\n   float first_x, first_y;\r\n   float x, y;\r\n   stbtt_int32 min_x, max_x, min_y, max_y;\r\n\r\n   stbtt_vertex *pvertices;\r\n   int num_vertices;\r\n} stbtt__csctx;\r\n\r\n#define STBTT__CSCTX_INIT(bounds) {bounds,0, 0,0, 0,0, 0,0,0,0, NULL, 0}\r\n\r\nstatic void stbtt__track_vertex(stbtt__csctx *c, stbtt_int32 x, stbtt_int32 y)\r\n{\r\n   if (x > c->max_x || !c->started) c->max_x = x;\r\n   if (y > c->max_y || !c->started) c->max_y = y;\r\n   if (x < c->min_x || !c->started) c->min_x = x;\r\n   if (y < c->min_y || !c->started) c->min_y = y;\r\n   c->started = 1;\r\n}\r\n\r\nstatic void stbtt__csctx_v(stbtt__csctx *c, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy, stbtt_int32 cx1, stbtt_int32 cy1)\r\n{\r\n   if (c->bounds) {\r\n      stbtt__track_vertex(c, x, y);\r\n      if (type == STBTT_vcubic) {\r\n         stbtt__track_vertex(c, cx, cy);\r\n         stbtt__track_vertex(c, cx1, cy1);\r\n      }\r\n   } else {\r\n      stbtt_setvertex(&c->pvertices[c->num_vertices], type, x, y, cx, cy);\r\n      c->pvertices[c->num_vertices].cx1 = (stbtt_int16) cx1;\r\n      c->pvertices[c->num_vertices].cy1 = (stbtt_int16) cy1;\r\n   }\r\n   c->num_vertices++;\r\n}\r\n\r\nstatic void stbtt__csctx_close_shape(stbtt__csctx *ctx)\r\n{\r\n   if (ctx->first_x != ctx->x || ctx->first_y != ctx->y)\r\n      stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->first_x, (int)ctx->first_y, 0, 0, 0, 0);\r\n}\r\n\r\nstatic void stbtt__csctx_rmove_to(stbtt__csctx *ctx, float dx, float dy)\r\n{\r\n   stbtt__csctx_close_shape(ctx);\r\n   ctx->first_x = ctx->x = ctx->x + dx;\r\n   ctx->first_y = ctx->y = ctx->y + dy;\r\n   stbtt__csctx_v(ctx, STBTT_vmove, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0);\r\n}\r\n\r\nstatic void stbtt__csctx_rline_to(stbtt__csctx *ctx, float dx, float dy)\r\n{\r\n   ctx->x += dx;\r\n   ctx->y += dy;\r\n   stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0);\r\n}\r\n\r\nstatic void stbtt__csctx_rccurve_to(stbtt__csctx *ctx, float dx1, float dy1, float dx2, float dy2, float dx3, float dy3)\r\n{\r\n   float cx1 = ctx->x + dx1;\r\n   float cy1 = ctx->y + dy1;\r\n   float cx2 = cx1 + dx2;\r\n   float cy2 = cy1 + dy2;\r\n   ctx->x = cx2 + dx3;\r\n   ctx->y = cy2 + dy3;\r\n   stbtt__csctx_v(ctx, STBTT_vcubic, (int)ctx->x, (int)ctx->y, (int)cx1, (int)cy1, (int)cx2, (int)cy2);\r\n}\r\n\r\nstatic stbtt__buf stbtt__get_subr(stbtt__buf idx, int n)\r\n{\r\n   int count = stbtt__cff_index_count(&idx);\r\n   int bias = 107;\r\n   if (count >= 33900)\r\n      bias = 32768;\r\n   else if (count >= 1240)\r\n      bias = 1131;\r\n   n += bias;\r\n   if (n < 0 || n >= count)\r\n      return stbtt__new_buf(NULL, 0);\r\n   return stbtt__cff_index_get(idx, n);\r\n}\r\n\r\nstatic stbtt__buf stbtt__cid_get_glyph_subrs(const stbtt_fontinfo *info, int glyph_index)\r\n{\r\n   stbtt__buf fdselect = info->fdselect;\r\n   int nranges, start, end, v, fmt, fdselector = -1, i;\r\n\r\n   stbtt__buf_seek(&fdselect, 0);\r\n   fmt = stbtt__buf_get8(&fdselect);\r\n   if (fmt == 0) {\r\n      // untested\r\n      stbtt__buf_skip(&fdselect, glyph_index);\r\n      fdselector = stbtt__buf_get8(&fdselect);\r\n   } else if (fmt == 3) {\r\n      nranges = stbtt__buf_get16(&fdselect);\r\n      start = stbtt__buf_get16(&fdselect);\r\n      for (i = 0; i < nranges; i++) {\r\n         v = stbtt__buf_get8(&fdselect);\r\n         end = stbtt__buf_get16(&fdselect);\r\n         if (glyph_index >= start && glyph_index < end) {\r\n            fdselector = v;\r\n            break;\r\n         }\r\n         start = end;\r\n      }\r\n   }\r\n   if (fdselector == -1) stbtt__new_buf(NULL, 0);\r\n   return stbtt__get_subrs(info->cff, stbtt__cff_index_get(info->fontdicts, fdselector));\r\n}\r\n\r\nstatic int stbtt__run_charstring(const stbtt_fontinfo *info, int glyph_index, stbtt__csctx *c)\r\n{\r\n   int in_header = 1, maskbits = 0, subr_stack_height = 0, sp = 0, v, i, b0;\r\n   int has_subrs = 0, clear_stack;\r\n   float s[48];\r\n   stbtt__buf subr_stack[10], subrs = info->subrs, b;\r\n   float f;\r\n\r\n#define STBTT__CSERR(s) (0)\r\n\r\n   // this currently ignores the initial width value, which isn't needed if we have hmtx\r\n   b = stbtt__cff_index_get(info->charstrings, glyph_index);\r\n   while (b.cursor < b.size) {\r\n      i = 0;\r\n      clear_stack = 1;\r\n      b0 = stbtt__buf_get8(&b);\r\n      switch (b0) {\r\n      // @TODO implement hinting\r\n      case 0x13: // hintmask\r\n      case 0x14: // cntrmask\r\n         if (in_header)\r\n            maskbits += (sp / 2); // implicit \"vstem\"\r\n         in_header = 0;\r\n         stbtt__buf_skip(&b, (maskbits + 7) / 8);\r\n         break;\r\n\r\n      case 0x01: // hstem\r\n      case 0x03: // vstem\r\n      case 0x12: // hstemhm\r\n      case 0x17: // vstemhm\r\n         maskbits += (sp / 2);\r\n         break;\r\n\r\n      case 0x15: // rmoveto\r\n         in_header = 0;\r\n         if (sp < 2) return STBTT__CSERR(\"rmoveto stack\");\r\n         stbtt__csctx_rmove_to(c, s[sp-2], s[sp-1]);\r\n         break;\r\n      case 0x04: // vmoveto\r\n         in_header = 0;\r\n         if (sp < 1) return STBTT__CSERR(\"vmoveto stack\");\r\n         stbtt__csctx_rmove_to(c, 0, s[sp-1]);\r\n         break;\r\n      case 0x16: // hmoveto\r\n         in_header = 0;\r\n         if (sp < 1) return STBTT__CSERR(\"hmoveto stack\");\r\n         stbtt__csctx_rmove_to(c, s[sp-1], 0);\r\n         break;\r\n\r\n      case 0x05: // rlineto\r\n         if (sp < 2) return STBTT__CSERR(\"rlineto stack\");\r\n         for (; i + 1 < sp; i += 2)\r\n            stbtt__csctx_rline_to(c, s[i], s[i+1]);\r\n         break;\r\n\r\n      // hlineto/vlineto and vhcurveto/hvcurveto alternate horizontal and vertical\r\n      // starting from a different place.\r\n\r\n      case 0x07: // vlineto\r\n         if (sp < 1) return STBTT__CSERR(\"vlineto stack\");\r\n         goto vlineto;\r\n      case 0x06: // hlineto\r\n         if (sp < 1) return STBTT__CSERR(\"hlineto stack\");\r\n         for (;;) {\r\n            if (i >= sp) break;\r\n            stbtt__csctx_rline_to(c, s[i], 0);\r\n            i++;\r\n      vlineto:\r\n            if (i >= sp) break;\r\n            stbtt__csctx_rline_to(c, 0, s[i]);\r\n            i++;\r\n         }\r\n         break;\r\n\r\n      case 0x1F: // hvcurveto\r\n         if (sp < 4) return STBTT__CSERR(\"hvcurveto stack\");\r\n         goto hvcurveto;\r\n      case 0x1E: // vhcurveto\r\n         if (sp < 4) return STBTT__CSERR(\"vhcurveto stack\");\r\n         for (;;) {\r\n            if (i + 3 >= sp) break;\r\n            stbtt__csctx_rccurve_to(c, 0, s[i], s[i+1], s[i+2], s[i+3], (sp - i == 5) ? s[i + 4] : 0.0f);\r\n            i += 4;\r\n      hvcurveto:\r\n            if (i + 3 >= sp) break;\r\n            stbtt__csctx_rccurve_to(c, s[i], 0, s[i+1], s[i+2], (sp - i == 5) ? s[i+4] : 0.0f, s[i+3]);\r\n            i += 4;\r\n         }\r\n         break;\r\n\r\n      case 0x08: // rrcurveto\r\n         if (sp < 6) return STBTT__CSERR(\"rcurveline stack\");\r\n         for (; i + 5 < sp; i += 6)\r\n            stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]);\r\n         break;\r\n\r\n      case 0x18: // rcurveline\r\n         if (sp < 8) return STBTT__CSERR(\"rcurveline stack\");\r\n         for (; i + 5 < sp - 2; i += 6)\r\n            stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]);\r\n         if (i + 1 >= sp) return STBTT__CSERR(\"rcurveline stack\");\r\n         stbtt__csctx_rline_to(c, s[i], s[i+1]);\r\n         break;\r\n\r\n      case 0x19: // rlinecurve\r\n         if (sp < 8) return STBTT__CSERR(\"rlinecurve stack\");\r\n         for (; i + 1 < sp - 6; i += 2)\r\n            stbtt__csctx_rline_to(c, s[i], s[i+1]);\r\n         if (i + 5 >= sp) return STBTT__CSERR(\"rlinecurve stack\");\r\n         stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]);\r\n         break;\r\n\r\n      case 0x1A: // vvcurveto\r\n      case 0x1B: // hhcurveto\r\n         if (sp < 4) return STBTT__CSERR(\"(vv|hh)curveto stack\");\r\n         f = 0.0;\r\n         if (sp & 1) { f = s[i]; i++; }\r\n         for (; i + 3 < sp; i += 4) {\r\n            if (b0 == 0x1B)\r\n               stbtt__csctx_rccurve_to(c, s[i], f, s[i+1], s[i+2], s[i+3], 0.0);\r\n            else\r\n               stbtt__csctx_rccurve_to(c, f, s[i], s[i+1], s[i+2], 0.0, s[i+3]);\r\n            f = 0.0;\r\n         }\r\n         break;\r\n\r\n      case 0x0A: // callsubr\r\n         if (!has_subrs) {\r\n            if (info->fdselect.size)\r\n               subrs = stbtt__cid_get_glyph_subrs(info, glyph_index);\r\n            has_subrs = 1;\r\n         }\r\n         // fallthrough\r\n      case 0x1D: // callgsubr\r\n         if (sp < 1) return STBTT__CSERR(\"call(g|)subr stack\");\r\n         v = (int) s[--sp];\r\n         if (subr_stack_height >= 10) return STBTT__CSERR(\"recursion limit\");\r\n         subr_stack[subr_stack_height++] = b;\r\n         b = stbtt__get_subr(b0 == 0x0A ? subrs : info->gsubrs, v);\r\n         if (b.size == 0) return STBTT__CSERR(\"subr not found\");\r\n         b.cursor = 0;\r\n         clear_stack = 0;\r\n         break;\r\n\r\n      case 0x0B: // return\r\n         if (subr_stack_height <= 0) return STBTT__CSERR(\"return outside subr\");\r\n         b = subr_stack[--subr_stack_height];\r\n         clear_stack = 0;\r\n         break;\r\n\r\n      case 0x0E: // endchar\r\n         stbtt__csctx_close_shape(c);\r\n         return 1;\r\n\r\n      case 0x0C: { // two-byte escape\r\n         float dx1, dx2, dx3, dx4, dx5, dx6, dy1, dy2, dy3, dy4, dy5, dy6;\r\n         float dx, dy;\r\n         int b1 = stbtt__buf_get8(&b);\r\n         switch (b1) {\r\n         // @TODO These \"flex\" implementations ignore the flex-depth and resolution,\r\n         // and always draw beziers.\r\n         case 0x22: // hflex\r\n            if (sp < 7) return STBTT__CSERR(\"hflex stack\");\r\n            dx1 = s[0];\r\n            dx2 = s[1];\r\n            dy2 = s[2];\r\n            dx3 = s[3];\r\n            dx4 = s[4];\r\n            dx5 = s[5];\r\n            dx6 = s[6];\r\n            stbtt__csctx_rccurve_to(c, dx1, 0, dx2, dy2, dx3, 0);\r\n            stbtt__csctx_rccurve_to(c, dx4, 0, dx5, -dy2, dx6, 0);\r\n            break;\r\n\r\n         case 0x23: // flex\r\n            if (sp < 13) return STBTT__CSERR(\"flex stack\");\r\n            dx1 = s[0];\r\n            dy1 = s[1];\r\n            dx2 = s[2];\r\n            dy2 = s[3];\r\n            dx3 = s[4];\r\n            dy3 = s[5];\r\n            dx4 = s[6];\r\n            dy4 = s[7];\r\n            dx5 = s[8];\r\n            dy5 = s[9];\r\n            dx6 = s[10];\r\n            dy6 = s[11];\r\n            //fd is s[12]\r\n            stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3);\r\n            stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6);\r\n            break;\r\n\r\n         case 0x24: // hflex1\r\n            if (sp < 9) return STBTT__CSERR(\"hflex1 stack\");\r\n            dx1 = s[0];\r\n            dy1 = s[1];\r\n            dx2 = s[2];\r\n            dy2 = s[3];\r\n            dx3 = s[4];\r\n            dx4 = s[5];\r\n            dx5 = s[6];\r\n            dy5 = s[7];\r\n            dx6 = s[8];\r\n            stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, 0);\r\n            stbtt__csctx_rccurve_to(c, dx4, 0, dx5, dy5, dx6, -(dy1+dy2+dy5));\r\n            break;\r\n\r\n         case 0x25: // flex1\r\n            if (sp < 11) return STBTT__CSERR(\"flex1 stack\");\r\n            dx1 = s[0];\r\n            dy1 = s[1];\r\n            dx2 = s[2];\r\n            dy2 = s[3];\r\n            dx3 = s[4];\r\n            dy3 = s[5];\r\n            dx4 = s[6];\r\n            dy4 = s[7];\r\n            dx5 = s[8];\r\n            dy5 = s[9];\r\n            dx6 = dy6 = s[10];\r\n            dx = dx1+dx2+dx3+dx4+dx5;\r\n            dy = dy1+dy2+dy3+dy4+dy5;\r\n            if (STBTT_fabs(dx) > STBTT_fabs(dy))\r\n               dy6 = -dy;\r\n            else\r\n               dx6 = -dx;\r\n            stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3);\r\n            stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6);\r\n            break;\r\n\r\n         default:\r\n            return STBTT__CSERR(\"unimplemented\");\r\n         }\r\n      } break;\r\n\r\n      default:\r\n         if (b0 != 255 && b0 != 28 && (b0 < 32 || b0 > 254)) //-V560\r\n            return STBTT__CSERR(\"reserved operator\");\r\n\r\n         // push immediate\r\n         if (b0 == 255) {\r\n            f = (float)(stbtt_int32)stbtt__buf_get32(&b) / 0x10000;\r\n         } else {\r\n            stbtt__buf_skip(&b, -1);\r\n            f = (float)(stbtt_int16)stbtt__cff_int(&b);\r\n         }\r\n         if (sp >= 48) return STBTT__CSERR(\"push stack overflow\");\r\n         s[sp++] = f;\r\n         clear_stack = 0;\r\n         break;\r\n      }\r\n      if (clear_stack) sp = 0;\r\n   }\r\n   return STBTT__CSERR(\"no endchar\");\r\n\r\n#undef STBTT__CSERR\r\n}\r\n\r\nstatic int stbtt__GetGlyphShapeT2(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices)\r\n{\r\n   // runs the charstring twice, once to count and once to output (to avoid realloc)\r\n   stbtt__csctx count_ctx = STBTT__CSCTX_INIT(1);\r\n   stbtt__csctx output_ctx = STBTT__CSCTX_INIT(0);\r\n   if (stbtt__run_charstring(info, glyph_index, &count_ctx)) {\r\n      *pvertices = (stbtt_vertex*)STBTT_malloc(count_ctx.num_vertices*sizeof(stbtt_vertex), info->userdata);\r\n      output_ctx.pvertices = *pvertices;\r\n      if (stbtt__run_charstring(info, glyph_index, &output_ctx)) {\r\n         STBTT_assert(output_ctx.num_vertices == count_ctx.num_vertices);\r\n         return output_ctx.num_vertices;\r\n      }\r\n   }\r\n   *pvertices = NULL;\r\n   return 0;\r\n}\r\n\r\nstatic int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1)\r\n{\r\n   stbtt__csctx c = STBTT__CSCTX_INIT(1);\r\n   int r = stbtt__run_charstring(info, glyph_index, &c);\r\n   if (x0)  *x0 = r ? c.min_x : 0;\r\n   if (y0)  *y0 = r ? c.min_y : 0;\r\n   if (x1)  *x1 = r ? c.max_x : 0;\r\n   if (y1)  *y1 = r ? c.max_y : 0;\r\n   return r ? c.num_vertices : 0;\r\n}\r\n\r\nSTBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices)\r\n{\r\n   if (!info->cff.size)\r\n      return stbtt__GetGlyphShapeTT(info, glyph_index, pvertices);\r\n   else\r\n      return stbtt__GetGlyphShapeT2(info, glyph_index, pvertices);\r\n}\r\n\r\nSTBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing)\r\n{\r\n   stbtt_uint16 numOfLongHorMetrics = ttUSHORT(info->data+info->hhea + 34);\r\n   if (glyph_index < numOfLongHorMetrics) {\r\n      if (advanceWidth)     *advanceWidth    = ttSHORT(info->data + info->hmtx + 4*glyph_index);\r\n      if (leftSideBearing)  *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*glyph_index + 2);\r\n   } else {\r\n      if (advanceWidth)     *advanceWidth    = ttSHORT(info->data + info->hmtx + 4*(numOfLongHorMetrics-1));\r\n      if (leftSideBearing)  *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*numOfLongHorMetrics + 2*(glyph_index - numOfLongHorMetrics));\r\n   }\r\n}\r\n\r\nstatic int  stbtt__GetGlyphKernInfoAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2)\r\n{\r\n   stbtt_uint8 *data = info->data + info->kern;\r\n   stbtt_uint32 needle, straw;\r\n   int l, r, m;\r\n\r\n   // we only look at the first table. it must be 'horizontal' and format 0.\r\n   if (!info->kern)\r\n      return 0;\r\n   if (ttUSHORT(data+2) < 1) // number of tables, need at least 1\r\n      return 0;\r\n   if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format\r\n      return 0;\r\n\r\n   l = 0;\r\n   r = ttUSHORT(data+10) - 1;\r\n   needle = glyph1 << 16 | glyph2;\r\n   while (l <= r) {\r\n      m = (l + r) >> 1;\r\n      straw = ttULONG(data+18+(m*6)); // note: unaligned read\r\n      if (needle < straw)\r\n         r = m - 1;\r\n      else if (needle > straw)\r\n         l = m + 1;\r\n      else\r\n         return ttSHORT(data+22+(m*6));\r\n   }\r\n   return 0;\r\n}\r\n\r\nstatic stbtt_int32  stbtt__GetCoverageIndex(stbtt_uint8 *coverageTable, int glyph)\r\n{\r\n    stbtt_uint16 coverageFormat = ttUSHORT(coverageTable);\r\n    switch(coverageFormat) {\r\n        case 1: {\r\n            stbtt_uint16 glyphCount = ttUSHORT(coverageTable + 2);\r\n\r\n            // Binary search.\r\n            stbtt_int32 l=0, r=glyphCount-1, m;\r\n            int straw, needle=glyph;\r\n            while (l <= r) {\r\n                stbtt_uint8 *glyphArray = coverageTable + 4;\r\n                stbtt_uint16 glyphID;\r\n                m = (l + r) >> 1;\r\n                glyphID = ttUSHORT(glyphArray + 2 * m);\r\n                straw = glyphID;\r\n                if (needle < straw)\r\n                    r = m - 1;\r\n                else if (needle > straw)\r\n                    l = m + 1;\r\n                else {\r\n                     return m;\r\n                }\r\n            }\r\n        } break;\r\n\r\n        case 2: {\r\n            stbtt_uint16 rangeCount = ttUSHORT(coverageTable + 2);\r\n            stbtt_uint8 *rangeArray = coverageTable + 4;\r\n\r\n            // Binary search.\r\n            stbtt_int32 l=0, r=rangeCount-1, m;\r\n            int strawStart, strawEnd, needle=glyph;\r\n            while (l <= r) {\r\n                stbtt_uint8 *rangeRecord;\r\n                m = (l + r) >> 1;\r\n                rangeRecord = rangeArray + 6 * m;\r\n                strawStart = ttUSHORT(rangeRecord);\r\n                strawEnd = ttUSHORT(rangeRecord + 2);\r\n                if (needle < strawStart)\r\n                    r = m - 1;\r\n                else if (needle > strawEnd)\r\n                    l = m + 1;\r\n                else {\r\n                    stbtt_uint16 startCoverageIndex = ttUSHORT(rangeRecord + 4);\r\n                    return startCoverageIndex + glyph - strawStart;\r\n                }\r\n            }\r\n        } break;\r\n\r\n        default: {\r\n            // There are no other cases.\r\n            STBTT_assert(0);\r\n        } break;\r\n    }\r\n\r\n    return -1;\r\n}\r\n\r\nstatic stbtt_int32  stbtt__GetGlyphClass(stbtt_uint8 *classDefTable, int glyph)\r\n{\r\n    stbtt_uint16 classDefFormat = ttUSHORT(classDefTable);\r\n    switch(classDefFormat)\r\n    {\r\n        case 1: {\r\n            stbtt_uint16 startGlyphID = ttUSHORT(classDefTable + 2);\r\n            stbtt_uint16 glyphCount = ttUSHORT(classDefTable + 4);\r\n            stbtt_uint8 *classDef1ValueArray = classDefTable + 6;\r\n\r\n            if (glyph >= startGlyphID && glyph < startGlyphID + glyphCount)\r\n                return (stbtt_int32)ttUSHORT(classDef1ValueArray + 2 * (glyph - startGlyphID));\r\n\r\n            // [DEAR IMGUI] Commented to fix static analyzer warning\r\n            //classDefTable = classDef1ValueArray + 2 * glyphCount;\r\n        } break;\r\n\r\n        case 2: {\r\n            stbtt_uint16 classRangeCount = ttUSHORT(classDefTable + 2);\r\n            stbtt_uint8 *classRangeRecords = classDefTable + 4;\r\n\r\n            // Binary search.\r\n            stbtt_int32 l=0, r=classRangeCount-1, m;\r\n            int strawStart, strawEnd, needle=glyph;\r\n            while (l <= r) {\r\n                stbtt_uint8 *classRangeRecord;\r\n                m = (l + r) >> 1;\r\n                classRangeRecord = classRangeRecords + 6 * m;\r\n                strawStart = ttUSHORT(classRangeRecord);\r\n                strawEnd = ttUSHORT(classRangeRecord + 2);\r\n                if (needle < strawStart)\r\n                    r = m - 1;\r\n                else if (needle > strawEnd)\r\n                    l = m + 1;\r\n                else\r\n                    return (stbtt_int32)ttUSHORT(classRangeRecord + 4);\r\n            }\r\n\r\n            // [DEAR IMGUI] Commented to fix static analyzer warning\r\n            //classDefTable = classRangeRecords + 6 * classRangeCount;\r\n        } break;\r\n\r\n        default: {\r\n            // There are no other cases.\r\n            STBTT_assert(0);\r\n        } break;\r\n    }\r\n\r\n    return -1;\r\n}\r\n\r\n// Define to STBTT_assert(x) if you want to break on unimplemented formats.\r\n#define STBTT_GPOS_TODO_assert(x)\r\n\r\nstatic stbtt_int32  stbtt__GetGlyphGPOSInfoAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2)\r\n{\r\n    stbtt_uint16 lookupListOffset;\r\n    stbtt_uint8 *lookupList;\r\n    stbtt_uint16 lookupCount;\r\n    stbtt_uint8 *data;\r\n    stbtt_int32 i;\r\n\r\n    if (!info->gpos) return 0;\r\n\r\n    data = info->data + info->gpos;\r\n\r\n    if (ttUSHORT(data+0) != 1) return 0; // Major version 1\r\n    if (ttUSHORT(data+2) != 0) return 0; // Minor version 0\r\n\r\n    lookupListOffset = ttUSHORT(data+8);\r\n    lookupList = data + lookupListOffset;\r\n    lookupCount = ttUSHORT(lookupList);\r\n\r\n    for (i=0; i<lookupCount; ++i) {\r\n        stbtt_uint16 lookupOffset = ttUSHORT(lookupList + 2 + 2 * i);\r\n        stbtt_uint8 *lookupTable = lookupList + lookupOffset;\r\n\r\n        stbtt_uint16 lookupType = ttUSHORT(lookupTable);\r\n        stbtt_uint16 subTableCount = ttUSHORT(lookupTable + 4);\r\n        stbtt_uint8 *subTableOffsets = lookupTable + 6;\r\n        switch(lookupType) {\r\n            case 2: { // Pair Adjustment Positioning Subtable\r\n                stbtt_int32 sti;\r\n                for (sti=0; sti<subTableCount; sti++) {\r\n                    stbtt_uint16 subtableOffset = ttUSHORT(subTableOffsets + 2 * sti);\r\n                    stbtt_uint8 *table = lookupTable + subtableOffset;\r\n                    stbtt_uint16 posFormat = ttUSHORT(table);\r\n                    stbtt_uint16 coverageOffset = ttUSHORT(table + 2);\r\n                    stbtt_int32 coverageIndex = stbtt__GetCoverageIndex(table + coverageOffset, glyph1);\r\n                    if (coverageIndex == -1) continue;\r\n\r\n                    switch (posFormat) {\r\n                        case 1: {\r\n                            stbtt_int32 l, r, m;\r\n                            int straw, needle;\r\n                            stbtt_uint16 valueFormat1 = ttUSHORT(table + 4);\r\n                            stbtt_uint16 valueFormat2 = ttUSHORT(table + 6);\r\n                            stbtt_int32 valueRecordPairSizeInBytes = 2;\r\n                            stbtt_uint16 pairSetCount = ttUSHORT(table + 8);\r\n                            stbtt_uint16 pairPosOffset = ttUSHORT(table + 10 + 2 * coverageIndex);\r\n                            stbtt_uint8 *pairValueTable = table + pairPosOffset;\r\n                            stbtt_uint16 pairValueCount = ttUSHORT(pairValueTable);\r\n                            stbtt_uint8 *pairValueArray = pairValueTable + 2;\r\n                            // TODO: Support more formats.\r\n                            STBTT_GPOS_TODO_assert(valueFormat1 == 4);\r\n                            if (valueFormat1 != 4) return 0;\r\n                            STBTT_GPOS_TODO_assert(valueFormat2 == 0);\r\n                            if (valueFormat2 != 0) return 0;\r\n\r\n                            STBTT_assert(coverageIndex < pairSetCount);\r\n                            STBTT__NOTUSED(pairSetCount);\r\n\r\n                            needle=glyph2;\r\n                            r=pairValueCount-1;\r\n                            l=0;\r\n\r\n                            // Binary search.\r\n                            while (l <= r) {\r\n                                stbtt_uint16 secondGlyph;\r\n                                stbtt_uint8 *pairValue;\r\n                                m = (l + r) >> 1;\r\n                                pairValue = pairValueArray + (2 + valueRecordPairSizeInBytes) * m;\r\n                                secondGlyph = ttUSHORT(pairValue);\r\n                                straw = secondGlyph;\r\n                                if (needle < straw)\r\n                                    r = m - 1;\r\n                                else if (needle > straw)\r\n                                    l = m + 1;\r\n                                else {\r\n                                    stbtt_int16 xAdvance = ttSHORT(pairValue + 2);\r\n                                    return xAdvance;\r\n                                }\r\n                            }\r\n                        } break;\r\n\r\n                        case 2: {\r\n                            stbtt_uint16 valueFormat1 = ttUSHORT(table + 4);\r\n                            stbtt_uint16 valueFormat2 = ttUSHORT(table + 6);\r\n\r\n                            stbtt_uint16 classDef1Offset = ttUSHORT(table + 8);\r\n                            stbtt_uint16 classDef2Offset = ttUSHORT(table + 10);\r\n                            int glyph1class = stbtt__GetGlyphClass(table + classDef1Offset, glyph1);\r\n                            int glyph2class = stbtt__GetGlyphClass(table + classDef2Offset, glyph2);\r\n\r\n                            stbtt_uint16 class1Count = ttUSHORT(table + 12);\r\n                            stbtt_uint16 class2Count = ttUSHORT(table + 14);\r\n                            STBTT_assert(glyph1class < class1Count);\r\n                            STBTT_assert(glyph2class < class2Count);\r\n\r\n                            // TODO: Support more formats.\r\n                            STBTT_GPOS_TODO_assert(valueFormat1 == 4);\r\n                            if (valueFormat1 != 4) return 0;\r\n                            STBTT_GPOS_TODO_assert(valueFormat2 == 0);\r\n                            if (valueFormat2 != 0) return 0;\r\n\r\n                            if (glyph1class >= 0 && glyph1class < class1Count && glyph2class >= 0 && glyph2class < class2Count) {\r\n                                stbtt_uint8 *class1Records = table + 16;\r\n                                stbtt_uint8 *class2Records = class1Records + 2 * (glyph1class * class2Count);\r\n                                stbtt_int16 xAdvance = ttSHORT(class2Records + 2 * glyph2class);\r\n                                return xAdvance;\r\n                            }\r\n                        } break;\r\n\r\n                        default: {\r\n                            // There are no other cases.\r\n                            STBTT_assert(0);\r\n                            break;\r\n                        } // [DEAR IMGUI] removed ;\r\n                    }\r\n                }\r\n                break;\r\n            } // [DEAR IMGUI] removed ;\r\n\r\n            default:\r\n                // TODO: Implement other stuff.\r\n                break;\r\n        }\r\n    }\r\n\r\n    return 0;\r\n}\r\n\r\nSTBTT_DEF int  stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int g1, int g2)\r\n{\r\n   int xAdvance = 0;\r\n\r\n   if (info->gpos)\r\n      xAdvance += stbtt__GetGlyphGPOSInfoAdvance(info, g1, g2);\r\n\r\n   if (info->kern)\r\n      xAdvance += stbtt__GetGlyphKernInfoAdvance(info, g1, g2);\r\n\r\n   return xAdvance;\r\n}\r\n\r\nSTBTT_DEF int  stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2)\r\n{\r\n   if (!info->kern && !info->gpos) // if no kerning table, don't waste time looking up both codepoint->glyphs\r\n      return 0;\r\n   return stbtt_GetGlyphKernAdvance(info, stbtt_FindGlyphIndex(info,ch1), stbtt_FindGlyphIndex(info,ch2));\r\n}\r\n\r\nSTBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing)\r\n{\r\n   stbtt_GetGlyphHMetrics(info, stbtt_FindGlyphIndex(info,codepoint), advanceWidth, leftSideBearing);\r\n}\r\n\r\nSTBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap)\r\n{\r\n   if (ascent ) *ascent  = ttSHORT(info->data+info->hhea + 4);\r\n   if (descent) *descent = ttSHORT(info->data+info->hhea + 6);\r\n   if (lineGap) *lineGap = ttSHORT(info->data+info->hhea + 8);\r\n}\r\n\r\nSTBTT_DEF int  stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap)\r\n{\r\n   int tab = stbtt__find_table(info->data, info->fontstart, \"OS/2\");\r\n   if (!tab)\r\n      return 0;\r\n   if (typoAscent ) *typoAscent  = ttSHORT(info->data+tab + 68);\r\n   if (typoDescent) *typoDescent = ttSHORT(info->data+tab + 70);\r\n   if (typoLineGap) *typoLineGap = ttSHORT(info->data+tab + 72);\r\n   return 1;\r\n}\r\n\r\nSTBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1)\r\n{\r\n   *x0 = ttSHORT(info->data + info->head + 36);\r\n   *y0 = ttSHORT(info->data + info->head + 38);\r\n   *x1 = ttSHORT(info->data + info->head + 40);\r\n   *y1 = ttSHORT(info->data + info->head + 42);\r\n}\r\n\r\nSTBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float height)\r\n{\r\n   int fheight = ttSHORT(info->data + info->hhea + 4) - ttSHORT(info->data + info->hhea + 6);\r\n   return (float) height / fheight;\r\n}\r\n\r\nSTBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels)\r\n{\r\n   int unitsPerEm = ttUSHORT(info->data + info->head + 18);\r\n   return pixels / unitsPerEm;\r\n}\r\n\r\nSTBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *v)\r\n{\r\n   STBTT_free(v, info->userdata);\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//\r\n// antialiasing software rasterizer\r\n//\r\n\r\nSTBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1)\r\n{\r\n   int x0=0,y0=0,x1,y1; // =0 suppresses compiler warning\r\n   if (!stbtt_GetGlyphBox(font, glyph, &x0,&y0,&x1,&y1)) {\r\n      // e.g. space character\r\n      if (ix0) *ix0 = 0;\r\n      if (iy0) *iy0 = 0;\r\n      if (ix1) *ix1 = 0;\r\n      if (iy1) *iy1 = 0;\r\n   } else {\r\n      // move to integral bboxes (treating pixels as little squares, what pixels get touched)?\r\n      if (ix0) *ix0 = STBTT_ifloor( x0 * scale_x + shift_x);\r\n      if (iy0) *iy0 = STBTT_ifloor(-y1 * scale_y + shift_y);\r\n      if (ix1) *ix1 = STBTT_iceil ( x1 * scale_x + shift_x);\r\n      if (iy1) *iy1 = STBTT_iceil (-y0 * scale_y + shift_y);\r\n   }\r\n}\r\n\r\nSTBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1)\r\n{\r\n   stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y,0.0f,0.0f, ix0, iy0, ix1, iy1);\r\n}\r\n\r\nSTBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1)\r\n{\r\n   stbtt_GetGlyphBitmapBoxSubpixel(font, stbtt_FindGlyphIndex(font,codepoint), scale_x, scale_y,shift_x,shift_y, ix0,iy0,ix1,iy1);\r\n}\r\n\r\nSTBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1)\r\n{\r\n   stbtt_GetCodepointBitmapBoxSubpixel(font, codepoint, scale_x, scale_y,0.0f,0.0f, ix0,iy0,ix1,iy1);\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//\r\n//  Rasterizer\r\n\r\ntypedef struct stbtt__hheap_chunk\r\n{\r\n   struct stbtt__hheap_chunk *next;\r\n} stbtt__hheap_chunk;\r\n\r\ntypedef struct stbtt__hheap\r\n{\r\n   struct stbtt__hheap_chunk *head;\r\n   void   *first_free;\r\n   int    num_remaining_in_head_chunk;\r\n} stbtt__hheap;\r\n\r\nstatic void *stbtt__hheap_alloc(stbtt__hheap *hh, size_t size, void *userdata)\r\n{\r\n   if (hh->first_free) {\r\n      void *p = hh->first_free;\r\n      hh->first_free = * (void **) p;\r\n      return p;\r\n   } else {\r\n      if (hh->num_remaining_in_head_chunk == 0) {\r\n         int count = (size < 32 ? 2000 : size < 128 ? 800 : 100);\r\n         stbtt__hheap_chunk *c = (stbtt__hheap_chunk *) STBTT_malloc(sizeof(stbtt__hheap_chunk) + size * count, userdata);\r\n         if (c == NULL)\r\n            return NULL;\r\n         c->next = hh->head;\r\n         hh->head = c;\r\n         hh->num_remaining_in_head_chunk = count;\r\n      }\r\n      --hh->num_remaining_in_head_chunk;\r\n      return (char *) (hh->head) + sizeof(stbtt__hheap_chunk) + size * hh->num_remaining_in_head_chunk;\r\n   }\r\n}\r\n\r\nstatic void stbtt__hheap_free(stbtt__hheap *hh, void *p)\r\n{\r\n   *(void **) p = hh->first_free;\r\n   hh->first_free = p;\r\n}\r\n\r\nstatic void stbtt__hheap_cleanup(stbtt__hheap *hh, void *userdata)\r\n{\r\n   stbtt__hheap_chunk *c = hh->head;\r\n   while (c) {\r\n      stbtt__hheap_chunk *n = c->next;\r\n      STBTT_free(c, userdata);\r\n      c = n;\r\n   }\r\n}\r\n\r\ntypedef struct stbtt__edge {\r\n   float x0,y0, x1,y1;\r\n   int invert;\r\n} stbtt__edge;\r\n\r\n\r\ntypedef struct stbtt__active_edge\r\n{\r\n   struct stbtt__active_edge *next;\r\n   #if STBTT_RASTERIZER_VERSION==1\r\n   int x,dx;\r\n   float ey;\r\n   int direction;\r\n   #elif STBTT_RASTERIZER_VERSION==2\r\n   float fx,fdx,fdy;\r\n   float direction;\r\n   float sy;\r\n   float ey;\r\n   #else\r\n   #error \"Unrecognized value of STBTT_RASTERIZER_VERSION\"\r\n   #endif\r\n} stbtt__active_edge;\r\n\r\n#if STBTT_RASTERIZER_VERSION == 1\r\n#define STBTT_FIXSHIFT   10\r\n#define STBTT_FIX        (1 << STBTT_FIXSHIFT)\r\n#define STBTT_FIXMASK    (STBTT_FIX-1)\r\n\r\nstatic stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata)\r\n{\r\n   stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata);\r\n   float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0);\r\n   STBTT_assert(z != NULL);\r\n   if (!z) return z;\r\n\r\n   // round dx down to avoid overshooting\r\n   if (dxdy < 0)\r\n      z->dx = -STBTT_ifloor(STBTT_FIX * -dxdy);\r\n   else\r\n      z->dx = STBTT_ifloor(STBTT_FIX * dxdy);\r\n\r\n   z->x = STBTT_ifloor(STBTT_FIX * e->x0 + z->dx * (start_point - e->y0)); // use z->dx so when we offset later it's by the same amount\r\n   z->x -= off_x * STBTT_FIX;\r\n\r\n   z->ey = e->y1;\r\n   z->next = 0;\r\n   z->direction = e->invert ? 1 : -1;\r\n   return z;\r\n}\r\n#elif STBTT_RASTERIZER_VERSION == 2\r\nstatic stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata)\r\n{\r\n   stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata);\r\n   float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0);\r\n   STBTT_assert(z != NULL);\r\n   //STBTT_assert(e->y0 <= start_point);\r\n   if (!z) return z;\r\n   z->fdx = dxdy;\r\n   z->fdy = dxdy != 0.0f ? (1.0f/dxdy) : 0.0f;\r\n   z->fx = e->x0 + dxdy * (start_point - e->y0);\r\n   z->fx -= off_x;\r\n   z->direction = e->invert ? 1.0f : -1.0f;\r\n   z->sy = e->y0;\r\n   z->ey = e->y1;\r\n   z->next = 0;\r\n   return z;\r\n}\r\n#else\r\n#error \"Unrecognized value of STBTT_RASTERIZER_VERSION\"\r\n#endif\r\n\r\n#if STBTT_RASTERIZER_VERSION == 1\r\n// note: this routine clips fills that extend off the edges... ideally this\r\n// wouldn't happen, but it could happen if the truetype glyph bounding boxes\r\n// are wrong, or if the user supplies a too-small bitmap\r\nstatic void stbtt__fill_active_edges(unsigned char *scanline, int len, stbtt__active_edge *e, int max_weight)\r\n{\r\n   // non-zero winding fill\r\n   int x0=0, w=0;\r\n\r\n   while (e) {\r\n      if (w == 0) {\r\n         // if we're currently at zero, we need to record the edge start point\r\n         x0 = e->x; w += e->direction;\r\n      } else {\r\n         int x1 = e->x; w += e->direction;\r\n         // if we went to zero, we need to draw\r\n         if (w == 0) {\r\n            int i = x0 >> STBTT_FIXSHIFT;\r\n            int j = x1 >> STBTT_FIXSHIFT;\r\n\r\n            if (i < len && j >= 0) {\r\n               if (i == j) {\r\n                  // x0,x1 are the same pixel, so compute combined coverage\r\n                  scanline[i] = scanline[i] + (stbtt_uint8) ((x1 - x0) * max_weight >> STBTT_FIXSHIFT);\r\n               } else {\r\n                  if (i >= 0) // add antialiasing for x0\r\n                     scanline[i] = scanline[i] + (stbtt_uint8) (((STBTT_FIX - (x0 & STBTT_FIXMASK)) * max_weight) >> STBTT_FIXSHIFT);\r\n                  else\r\n                     i = -1; // clip\r\n\r\n                  if (j < len) // add antialiasing for x1\r\n                     scanline[j] = scanline[j] + (stbtt_uint8) (((x1 & STBTT_FIXMASK) * max_weight) >> STBTT_FIXSHIFT);\r\n                  else\r\n                     j = len; // clip\r\n\r\n                  for (++i; i < j; ++i) // fill pixels between x0 and x1\r\n                     scanline[i] = scanline[i] + (stbtt_uint8) max_weight;\r\n               }\r\n            }\r\n         }\r\n      }\r\n\r\n      e = e->next;\r\n   }\r\n}\r\n\r\nstatic void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata)\r\n{\r\n   stbtt__hheap hh = { 0, 0, 0 };\r\n   stbtt__active_edge *active = NULL;\r\n   int y,j=0;\r\n   int max_weight = (255 / vsubsample);  // weight per vertical scanline\r\n   int s; // vertical subsample index\r\n   unsigned char scanline_data[512], *scanline;\r\n\r\n   if (result->w > 512)\r\n      scanline = (unsigned char *) STBTT_malloc(result->w, userdata);\r\n   else\r\n      scanline = scanline_data;\r\n\r\n   y = off_y * vsubsample;\r\n   e[n].y0 = (off_y + result->h) * (float) vsubsample + 1;\r\n\r\n   while (j < result->h) {\r\n      STBTT_memset(scanline, 0, result->w);\r\n      for (s=0; s < vsubsample; ++s) {\r\n         // find center of pixel for this scanline\r\n         float scan_y = y + 0.5f;\r\n         stbtt__active_edge **step = &active;\r\n\r\n         // update all active edges;\r\n         // remove all active edges that terminate before the center of this scanline\r\n         while (*step) {\r\n            stbtt__active_edge * z = *step;\r\n            if (z->ey <= scan_y) {\r\n               *step = z->next; // delete from list\r\n               STBTT_assert(z->direction);\r\n               z->direction = 0;\r\n               stbtt__hheap_free(&hh, z);\r\n            } else {\r\n               z->x += z->dx; // advance to position for current scanline\r\n               step = &((*step)->next); // advance through list\r\n            }\r\n         }\r\n\r\n         // resort the list if needed\r\n         for(;;) {\r\n            int changed=0;\r\n            step = &active;\r\n            while (*step && (*step)->next) {\r\n               if ((*step)->x > (*step)->next->x) {\r\n                  stbtt__active_edge *t = *step;\r\n                  stbtt__active_edge *q = t->next;\r\n\r\n                  t->next = q->next;\r\n                  q->next = t;\r\n                  *step = q;\r\n                  changed = 1;\r\n               }\r\n               step = &(*step)->next;\r\n            }\r\n            if (!changed) break;\r\n         }\r\n\r\n         // insert all edges that start before the center of this scanline -- omit ones that also end on this scanline\r\n         while (e->y0 <= scan_y) {\r\n            if (e->y1 > scan_y) {\r\n               stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y, userdata);\r\n               if (z != NULL) {\r\n                  // find insertion point\r\n                  if (active == NULL)\r\n                     active = z;\r\n                  else if (z->x < active->x) {\r\n                     // insert at front\r\n                     z->next = active;\r\n                     active = z;\r\n                  } else {\r\n                     // find thing to insert AFTER\r\n                     stbtt__active_edge *p = active;\r\n                     while (p->next && p->next->x < z->x)\r\n                        p = p->next;\r\n                     // at this point, p->next->x is NOT < z->x\r\n                     z->next = p->next;\r\n                     p->next = z;\r\n                  }\r\n               }\r\n            }\r\n            ++e;\r\n         }\r\n\r\n         // now process all active edges in XOR fashion\r\n         if (active)\r\n            stbtt__fill_active_edges(scanline, result->w, active, max_weight);\r\n\r\n         ++y;\r\n      }\r\n      STBTT_memcpy(result->pixels + j * result->stride, scanline, result->w);\r\n      ++j;\r\n   }\r\n\r\n   stbtt__hheap_cleanup(&hh, userdata);\r\n\r\n   if (scanline != scanline_data)\r\n      STBTT_free(scanline, userdata);\r\n}\r\n\r\n#elif STBTT_RASTERIZER_VERSION == 2\r\n\r\n// the edge passed in here does not cross the vertical line at x or the vertical line at x+1\r\n// (i.e. it has already been clipped to those)\r\nstatic void stbtt__handle_clipped_edge(float *scanline, int x, stbtt__active_edge *e, float x0, float y0, float x1, float y1)\r\n{\r\n   if (y0 == y1) return;\r\n   STBTT_assert(y0 < y1);\r\n   STBTT_assert(e->sy <= e->ey);\r\n   if (y0 > e->ey) return;\r\n   if (y1 < e->sy) return;\r\n   if (y0 < e->sy) {\r\n      x0 += (x1-x0) * (e->sy - y0) / (y1-y0);\r\n      y0 = e->sy;\r\n   }\r\n   if (y1 > e->ey) {\r\n      x1 += (x1-x0) * (e->ey - y1) / (y1-y0);\r\n      y1 = e->ey;\r\n   }\r\n\r\n   if (x0 == x)\r\n      STBTT_assert(x1 <= x+1);\r\n   else if (x0 == x+1)\r\n      STBTT_assert(x1 >= x);\r\n   else if (x0 <= x)\r\n      STBTT_assert(x1 <= x);\r\n   else if (x0 >= x+1)\r\n      STBTT_assert(x1 >= x+1);\r\n   else\r\n      STBTT_assert(x1 >= x && x1 <= x+1);\r\n\r\n   if (x0 <= x && x1 <= x)\r\n      scanline[x] += e->direction * (y1-y0);\r\n   else if (x0 >= x+1 && x1 >= x+1)\r\n      ;\r\n   else {\r\n      STBTT_assert(x0 >= x && x0 <= x+1 && x1 >= x && x1 <= x+1);\r\n      scanline[x] += e->direction * (y1-y0) * (1-((x0-x)+(x1-x))/2); // coverage = 1 - average x position\r\n   }\r\n}\r\n\r\nstatic void stbtt__fill_active_edges_new(float *scanline, float *scanline_fill, int len, stbtt__active_edge *e, float y_top)\r\n{\r\n   float y_bottom = y_top+1;\r\n\r\n   while (e) {\r\n      // brute force every pixel\r\n\r\n      // compute intersection points with top & bottom\r\n      STBTT_assert(e->ey >= y_top);\r\n\r\n      if (e->fdx == 0) {\r\n         float x0 = e->fx;\r\n         if (x0 < len) {\r\n            if (x0 >= 0) {\r\n               stbtt__handle_clipped_edge(scanline,(int) x0,e, x0,y_top, x0,y_bottom);\r\n               stbtt__handle_clipped_edge(scanline_fill-1,(int) x0+1,e, x0,y_top, x0,y_bottom);\r\n            } else {\r\n               stbtt__handle_clipped_edge(scanline_fill-1,0,e, x0,y_top, x0,y_bottom);\r\n            }\r\n         }\r\n      } else {\r\n         float x0 = e->fx;\r\n         float dx = e->fdx;\r\n         float xb = x0 + dx;\r\n         float x_top, x_bottom;\r\n         float sy0,sy1;\r\n         float dy = e->fdy;\r\n         STBTT_assert(e->sy <= y_bottom && e->ey >= y_top);\r\n\r\n         // compute endpoints of line segment clipped to this scanline (if the\r\n         // line segment starts on this scanline. x0 is the intersection of the\r\n         // line with y_top, but that may be off the line segment.\r\n         if (e->sy > y_top) {\r\n            x_top = x0 + dx * (e->sy - y_top);\r\n            sy0 = e->sy;\r\n         } else {\r\n            x_top = x0;\r\n            sy0 = y_top;\r\n         }\r\n         if (e->ey < y_bottom) {\r\n            x_bottom = x0 + dx * (e->ey - y_top);\r\n            sy1 = e->ey;\r\n         } else {\r\n            x_bottom = xb;\r\n            sy1 = y_bottom;\r\n         }\r\n\r\n         if (x_top >= 0 && x_bottom >= 0 && x_top < len && x_bottom < len) {\r\n            // from here on, we don't have to range check x values\r\n\r\n            if ((int) x_top == (int) x_bottom) {\r\n               float height;\r\n               // simple case, only spans one pixel\r\n               int x = (int) x_top;\r\n               height = sy1 - sy0;\r\n               STBTT_assert(x >= 0 && x < len);\r\n               scanline[x] += e->direction * (1-((x_top - x) + (x_bottom-x))/2)  * height;\r\n               scanline_fill[x] += e->direction * height; // everything right of this pixel is filled\r\n            } else {\r\n               int x,x1,x2;\r\n               float y_crossing, step, sign, area;\r\n               // covers 2+ pixels\r\n               if (x_top > x_bottom) {\r\n                  // flip scanline vertically; signed area is the same\r\n                  float t;\r\n                  sy0 = y_bottom - (sy0 - y_top);\r\n                  sy1 = y_bottom - (sy1 - y_top);\r\n                  t = sy0, sy0 = sy1, sy1 = t;\r\n                  t = x_bottom, x_bottom = x_top, x_top = t;\r\n                  dx = -dx;\r\n                  dy = -dy;\r\n                  t = x0, x0 = xb, xb = t;\r\n                  // [DEAR IMGUI] Fix static analyzer warning\r\n                  (void)dx; // [ImGui: fix static analyzer warning]\r\n               }\r\n\r\n               x1 = (int) x_top;\r\n               x2 = (int) x_bottom;\r\n               // compute intersection with y axis at x1+1\r\n               y_crossing = (x1+1 - x0) * dy + y_top;\r\n\r\n               sign = e->direction;\r\n               // area of the rectangle covered from y0..y_crossing\r\n               area = sign * (y_crossing-sy0);\r\n               // area of the triangle (x_top,y0), (x+1,y0), (x+1,y_crossing)\r\n               scanline[x1] += area * (1-((x_top - x1)+(x1+1-x1))/2);\r\n\r\n               step = sign * dy;\r\n               for (x = x1+1; x < x2; ++x) {\r\n                  scanline[x] += area + step/2;\r\n                  area += step;\r\n               }\r\n               y_crossing += dy * (x2 - (x1+1));\r\n\r\n               STBTT_assert(STBTT_fabs(area) <= 1.01f);\r\n\r\n               scanline[x2] += area + sign * (1-((x2-x2)+(x_bottom-x2))/2) * (sy1-y_crossing);\r\n\r\n               scanline_fill[x2] += sign * (sy1-sy0);\r\n            }\r\n         } else {\r\n            // if edge goes outside of box we're drawing, we require\r\n            // clipping logic. since this does not match the intended use\r\n            // of this library, we use a different, very slow brute\r\n            // force implementation\r\n            int x;\r\n            for (x=0; x < len; ++x) {\r\n               // cases:\r\n               //\r\n               // there can be up to two intersections with the pixel. any intersection\r\n               // with left or right edges can be handled by splitting into two (or three)\r\n               // regions. intersections with top & bottom do not necessitate case-wise logic.\r\n               //\r\n               // the old way of doing this found the intersections with the left & right edges,\r\n               // then used some simple logic to produce up to three segments in sorted order\r\n               // from top-to-bottom. however, this had a problem: if an x edge was epsilon\r\n               // across the x border, then the corresponding y position might not be distinct\r\n               // from the other y segment, and it might ignored as an empty segment. to avoid\r\n               // that, we need to explicitly produce segments based on x positions.\r\n\r\n               // rename variables to clearly-defined pairs\r\n               float y0 = y_top;\r\n               float x1 = (float) (x);\r\n               float x2 = (float) (x+1);\r\n               float x3 = xb;\r\n               float y3 = y_bottom;\r\n\r\n               // x = e->x + e->dx * (y-y_top)\r\n               // (y-y_top) = (x - e->x) / e->dx\r\n               // y = (x - e->x) / e->dx + y_top\r\n               float y1 = (x - x0) / dx + y_top;\r\n               float y2 = (x+1 - x0) / dx + y_top;\r\n\r\n               if (x0 < x1 && x3 > x2) {         // three segments descending down-right\r\n                  stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1);\r\n                  stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x2,y2);\r\n                  stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3);\r\n               } else if (x3 < x1 && x0 > x2) {  // three segments descending down-left\r\n                  stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2);\r\n                  stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x1,y1);\r\n                  stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3);\r\n               } else if (x0 < x1 && x3 > x1) {  // two segments across x, down-right\r\n                  stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1);\r\n                  stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3);\r\n               } else if (x3 < x1 && x0 > x1) {  // two segments across x, down-left\r\n                  stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1);\r\n                  stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3);\r\n               } else if (x0 < x2 && x3 > x2) {  // two segments across x+1, down-right\r\n                  stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2);\r\n                  stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3);\r\n               } else if (x3 < x2 && x0 > x2) {  // two segments across x+1, down-left\r\n                  stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2);\r\n                  stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3);\r\n               } else {  // one segment\r\n                  stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x3,y3);\r\n               }\r\n            }\r\n         }\r\n      }\r\n      e = e->next;\r\n   }\r\n}\r\n\r\n// directly AA rasterize edges w/o supersampling\r\nstatic void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata)\r\n{\r\n   stbtt__hheap hh = { 0, 0, 0 };\r\n   stbtt__active_edge *active = NULL;\r\n   int y,j=0, i;\r\n   float scanline_data[129], *scanline, *scanline2;\r\n\r\n   STBTT__NOTUSED(vsubsample);\r\n\r\n   if (result->w > 64)\r\n      scanline = (float *) STBTT_malloc((result->w*2+1) * sizeof(float), userdata);\r\n   else\r\n      scanline = scanline_data;\r\n\r\n   scanline2 = scanline + result->w;\r\n\r\n   y = off_y;\r\n   e[n].y0 = (float) (off_y + result->h) + 1;\r\n\r\n   while (j < result->h) {\r\n      // find center of pixel for this scanline\r\n      float scan_y_top    = y + 0.0f;\r\n      float scan_y_bottom = y + 1.0f;\r\n      stbtt__active_edge **step = &active;\r\n\r\n      STBTT_memset(scanline , 0, result->w*sizeof(scanline[0]));\r\n      STBTT_memset(scanline2, 0, (result->w+1)*sizeof(scanline[0]));\r\n\r\n      // update all active edges;\r\n      // remove all active edges that terminate before the top of this scanline\r\n      while (*step) {\r\n         stbtt__active_edge * z = *step;\r\n         if (z->ey <= scan_y_top) {\r\n            *step = z->next; // delete from list\r\n            STBTT_assert(z->direction);\r\n            z->direction = 0;\r\n            stbtt__hheap_free(&hh, z);\r\n         } else {\r\n            step = &((*step)->next); // advance through list\r\n         }\r\n      }\r\n\r\n      // insert all edges that start before the bottom of this scanline\r\n      while (e->y0 <= scan_y_bottom) {\r\n         if (e->y0 != e->y1) {\r\n            stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y_top, userdata);\r\n            if (z != NULL) {\r\n               if (j == 0 && off_y != 0) {\r\n                  if (z->ey < scan_y_top) {\r\n                     // this can happen due to subpixel positioning and some kind of fp rounding error i think\r\n                     z->ey = scan_y_top;\r\n                  }\r\n               }\r\n               STBTT_assert(z->ey >= scan_y_top); // if we get really unlucky a tiny bit of an edge can be out of bounds\r\n               // insert at front\r\n               z->next = active;\r\n               active = z;\r\n            }\r\n         }\r\n         ++e;\r\n      }\r\n\r\n      // now process all active edges\r\n      if (active)\r\n         stbtt__fill_active_edges_new(scanline, scanline2+1, result->w, active, scan_y_top);\r\n\r\n      {\r\n         float sum = 0;\r\n         for (i=0; i < result->w; ++i) {\r\n            float k;\r\n            int m;\r\n            sum += scanline2[i];\r\n            k = scanline[i] + sum;\r\n            k = (float) STBTT_fabs(k)*255 + 0.5f;\r\n            m = (int) k;\r\n            if (m > 255) m = 255;\r\n            result->pixels[j*result->stride + i] = (unsigned char) m;\r\n         }\r\n      }\r\n      // advance all the edges\r\n      step = &active;\r\n      while (*step) {\r\n         stbtt__active_edge *z = *step;\r\n         z->fx += z->fdx; // advance to position for current scanline\r\n         step = &((*step)->next); // advance through list\r\n      }\r\n\r\n      ++y;\r\n      ++j;\r\n   }\r\n\r\n   stbtt__hheap_cleanup(&hh, userdata);\r\n\r\n   if (scanline != scanline_data)\r\n      STBTT_free(scanline, userdata);\r\n}\r\n#else\r\n#error \"Unrecognized value of STBTT_RASTERIZER_VERSION\"\r\n#endif\r\n\r\n#define STBTT__COMPARE(a,b)  ((a)->y0 < (b)->y0)\r\n\r\nstatic void stbtt__sort_edges_ins_sort(stbtt__edge *p, int n)\r\n{\r\n   int i,j;\r\n   for (i=1; i < n; ++i) {\r\n      stbtt__edge t = p[i], *a = &t;\r\n      j = i;\r\n      while (j > 0) {\r\n         stbtt__edge *b = &p[j-1];\r\n         int c = STBTT__COMPARE(a,b);\r\n         if (!c) break;\r\n         p[j] = p[j-1];\r\n         --j;\r\n      }\r\n      if (i != j)\r\n         p[j] = t;\r\n   }\r\n}\r\n\r\nstatic void stbtt__sort_edges_quicksort(stbtt__edge *p, int n)\r\n{\r\n   /* threshold for transitioning to insertion sort */\r\n   while (n > 12) {\r\n      stbtt__edge t;\r\n      int c01,c12,c,m,i,j;\r\n\r\n      /* compute median of three */\r\n      m = n >> 1;\r\n      c01 = STBTT__COMPARE(&p[0],&p[m]);\r\n      c12 = STBTT__COMPARE(&p[m],&p[n-1]);\r\n      /* if 0 >= mid >= end, or 0 < mid < end, then use mid */\r\n      if (c01 != c12) {\r\n         /* otherwise, we'll need to swap something else to middle */\r\n         int z;\r\n         c = STBTT__COMPARE(&p[0],&p[n-1]);\r\n         /* 0>mid && mid<n:  0>n => n; 0<n => 0 */\r\n         /* 0<mid && mid>n:  0>n => 0; 0<n => n */\r\n         z = (c == c12) ? 0 : n-1;\r\n         t = p[z];\r\n         p[z] = p[m];\r\n         p[m] = t;\r\n      }\r\n      /* now p[m] is the median-of-three */\r\n      /* swap it to the beginning so it won't move around */\r\n      t = p[0];\r\n      p[0] = p[m];\r\n      p[m] = t;\r\n\r\n      /* partition loop */\r\n      i=1;\r\n      j=n-1;\r\n      for(;;) {\r\n         /* handling of equality is crucial here */\r\n         /* for sentinels & efficiency with duplicates */\r\n         for (;;++i) {\r\n            if (!STBTT__COMPARE(&p[i], &p[0])) break;\r\n         }\r\n         for (;;--j) {\r\n            if (!STBTT__COMPARE(&p[0], &p[j])) break;\r\n         }\r\n         /* make sure we haven't crossed */\r\n         if (i >= j) break;\r\n         t = p[i];\r\n         p[i] = p[j];\r\n         p[j] = t;\r\n\r\n         ++i;\r\n         --j;\r\n      }\r\n      /* recurse on smaller side, iterate on larger */\r\n      if (j < (n-i)) {\r\n         stbtt__sort_edges_quicksort(p,j);\r\n         p = p+i;\r\n         n = n-i;\r\n      } else {\r\n         stbtt__sort_edges_quicksort(p+i, n-i);\r\n         n = j;\r\n      }\r\n   }\r\n}\r\n\r\nstatic void stbtt__sort_edges(stbtt__edge *p, int n)\r\n{\r\n   stbtt__sort_edges_quicksort(p, n);\r\n   stbtt__sort_edges_ins_sort(p, n);\r\n}\r\n\r\ntypedef struct\r\n{\r\n   float x,y;\r\n} stbtt__point;\r\n\r\nstatic void stbtt__rasterize(stbtt__bitmap *result, stbtt__point *pts, int *wcount, int windings, float scale_x, float scale_y, float shift_x, float shift_y, int off_x, int off_y, int invert, void *userdata)\r\n{\r\n   float y_scale_inv = invert ? -scale_y : scale_y;\r\n   stbtt__edge *e;\r\n   int n,i,j,k,m;\r\n#if STBTT_RASTERIZER_VERSION == 1\r\n   int vsubsample = result->h < 8 ? 15 : 5;\r\n#elif STBTT_RASTERIZER_VERSION == 2\r\n   int vsubsample = 1;\r\n#else\r\n   #error \"Unrecognized value of STBTT_RASTERIZER_VERSION\"\r\n#endif\r\n   // vsubsample should divide 255 evenly; otherwise we won't reach full opacity\r\n\r\n   // now we have to blow out the windings into explicit edge lists\r\n   n = 0;\r\n   for (i=0; i < windings; ++i)\r\n      n += wcount[i];\r\n\r\n   e = (stbtt__edge *) STBTT_malloc(sizeof(*e) * (n+1), userdata); // add an extra one as a sentinel\r\n   if (e == 0) return;\r\n   n = 0;\r\n\r\n   m=0;\r\n   for (i=0; i < windings; ++i) {\r\n      stbtt__point *p = pts + m;\r\n      m += wcount[i];\r\n      j = wcount[i]-1;\r\n      for (k=0; k < wcount[i]; j=k++) {\r\n         int a=k,b=j;\r\n         // skip the edge if horizontal\r\n         if (p[j].y == p[k].y)\r\n            continue;\r\n         // add edge from j to k to the list\r\n         e[n].invert = 0;\r\n         if (invert ? p[j].y > p[k].y : p[j].y < p[k].y) {\r\n            e[n].invert = 1;\r\n            a=j,b=k;\r\n         }\r\n         e[n].x0 = p[a].x * scale_x + shift_x;\r\n         e[n].y0 = (p[a].y * y_scale_inv + shift_y) * vsubsample;\r\n         e[n].x1 = p[b].x * scale_x + shift_x;\r\n         e[n].y1 = (p[b].y * y_scale_inv + shift_y) * vsubsample;\r\n         ++n;\r\n      }\r\n   }\r\n\r\n   // now sort the edges by their highest point (should snap to integer, and then by x)\r\n   //STBTT_sort(e, n, sizeof(e[0]), stbtt__edge_compare);\r\n   stbtt__sort_edges(e, n);\r\n\r\n   // now, traverse the scanlines and find the intersections on each scanline, use xor winding rule\r\n   stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y, userdata);\r\n\r\n   STBTT_free(e, userdata);\r\n}\r\n\r\nstatic void stbtt__add_point(stbtt__point *points, int n, float x, float y)\r\n{\r\n   if (!points) return; // during first pass, it's unallocated\r\n   points[n].x = x;\r\n   points[n].y = y;\r\n}\r\n\r\n// tessellate until threshold p is happy... @TODO warped to compensate for non-linear stretching\r\nstatic int stbtt__tesselate_curve(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float objspace_flatness_squared, int n)\r\n{\r\n   // midpoint\r\n   float mx = (x0 + 2*x1 + x2)/4;\r\n   float my = (y0 + 2*y1 + y2)/4;\r\n   // versus directly drawn line\r\n   float dx = (x0+x2)/2 - mx;\r\n   float dy = (y0+y2)/2 - my;\r\n   if (n > 16) // 65536 segments on one curve better be enough!\r\n      return 1;\r\n   if (dx*dx+dy*dy > objspace_flatness_squared) { // half-pixel error allowed... need to be smaller if AA\r\n      stbtt__tesselate_curve(points, num_points, x0,y0, (x0+x1)/2.0f,(y0+y1)/2.0f, mx,my, objspace_flatness_squared,n+1);\r\n      stbtt__tesselate_curve(points, num_points, mx,my, (x1+x2)/2.0f,(y1+y2)/2.0f, x2,y2, objspace_flatness_squared,n+1);\r\n   } else {\r\n      stbtt__add_point(points, *num_points,x2,y2);\r\n      *num_points = *num_points+1;\r\n   }\r\n   return 1;\r\n}\r\n\r\nstatic void stbtt__tesselate_cubic(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3, float objspace_flatness_squared, int n)\r\n{\r\n   // @TODO this \"flatness\" calculation is just made-up nonsense that seems to work well enough\r\n   float dx0 = x1-x0;\r\n   float dy0 = y1-y0;\r\n   float dx1 = x2-x1;\r\n   float dy1 = y2-y1;\r\n   float dx2 = x3-x2;\r\n   float dy2 = y3-y2;\r\n   float dx = x3-x0;\r\n   float dy = y3-y0;\r\n   float longlen = (float) (STBTT_sqrt(dx0*dx0+dy0*dy0)+STBTT_sqrt(dx1*dx1+dy1*dy1)+STBTT_sqrt(dx2*dx2+dy2*dy2));\r\n   float shortlen = (float) STBTT_sqrt(dx*dx+dy*dy);\r\n   float flatness_squared = longlen*longlen-shortlen*shortlen;\r\n\r\n   if (n > 16) // 65536 segments on one curve better be enough!\r\n      return;\r\n\r\n   if (flatness_squared > objspace_flatness_squared) {\r\n      float x01 = (x0+x1)/2;\r\n      float y01 = (y0+y1)/2;\r\n      float x12 = (x1+x2)/2;\r\n      float y12 = (y1+y2)/2;\r\n      float x23 = (x2+x3)/2;\r\n      float y23 = (y2+y3)/2;\r\n\r\n      float xa = (x01+x12)/2;\r\n      float ya = (y01+y12)/2;\r\n      float xb = (x12+x23)/2;\r\n      float yb = (y12+y23)/2;\r\n\r\n      float mx = (xa+xb)/2;\r\n      float my = (ya+yb)/2;\r\n\r\n      stbtt__tesselate_cubic(points, num_points, x0,y0, x01,y01, xa,ya, mx,my, objspace_flatness_squared,n+1);\r\n      stbtt__tesselate_cubic(points, num_points, mx,my, xb,yb, x23,y23, x3,y3, objspace_flatness_squared,n+1);\r\n   } else {\r\n      stbtt__add_point(points, *num_points,x3,y3);\r\n      *num_points = *num_points+1;\r\n   }\r\n}\r\n\r\n// returns number of contours\r\nstatic stbtt__point *stbtt_FlattenCurves(stbtt_vertex *vertices, int num_verts, float objspace_flatness, int **contour_lengths, int *num_contours, void *userdata)\r\n{\r\n   stbtt__point *points=0;\r\n   int num_points=0;\r\n\r\n   float objspace_flatness_squared = objspace_flatness * objspace_flatness;\r\n   int i,n=0,start=0, pass;\r\n\r\n   // count how many \"moves\" there are to get the contour count\r\n   for (i=0; i < num_verts; ++i)\r\n      if (vertices[i].type == STBTT_vmove)\r\n         ++n;\r\n\r\n   *num_contours = n;\r\n   if (n == 0) return 0;\r\n\r\n   *contour_lengths = (int *) STBTT_malloc(sizeof(**contour_lengths) * n, userdata);\r\n\r\n   if (*contour_lengths == 0) {\r\n      *num_contours = 0;\r\n      return 0;\r\n   }\r\n\r\n   // make two passes through the points so we don't need to realloc\r\n   for (pass=0; pass < 2; ++pass) {\r\n      float x=0,y=0;\r\n      if (pass == 1) {\r\n         points = (stbtt__point *) STBTT_malloc(num_points * sizeof(points[0]), userdata);\r\n         if (points == NULL) goto error;\r\n      }\r\n      num_points = 0;\r\n      n= -1;\r\n      for (i=0; i < num_verts; ++i) {\r\n         switch (vertices[i].type) {\r\n            case STBTT_vmove:\r\n               // start the next contour\r\n               if (n >= 0)\r\n                  (*contour_lengths)[n] = num_points - start;\r\n               ++n;\r\n               start = num_points;\r\n\r\n               x = vertices[i].x, y = vertices[i].y;\r\n               stbtt__add_point(points, num_points++, x,y);\r\n               break;\r\n            case STBTT_vline:\r\n               x = vertices[i].x, y = vertices[i].y;\r\n               stbtt__add_point(points, num_points++, x, y);\r\n               break;\r\n            case STBTT_vcurve:\r\n               stbtt__tesselate_curve(points, &num_points, x,y,\r\n                                        vertices[i].cx, vertices[i].cy,\r\n                                        vertices[i].x,  vertices[i].y,\r\n                                        objspace_flatness_squared, 0);\r\n               x = vertices[i].x, y = vertices[i].y;\r\n               break;\r\n            case STBTT_vcubic:\r\n               stbtt__tesselate_cubic(points, &num_points, x,y,\r\n                                        vertices[i].cx, vertices[i].cy,\r\n                                        vertices[i].cx1, vertices[i].cy1,\r\n                                        vertices[i].x,  vertices[i].y,\r\n                                        objspace_flatness_squared, 0);\r\n               x = vertices[i].x, y = vertices[i].y;\r\n               break;\r\n         }\r\n      }\r\n      (*contour_lengths)[n] = num_points - start;\r\n   }\r\n\r\n   return points;\r\nerror:\r\n   STBTT_free(points, userdata);\r\n   STBTT_free(*contour_lengths, userdata);\r\n   *contour_lengths = 0;\r\n   *num_contours = 0;\r\n   return NULL;\r\n}\r\n\r\nSTBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, float flatness_in_pixels, stbtt_vertex *vertices, int num_verts, float scale_x, float scale_y, float shift_x, float shift_y, int x_off, int y_off, int invert, void *userdata)\r\n{\r\n   float scale            = scale_x > scale_y ? scale_y : scale_x;\r\n   int winding_count      = 0;\r\n   int *winding_lengths   = NULL;\r\n   stbtt__point *windings = stbtt_FlattenCurves(vertices, num_verts, flatness_in_pixels / scale, &winding_lengths, &winding_count, userdata);\r\n   if (windings) {\r\n      stbtt__rasterize(result, windings, winding_lengths, winding_count, scale_x, scale_y, shift_x, shift_y, x_off, y_off, invert, userdata);\r\n      STBTT_free(winding_lengths, userdata);\r\n      STBTT_free(windings, userdata);\r\n   }\r\n}\r\n\r\nSTBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata)\r\n{\r\n   STBTT_free(bitmap, userdata);\r\n}\r\n\r\nSTBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff)\r\n{\r\n   int ix0,iy0,ix1,iy1;\r\n   stbtt__bitmap gbm;\r\n   stbtt_vertex *vertices;\r\n   int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices);\r\n\r\n   if (scale_x == 0) scale_x = scale_y;\r\n   if (scale_y == 0) {\r\n      if (scale_x == 0) {\r\n         STBTT_free(vertices, info->userdata);\r\n         return NULL;\r\n      }\r\n      scale_y = scale_x;\r\n   }\r\n\r\n   stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,&ix1,&iy1);\r\n\r\n   // now we get the size\r\n   gbm.w = (ix1 - ix0);\r\n   gbm.h = (iy1 - iy0);\r\n   gbm.pixels = NULL; // in case we error\r\n\r\n   if (width ) *width  = gbm.w;\r\n   if (height) *height = gbm.h;\r\n   if (xoff  ) *xoff   = ix0;\r\n   if (yoff  ) *yoff   = iy0;\r\n\r\n   if (gbm.w && gbm.h) {\r\n      gbm.pixels = (unsigned char *) STBTT_malloc(gbm.w * gbm.h, info->userdata);\r\n      if (gbm.pixels) {\r\n         gbm.stride = gbm.w;\r\n\r\n         stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0, iy0, 1, info->userdata);\r\n      }\r\n   }\r\n   STBTT_free(vertices, info->userdata);\r\n   return gbm.pixels;\r\n}\r\n\r\nSTBTT_DEF unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff)\r\n{\r\n   return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y, 0.0f, 0.0f, glyph, width, height, xoff, yoff);\r\n}\r\n\r\nSTBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph)\r\n{\r\n   int ix0,iy0;\r\n   stbtt_vertex *vertices;\r\n   int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices);\r\n   stbtt__bitmap gbm;\r\n\r\n   stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,0,0);\r\n   gbm.pixels = output;\r\n   gbm.w = out_w;\r\n   gbm.h = out_h;\r\n   gbm.stride = out_stride;\r\n\r\n   if (gbm.w && gbm.h)\r\n      stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0,iy0, 1, info->userdata);\r\n\r\n   STBTT_free(vertices, info->userdata);\r\n}\r\n\r\nSTBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph)\r\n{\r\n   stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, glyph);\r\n}\r\n\r\nSTBTT_DEF unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff)\r\n{\r\n   return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y,shift_x,shift_y, stbtt_FindGlyphIndex(info,codepoint), width,height,xoff,yoff);\r\n}\r\n\r\nSTBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int codepoint)\r\n{\r\n   stbtt_MakeGlyphBitmapSubpixelPrefilter(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, oversample_x, oversample_y, sub_x, sub_y, stbtt_FindGlyphIndex(info,codepoint));\r\n}\r\n\r\nSTBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint)\r\n{\r\n   stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, stbtt_FindGlyphIndex(info,codepoint));\r\n}\r\n\r\nSTBTT_DEF unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff)\r\n{\r\n   return stbtt_GetCodepointBitmapSubpixel(info, scale_x, scale_y, 0.0f,0.0f, codepoint, width,height,xoff,yoff);\r\n}\r\n\r\nSTBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint)\r\n{\r\n   stbtt_MakeCodepointBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, codepoint);\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//\r\n// bitmap baking\r\n//\r\n// This is SUPER-CRAPPY packing to keep source code small\r\n\r\nstatic int stbtt_BakeFontBitmap_internal(unsigned char *data, int offset,  // font location (use offset=0 for plain .ttf)\r\n                                float pixel_height,                     // height of font in pixels\r\n                                unsigned char *pixels, int pw, int ph,  // bitmap to be filled in\r\n                                int first_char, int num_chars,          // characters to bake\r\n                                stbtt_bakedchar *chardata)\r\n{\r\n   float scale;\r\n   int x,y,bottom_y, i;\r\n   stbtt_fontinfo f;\r\n   f.userdata = NULL;\r\n   if (!stbtt_InitFont(&f, data, offset))\r\n      return -1;\r\n   STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels\r\n   x=y=1;\r\n   bottom_y = 1;\r\n\r\n   scale = stbtt_ScaleForPixelHeight(&f, pixel_height);\r\n\r\n   for (i=0; i < num_chars; ++i) {\r\n      int advance, lsb, x0,y0,x1,y1,gw,gh;\r\n      int g = stbtt_FindGlyphIndex(&f, first_char + i);\r\n      stbtt_GetGlyphHMetrics(&f, g, &advance, &lsb);\r\n      stbtt_GetGlyphBitmapBox(&f, g, scale,scale, &x0,&y0,&x1,&y1);\r\n      gw = x1-x0;\r\n      gh = y1-y0;\r\n      if (x + gw + 1 >= pw)\r\n         y = bottom_y, x = 1; // advance to next row\r\n      if (y + gh + 1 >= ph) // check if it fits vertically AFTER potentially moving to next row\r\n         return -i;\r\n      STBTT_assert(x+gw < pw);\r\n      STBTT_assert(y+gh < ph);\r\n      stbtt_MakeGlyphBitmap(&f, pixels+x+y*pw, gw,gh,pw, scale,scale, g);\r\n      chardata[i].x0 = (stbtt_int16) x;\r\n      chardata[i].y0 = (stbtt_int16) y;\r\n      chardata[i].x1 = (stbtt_int16) (x + gw);\r\n      chardata[i].y1 = (stbtt_int16) (y + gh);\r\n      chardata[i].xadvance = scale * advance;\r\n      chardata[i].xoff     = (float) x0;\r\n      chardata[i].yoff     = (float) y0;\r\n      x = x + gw + 1;\r\n      if (y+gh+1 > bottom_y)\r\n         bottom_y = y+gh+1;\r\n   }\r\n   return bottom_y;\r\n}\r\n\r\nSTBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int opengl_fillrule)\r\n{\r\n   float d3d_bias = opengl_fillrule ? 0 : -0.5f;\r\n   float ipw = 1.0f / pw, iph = 1.0f / ph;\r\n   const stbtt_bakedchar *b = chardata + char_index;\r\n   int round_x = STBTT_ifloor((*xpos + b->xoff) + 0.5f);\r\n   int round_y = STBTT_ifloor((*ypos + b->yoff) + 0.5f);\r\n\r\n   q->x0 = round_x + d3d_bias;\r\n   q->y0 = round_y + d3d_bias;\r\n   q->x1 = round_x + b->x1 - b->x0 + d3d_bias;\r\n   q->y1 = round_y + b->y1 - b->y0 + d3d_bias;\r\n\r\n   q->s0 = b->x0 * ipw;\r\n   q->t0 = b->y0 * iph;\r\n   q->s1 = b->x1 * ipw;\r\n   q->t1 = b->y1 * iph;\r\n\r\n   *xpos += b->xadvance;\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//\r\n// rectangle packing replacement routines if you don't have stb_rect_pack.h\r\n//\r\n\r\n#ifndef STB_RECT_PACK_VERSION\r\n\r\ntypedef int stbrp_coord;\r\n\r\n////////////////////////////////////////////////////////////////////////////////////\r\n//                                                                                //\r\n//                                                                                //\r\n// COMPILER WARNING ?!?!?                                                         //\r\n//                                                                                //\r\n//                                                                                //\r\n// if you get a compile warning due to these symbols being defined more than      //\r\n// once, move #include \"stb_rect_pack.h\" before #include \"stb_truetype.h\"         //\r\n//                                                                                //\r\n////////////////////////////////////////////////////////////////////////////////////\r\n\r\ntypedef struct\r\n{\r\n   int width,height;\r\n   int x,y,bottom_y;\r\n} stbrp_context;\r\n\r\ntypedef struct\r\n{\r\n   unsigned char x;\r\n} stbrp_node;\r\n\r\nstruct stbrp_rect\r\n{\r\n   stbrp_coord x,y;\r\n   int id,w,h,was_packed;\r\n};\r\n\r\nstatic void stbrp_init_target(stbrp_context *con, int pw, int ph, stbrp_node *nodes, int num_nodes)\r\n{\r\n   con->width  = pw;\r\n   con->height = ph;\r\n   con->x = 0;\r\n   con->y = 0;\r\n   con->bottom_y = 0;\r\n   STBTT__NOTUSED(nodes);\r\n   STBTT__NOTUSED(num_nodes);\r\n}\r\n\r\nstatic void stbrp_pack_rects(stbrp_context *con, stbrp_rect *rects, int num_rects)\r\n{\r\n   int i;\r\n   for (i=0; i < num_rects; ++i) {\r\n      if (con->x + rects[i].w > con->width) {\r\n         con->x = 0;\r\n         con->y = con->bottom_y;\r\n      }\r\n      if (con->y + rects[i].h > con->height)\r\n         break;\r\n      rects[i].x = con->x;\r\n      rects[i].y = con->y;\r\n      rects[i].was_packed = 1;\r\n      con->x += rects[i].w;\r\n      if (con->y + rects[i].h > con->bottom_y)\r\n         con->bottom_y = con->y + rects[i].h;\r\n   }\r\n   for (   ; i < num_rects; ++i)\r\n      rects[i].was_packed = 0;\r\n}\r\n#endif\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//\r\n// bitmap baking\r\n//\r\n// This is SUPER-AWESOME (tm Ryan Gordon) packing using stb_rect_pack.h. If\r\n// stb_rect_pack.h isn't available, it uses the BakeFontBitmap strategy.\r\n\r\nSTBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int pw, int ph, int stride_in_bytes, int padding, void *alloc_context)\r\n{\r\n   stbrp_context *context = (stbrp_context *) STBTT_malloc(sizeof(*context)            ,alloc_context);\r\n   int            num_nodes = pw - padding;\r\n   stbrp_node    *nodes   = (stbrp_node    *) STBTT_malloc(sizeof(*nodes  ) * num_nodes,alloc_context);\r\n\r\n   if (context == NULL || nodes == NULL) {\r\n      if (context != NULL) STBTT_free(context, alloc_context);\r\n      if (nodes   != NULL) STBTT_free(nodes  , alloc_context);\r\n      return 0;\r\n   }\r\n\r\n   spc->user_allocator_context = alloc_context;\r\n   spc->width = pw;\r\n   spc->height = ph;\r\n   spc->pixels = pixels;\r\n   spc->pack_info = context;\r\n   spc->nodes = nodes;\r\n   spc->padding = padding;\r\n   spc->stride_in_bytes = stride_in_bytes != 0 ? stride_in_bytes : pw;\r\n   spc->h_oversample = 1;\r\n   spc->v_oversample = 1;\r\n   spc->skip_missing = 0;\r\n\r\n   stbrp_init_target(context, pw-padding, ph-padding, nodes, num_nodes);\r\n\r\n   if (pixels)\r\n      STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels\r\n\r\n   return 1;\r\n}\r\n\r\nSTBTT_DEF void stbtt_PackEnd  (stbtt_pack_context *spc)\r\n{\r\n   STBTT_free(spc->nodes    , spc->user_allocator_context);\r\n   STBTT_free(spc->pack_info, spc->user_allocator_context);\r\n}\r\n\r\nSTBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample)\r\n{\r\n   STBTT_assert(h_oversample <= STBTT_MAX_OVERSAMPLE);\r\n   STBTT_assert(v_oversample <= STBTT_MAX_OVERSAMPLE);\r\n   if (h_oversample <= STBTT_MAX_OVERSAMPLE)\r\n      spc->h_oversample = h_oversample;\r\n   if (v_oversample <= STBTT_MAX_OVERSAMPLE)\r\n      spc->v_oversample = v_oversample;\r\n}\r\n\r\nSTBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context *spc, int skip)\r\n{\r\n   spc->skip_missing = skip;\r\n}\r\n\r\n#define STBTT__OVER_MASK  (STBTT_MAX_OVERSAMPLE-1)\r\n\r\nstatic void stbtt__h_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width)\r\n{\r\n   unsigned char buffer[STBTT_MAX_OVERSAMPLE];\r\n   int safe_w = w - kernel_width;\r\n   int j;\r\n   STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze\r\n   for (j=0; j < h; ++j) {\r\n      int i;\r\n      unsigned int total;\r\n      STBTT_memset(buffer, 0, kernel_width);\r\n\r\n      total = 0;\r\n\r\n      // make kernel_width a constant in common cases so compiler can optimize out the divide\r\n      switch (kernel_width) {\r\n         case 2:\r\n            for (i=0; i <= safe_w; ++i) {\r\n               total += pixels[i] - buffer[i & STBTT__OVER_MASK];\r\n               buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];\r\n               pixels[i] = (unsigned char) (total / 2);\r\n            }\r\n            break;\r\n         case 3:\r\n            for (i=0; i <= safe_w; ++i) {\r\n               total += pixels[i] - buffer[i & STBTT__OVER_MASK];\r\n               buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];\r\n               pixels[i] = (unsigned char) (total / 3);\r\n            }\r\n            break;\r\n         case 4:\r\n            for (i=0; i <= safe_w; ++i) {\r\n               total += pixels[i] - buffer[i & STBTT__OVER_MASK];\r\n               buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];\r\n               pixels[i] = (unsigned char) (total / 4);\r\n            }\r\n            break;\r\n         case 5:\r\n            for (i=0; i <= safe_w; ++i) {\r\n               total += pixels[i] - buffer[i & STBTT__OVER_MASK];\r\n               buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];\r\n               pixels[i] = (unsigned char) (total / 5);\r\n            }\r\n            break;\r\n         default:\r\n            for (i=0; i <= safe_w; ++i) {\r\n               total += pixels[i] - buffer[i & STBTT__OVER_MASK];\r\n               buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i];\r\n               pixels[i] = (unsigned char) (total / kernel_width);\r\n            }\r\n            break;\r\n      }\r\n\r\n      for (; i < w; ++i) {\r\n         STBTT_assert(pixels[i] == 0);\r\n         total -= buffer[i & STBTT__OVER_MASK];\r\n         pixels[i] = (unsigned char) (total / kernel_width);\r\n      }\r\n\r\n      pixels += stride_in_bytes;\r\n   }\r\n}\r\n\r\nstatic void stbtt__v_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width)\r\n{\r\n   unsigned char buffer[STBTT_MAX_OVERSAMPLE];\r\n   int safe_h = h - kernel_width;\r\n   int j;\r\n   STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze\r\n   for (j=0; j < w; ++j) {\r\n      int i;\r\n      unsigned int total;\r\n      STBTT_memset(buffer, 0, kernel_width);\r\n\r\n      total = 0;\r\n\r\n      // make kernel_width a constant in common cases so compiler can optimize out the divide\r\n      switch (kernel_width) {\r\n         case 2:\r\n            for (i=0; i <= safe_h; ++i) {\r\n               total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];\r\n               buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];\r\n               pixels[i*stride_in_bytes] = (unsigned char) (total / 2);\r\n            }\r\n            break;\r\n         case 3:\r\n            for (i=0; i <= safe_h; ++i) {\r\n               total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];\r\n               buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];\r\n               pixels[i*stride_in_bytes] = (unsigned char) (total / 3);\r\n            }\r\n            break;\r\n         case 4:\r\n            for (i=0; i <= safe_h; ++i) {\r\n               total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];\r\n               buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];\r\n               pixels[i*stride_in_bytes] = (unsigned char) (total / 4);\r\n            }\r\n            break;\r\n         case 5:\r\n            for (i=0; i <= safe_h; ++i) {\r\n               total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];\r\n               buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];\r\n               pixels[i*stride_in_bytes] = (unsigned char) (total / 5);\r\n            }\r\n            break;\r\n         default:\r\n            for (i=0; i <= safe_h; ++i) {\r\n               total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK];\r\n               buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes];\r\n               pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width);\r\n            }\r\n            break;\r\n      }\r\n\r\n      for (; i < h; ++i) {\r\n         STBTT_assert(pixels[i*stride_in_bytes] == 0);\r\n         total -= buffer[i & STBTT__OVER_MASK];\r\n         pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width);\r\n      }\r\n\r\n      pixels += 1;\r\n   }\r\n}\r\n\r\nstatic float stbtt__oversample_shift(int oversample)\r\n{\r\n   if (!oversample)\r\n      return 0.0f;\r\n\r\n   // The prefilter is a box filter of width \"oversample\",\r\n   // which shifts phase by (oversample - 1)/2 pixels in\r\n   // oversampled space. We want to shift in the opposite\r\n   // direction to counter this.\r\n   return (float)-(oversample - 1) / (2.0f * (float)oversample);\r\n}\r\n\r\n// rects array must be big enough to accommodate all characters in the given ranges\r\nSTBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects)\r\n{\r\n   int i,j,k;\r\n\r\n   k=0;\r\n   for (i=0; i < num_ranges; ++i) {\r\n      float fh = ranges[i].font_size;\r\n      float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh);\r\n      ranges[i].h_oversample = (unsigned char) spc->h_oversample;\r\n      ranges[i].v_oversample = (unsigned char) spc->v_oversample;\r\n      for (j=0; j < ranges[i].num_chars; ++j) {\r\n         int x0,y0,x1,y1;\r\n         int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j];\r\n         int glyph = stbtt_FindGlyphIndex(info, codepoint);\r\n         if (glyph == 0 && spc->skip_missing) {\r\n            rects[k].w = rects[k].h = 0;\r\n         } else {\r\n            stbtt_GetGlyphBitmapBoxSubpixel(info,glyph,\r\n                                            scale * spc->h_oversample,\r\n                                            scale * spc->v_oversample,\r\n                                            0,0,\r\n                                            &x0,&y0,&x1,&y1);\r\n            rects[k].w = (stbrp_coord) (x1-x0 + spc->padding + spc->h_oversample-1);\r\n            rects[k].h = (stbrp_coord) (y1-y0 + spc->padding + spc->v_oversample-1);\r\n         }\r\n         ++k;\r\n      }\r\n   }\r\n\r\n   return k;\r\n}\r\n\r\nSTBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int prefilter_x, int prefilter_y, float *sub_x, float *sub_y, int glyph)\r\n{\r\n   stbtt_MakeGlyphBitmapSubpixel(info,\r\n                                 output,\r\n                                 out_w - (prefilter_x - 1),\r\n                                 out_h - (prefilter_y - 1),\r\n                                 out_stride,\r\n                                 scale_x,\r\n                                 scale_y,\r\n                                 shift_x,\r\n                                 shift_y,\r\n                                 glyph);\r\n\r\n   if (prefilter_x > 1)\r\n      stbtt__h_prefilter(output, out_w, out_h, out_stride, prefilter_x);\r\n\r\n   if (prefilter_y > 1)\r\n      stbtt__v_prefilter(output, out_w, out_h, out_stride, prefilter_y);\r\n\r\n   *sub_x = stbtt__oversample_shift(prefilter_x);\r\n   *sub_y = stbtt__oversample_shift(prefilter_y);\r\n}\r\n\r\n// rects array must be big enough to accommodate all characters in the given ranges\r\nSTBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects)\r\n{\r\n   int i,j,k, return_value = 1;\r\n\r\n   // save current values\r\n   int old_h_over = spc->h_oversample;\r\n   int old_v_over = spc->v_oversample;\r\n\r\n   k = 0;\r\n   for (i=0; i < num_ranges; ++i) {\r\n      float fh = ranges[i].font_size;\r\n      float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh);\r\n      float recip_h,recip_v,sub_x,sub_y;\r\n      spc->h_oversample = ranges[i].h_oversample;\r\n      spc->v_oversample = ranges[i].v_oversample;\r\n      recip_h = 1.0f / spc->h_oversample;\r\n      recip_v = 1.0f / spc->v_oversample;\r\n      sub_x = stbtt__oversample_shift(spc->h_oversample);\r\n      sub_y = stbtt__oversample_shift(spc->v_oversample);\r\n      for (j=0; j < ranges[i].num_chars; ++j) {\r\n         stbrp_rect *r = &rects[k];\r\n         if (r->was_packed && r->w != 0 && r->h != 0) {\r\n            stbtt_packedchar *bc = &ranges[i].chardata_for_range[j];\r\n            int advance, lsb, x0,y0,x1,y1;\r\n            int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j];\r\n            int glyph = stbtt_FindGlyphIndex(info, codepoint);\r\n            stbrp_coord pad = (stbrp_coord) spc->padding;\r\n\r\n            // pad on left and top\r\n            r->x += pad;\r\n            r->y += pad;\r\n            r->w -= pad;\r\n            r->h -= pad;\r\n            stbtt_GetGlyphHMetrics(info, glyph, &advance, &lsb);\r\n            stbtt_GetGlyphBitmapBox(info, glyph,\r\n                                    scale * spc->h_oversample,\r\n                                    scale * spc->v_oversample,\r\n                                    &x0,&y0,&x1,&y1);\r\n            stbtt_MakeGlyphBitmapSubpixel(info,\r\n                                          spc->pixels + r->x + r->y*spc->stride_in_bytes,\r\n                                          r->w - spc->h_oversample+1,\r\n                                          r->h - spc->v_oversample+1,\r\n                                          spc->stride_in_bytes,\r\n                                          scale * spc->h_oversample,\r\n                                          scale * spc->v_oversample,\r\n                                          0,0,\r\n                                          glyph);\r\n\r\n            if (spc->h_oversample > 1)\r\n               stbtt__h_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes,\r\n                                  r->w, r->h, spc->stride_in_bytes,\r\n                                  spc->h_oversample);\r\n\r\n            if (spc->v_oversample > 1)\r\n               stbtt__v_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes,\r\n                                  r->w, r->h, spc->stride_in_bytes,\r\n                                  spc->v_oversample);\r\n\r\n            bc->x0       = (stbtt_int16)  r->x;\r\n            bc->y0       = (stbtt_int16)  r->y;\r\n            bc->x1       = (stbtt_int16) (r->x + r->w);\r\n            bc->y1       = (stbtt_int16) (r->y + r->h);\r\n            bc->xadvance =                scale * advance;\r\n            bc->xoff     =       (float)  x0 * recip_h + sub_x;\r\n            bc->yoff     =       (float)  y0 * recip_v + sub_y;\r\n            bc->xoff2    =                (x0 + r->w) * recip_h + sub_x;\r\n            bc->yoff2    =                (y0 + r->h) * recip_v + sub_y;\r\n         } else {\r\n            return_value = 0; // if any fail, report failure\r\n         }\r\n\r\n         ++k;\r\n      }\r\n   }\r\n\r\n   // restore original values\r\n   spc->h_oversample = old_h_over;\r\n   spc->v_oversample = old_v_over;\r\n\r\n   return return_value;\r\n}\r\n\r\nSTBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects)\r\n{\r\n   stbrp_pack_rects((stbrp_context *) spc->pack_info, rects, num_rects);\r\n}\r\n\r\nSTBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges)\r\n{\r\n   stbtt_fontinfo info;\r\n   int i,j,n, return_value; // [DEAR IMGUI] removed = 1\r\n   //stbrp_context *context = (stbrp_context *) spc->pack_info;\r\n   stbrp_rect    *rects;\r\n\r\n   // flag all characters as NOT packed\r\n   for (i=0; i < num_ranges; ++i)\r\n      for (j=0; j < ranges[i].num_chars; ++j)\r\n         ranges[i].chardata_for_range[j].x0 =\r\n         ranges[i].chardata_for_range[j].y0 =\r\n         ranges[i].chardata_for_range[j].x1 =\r\n         ranges[i].chardata_for_range[j].y1 = 0;\r\n\r\n   n = 0;\r\n   for (i=0; i < num_ranges; ++i)\r\n      n += ranges[i].num_chars;\r\n\r\n   rects = (stbrp_rect *) STBTT_malloc(sizeof(*rects) * n, spc->user_allocator_context);\r\n   if (rects == NULL)\r\n      return 0;\r\n\r\n   info.userdata = spc->user_allocator_context;\r\n   stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata,font_index));\r\n\r\n   n = stbtt_PackFontRangesGatherRects(spc, &info, ranges, num_ranges, rects);\r\n\r\n   stbtt_PackFontRangesPackRects(spc, rects, n);\r\n\r\n   return_value = stbtt_PackFontRangesRenderIntoRects(spc, &info, ranges, num_ranges, rects);\r\n\r\n   STBTT_free(rects, spc->user_allocator_context);\r\n   return return_value;\r\n}\r\n\r\nSTBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, float font_size,\r\n            int first_unicode_codepoint_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range)\r\n{\r\n   stbtt_pack_range range;\r\n   range.first_unicode_codepoint_in_range = first_unicode_codepoint_in_range;\r\n   range.array_of_unicode_codepoints = NULL;\r\n   range.num_chars                   = num_chars_in_range;\r\n   range.chardata_for_range          = chardata_for_range;\r\n   range.font_size                   = font_size;\r\n   return stbtt_PackFontRanges(spc, fontdata, font_index, &range, 1);\r\n}\r\n\r\nSTBTT_DEF void stbtt_GetScaledFontVMetrics(const unsigned char *fontdata, int index, float size, float *ascent, float *descent, float *lineGap)\r\n{\r\n   int i_ascent, i_descent, i_lineGap;\r\n   float scale;\r\n   stbtt_fontinfo info;\r\n   stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata, index));\r\n   scale = size > 0 ? stbtt_ScaleForPixelHeight(&info, size) : stbtt_ScaleForMappingEmToPixels(&info, -size);\r\n   stbtt_GetFontVMetrics(&info, &i_ascent, &i_descent, &i_lineGap);\r\n   *ascent  = (float) i_ascent  * scale;\r\n   *descent = (float) i_descent * scale;\r\n   *lineGap = (float) i_lineGap * scale;\r\n}\r\n\r\nSTBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int align_to_integer)\r\n{\r\n   float ipw = 1.0f / pw, iph = 1.0f / ph;\r\n   const stbtt_packedchar *b = chardata + char_index;\r\n\r\n   if (align_to_integer) {\r\n      float x = (float) STBTT_ifloor((*xpos + b->xoff) + 0.5f);\r\n      float y = (float) STBTT_ifloor((*ypos + b->yoff) + 0.5f);\r\n      q->x0 = x;\r\n      q->y0 = y;\r\n      q->x1 = x + b->xoff2 - b->xoff;\r\n      q->y1 = y + b->yoff2 - b->yoff;\r\n   } else {\r\n      q->x0 = *xpos + b->xoff;\r\n      q->y0 = *ypos + b->yoff;\r\n      q->x1 = *xpos + b->xoff2;\r\n      q->y1 = *ypos + b->yoff2;\r\n   }\r\n\r\n   q->s0 = b->x0 * ipw;\r\n   q->t0 = b->y0 * iph;\r\n   q->s1 = b->x1 * ipw;\r\n   q->t1 = b->y1 * iph;\r\n\r\n   *xpos += b->xadvance;\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//\r\n// sdf computation\r\n//\r\n\r\n#define STBTT_min(a,b)  ((a) < (b) ? (a) : (b))\r\n#define STBTT_max(a,b)  ((a) < (b) ? (b) : (a))\r\n\r\nstatic int stbtt__ray_intersect_bezier(float orig[2], float ray[2], float q0[2], float q1[2], float q2[2], float hits[2][2])\r\n{\r\n   float q0perp = q0[1]*ray[0] - q0[0]*ray[1];\r\n   float q1perp = q1[1]*ray[0] - q1[0]*ray[1];\r\n   float q2perp = q2[1]*ray[0] - q2[0]*ray[1];\r\n   float roperp = orig[1]*ray[0] - orig[0]*ray[1];\r\n\r\n   float a = q0perp - 2*q1perp + q2perp;\r\n   float b = q1perp - q0perp;\r\n   float c = q0perp - roperp;\r\n\r\n   float s0 = 0., s1 = 0.;\r\n   int num_s = 0;\r\n\r\n   if (a != 0.0) {\r\n      float discr = b*b - a*c;\r\n      if (discr > 0.0) {\r\n         float rcpna = -1 / a;\r\n         float d = (float) STBTT_sqrt(discr);\r\n         s0 = (b+d) * rcpna;\r\n         s1 = (b-d) * rcpna;\r\n         if (s0 >= 0.0 && s0 <= 1.0)\r\n            num_s = 1;\r\n         if (d > 0.0 && s1 >= 0.0 && s1 <= 1.0) {\r\n            if (num_s == 0) s0 = s1;\r\n            ++num_s;\r\n         }\r\n      }\r\n   } else {\r\n      // 2*b*s + c = 0\r\n      // s = -c / (2*b)\r\n      s0 = c / (-2 * b);\r\n      if (s0 >= 0.0 && s0 <= 1.0)\r\n         num_s = 1;\r\n   }\r\n\r\n   if (num_s == 0)\r\n      return 0;\r\n   else {\r\n      float rcp_len2 = 1 / (ray[0]*ray[0] + ray[1]*ray[1]);\r\n      float rayn_x = ray[0] * rcp_len2, rayn_y = ray[1] * rcp_len2;\r\n\r\n      float q0d =   q0[0]*rayn_x +   q0[1]*rayn_y;\r\n      float q1d =   q1[0]*rayn_x +   q1[1]*rayn_y;\r\n      float q2d =   q2[0]*rayn_x +   q2[1]*rayn_y;\r\n      float rod = orig[0]*rayn_x + orig[1]*rayn_y;\r\n\r\n      float q10d = q1d - q0d;\r\n      float q20d = q2d - q0d;\r\n      float q0rd = q0d - rod;\r\n\r\n      hits[0][0] = q0rd + s0*(2.0f - 2.0f*s0)*q10d + s0*s0*q20d;\r\n      hits[0][1] = a*s0+b;\r\n\r\n      if (num_s > 1) {\r\n         hits[1][0] = q0rd + s1*(2.0f - 2.0f*s1)*q10d + s1*s1*q20d;\r\n         hits[1][1] = a*s1+b;\r\n         return 2;\r\n      } else {\r\n         return 1;\r\n      }\r\n   }\r\n}\r\n\r\nstatic int equal(float *a, float *b)\r\n{\r\n   return (a[0] == b[0] && a[1] == b[1]);\r\n}\r\n\r\nstatic int stbtt__compute_crossings_x(float x, float y, int nverts, stbtt_vertex *verts)\r\n{\r\n   int i;\r\n   float orig[2], ray[2] = { 1, 0 };\r\n   float y_frac;\r\n   int winding = 0;\r\n\r\n   orig[0] = x;\r\n   //orig[1] = y; // [DEAR IMGUI] commented double assignment\r\n\r\n   // make sure y never passes through a vertex of the shape\r\n   y_frac = (float) STBTT_fmod(y, 1.0f);\r\n   if (y_frac < 0.01f)\r\n      y += 0.01f;\r\n   else if (y_frac > 0.99f)\r\n      y -= 0.01f;\r\n   orig[1] = y;\r\n\r\n   // test a ray from (-infinity,y) to (x,y)\r\n   for (i=0; i < nverts; ++i) {\r\n      if (verts[i].type == STBTT_vline) {\r\n         int x0 = (int) verts[i-1].x, y0 = (int) verts[i-1].y;\r\n         int x1 = (int) verts[i  ].x, y1 = (int) verts[i  ].y;\r\n         if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) {\r\n            float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0;\r\n            if (x_inter < x)\r\n               winding += (y0 < y1) ? 1 : -1;\r\n         }\r\n      }\r\n      if (verts[i].type == STBTT_vcurve) {\r\n         int x0 = (int) verts[i-1].x , y0 = (int) verts[i-1].y ;\r\n         int x1 = (int) verts[i  ].cx, y1 = (int) verts[i  ].cy;\r\n         int x2 = (int) verts[i  ].x , y2 = (int) verts[i  ].y ;\r\n         int ax = STBTT_min(x0,STBTT_min(x1,x2)), ay = STBTT_min(y0,STBTT_min(y1,y2));\r\n         int by = STBTT_max(y0,STBTT_max(y1,y2));\r\n         if (y > ay && y < by && x > ax) {\r\n            float q0[2],q1[2],q2[2];\r\n            float hits[2][2];\r\n            q0[0] = (float)x0;\r\n            q0[1] = (float)y0;\r\n            q1[0] = (float)x1;\r\n            q1[1] = (float)y1;\r\n            q2[0] = (float)x2;\r\n            q2[1] = (float)y2;\r\n            if (equal(q0,q1) || equal(q1,q2)) {\r\n               x0 = (int)verts[i-1].x;\r\n               y0 = (int)verts[i-1].y;\r\n               x1 = (int)verts[i  ].x;\r\n               y1 = (int)verts[i  ].y;\r\n               if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) {\r\n                  float x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0;\r\n                  if (x_inter < x)\r\n                     winding += (y0 < y1) ? 1 : -1;\r\n               }\r\n            } else {\r\n               int num_hits = stbtt__ray_intersect_bezier(orig, ray, q0, q1, q2, hits);\r\n               if (num_hits >= 1)\r\n                  if (hits[0][0] < 0)\r\n                     winding += (hits[0][1] < 0 ? -1 : 1);\r\n               if (num_hits >= 2)\r\n                  if (hits[1][0] < 0)\r\n                     winding += (hits[1][1] < 0 ? -1 : 1);\r\n            }\r\n         }\r\n      }\r\n   }\r\n   return winding;\r\n}\r\n\r\nstatic float stbtt__cuberoot( float x )\r\n{\r\n   if (x<0)\r\n      return -(float) STBTT_pow(-x,1.0f/3.0f);\r\n   else\r\n      return  (float) STBTT_pow( x,1.0f/3.0f);\r\n}\r\n\r\n// x^3 + c*x^2 + b*x + a = 0\r\nstatic int stbtt__solve_cubic(float a, float b, float c, float* r)\r\n{\r\n\tfloat s = -a / 3;\r\n\tfloat p = b - a*a / 3;\r\n\tfloat q = a * (2*a*a - 9*b) / 27 + c;\r\n   float p3 = p*p*p;\r\n\tfloat d = q*q + 4*p3 / 27;\r\n\tif (d >= 0) {\r\n\t\tfloat z = (float) STBTT_sqrt(d);\r\n\t\tfloat u = (-q + z) / 2;\r\n\t\tfloat v = (-q - z) / 2;\r\n\t\tu = stbtt__cuberoot(u);\r\n\t\tv = stbtt__cuberoot(v);\r\n\t\tr[0] = s + u + v;\r\n\t\treturn 1;\r\n\t} else {\r\n\t   float u = (float) STBTT_sqrt(-p/3);\r\n\t   float v = (float) STBTT_acos(-STBTT_sqrt(-27/p3) * q / 2) / 3; // p3 must be negative, since d is negative\r\n\t   float m = (float) STBTT_cos(v);\r\n      float n = (float) STBTT_cos(v-3.141592/2)*1.732050808f;\r\n\t   r[0] = s + u * 2 * m;\r\n\t   r[1] = s - u * (m + n);\r\n\t   r[2] = s - u * (m - n);\r\n\r\n      //STBTT_assert( STBTT_fabs(((r[0]+a)*r[0]+b)*r[0]+c) < 0.05f);  // these asserts may not be safe at all scales, though they're in bezier t parameter units so maybe?\r\n      //STBTT_assert( STBTT_fabs(((r[1]+a)*r[1]+b)*r[1]+c) < 0.05f);\r\n      //STBTT_assert( STBTT_fabs(((r[2]+a)*r[2]+b)*r[2]+c) < 0.05f);\r\n   \treturn 3;\r\n   }\r\n}\r\n\r\nSTBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff)\r\n{\r\n   float scale_x = scale, scale_y = scale;\r\n   int ix0,iy0,ix1,iy1;\r\n   int w,h;\r\n   unsigned char *data;\r\n\r\n   // if one scale is 0, use same scale for both\r\n   if (scale_x == 0) scale_x = scale_y;\r\n   if (scale_y == 0) {\r\n      if (scale_x == 0) return NULL;  // if both scales are 0, return NULL\r\n      scale_y = scale_x;\r\n   }\r\n\r\n   stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale, scale, 0.0f,0.0f, &ix0,&iy0,&ix1,&iy1);\r\n\r\n   // if empty, return NULL\r\n   if (ix0 == ix1 || iy0 == iy1)\r\n      return NULL;\r\n\r\n   ix0 -= padding;\r\n   iy0 -= padding;\r\n   ix1 += padding;\r\n   iy1 += padding;\r\n\r\n   w = (ix1 - ix0);\r\n   h = (iy1 - iy0);\r\n\r\n   if (width ) *width  = w;\r\n   if (height) *height = h;\r\n   if (xoff  ) *xoff   = ix0;\r\n   if (yoff  ) *yoff   = iy0;\r\n\r\n   // invert for y-downwards bitmaps\r\n   scale_y = -scale_y;\r\n\r\n   {\r\n      int x,y,i,j;\r\n      float *precompute;\r\n      stbtt_vertex *verts;\r\n      int num_verts = stbtt_GetGlyphShape(info, glyph, &verts);\r\n      data = (unsigned char *) STBTT_malloc(w * h, info->userdata);\r\n      precompute = (float *) STBTT_malloc(num_verts * sizeof(float), info->userdata);\r\n\r\n      for (i=0,j=num_verts-1; i < num_verts; j=i++) {\r\n         if (verts[i].type == STBTT_vline) {\r\n            float x0 = verts[i].x*scale_x, y0 = verts[i].y*scale_y;\r\n            float x1 = verts[j].x*scale_x, y1 = verts[j].y*scale_y;\r\n            float dist = (float) STBTT_sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0));\r\n            precompute[i] = (dist == 0) ? 0.0f : 1.0f / dist;\r\n         } else if (verts[i].type == STBTT_vcurve) {\r\n            float x2 = verts[j].x *scale_x, y2 = verts[j].y *scale_y;\r\n            float x1 = verts[i].cx*scale_x, y1 = verts[i].cy*scale_y;\r\n            float x0 = verts[i].x *scale_x, y0 = verts[i].y *scale_y;\r\n            float bx = x0 - 2*x1 + x2, by = y0 - 2*y1 + y2;\r\n            float len2 = bx*bx + by*by;\r\n            if (len2 != 0.0f)\r\n               precompute[i] = 1.0f / (bx*bx + by*by);\r\n            else\r\n               precompute[i] = 0.0f;\r\n         } else\r\n            precompute[i] = 0.0f;\r\n      }\r\n\r\n      for (y=iy0; y < iy1; ++y) {\r\n         for (x=ix0; x < ix1; ++x) {\r\n            float val;\r\n            float min_dist = 999999.0f;\r\n            float sx = (float) x + 0.5f;\r\n            float sy = (float) y + 0.5f;\r\n            float x_gspace = (sx / scale_x);\r\n            float y_gspace = (sy / scale_y);\r\n\r\n            int winding = stbtt__compute_crossings_x(x_gspace, y_gspace, num_verts, verts); // @OPTIMIZE: this could just be a rasterization, but needs to be line vs. non-tesselated curves so a new path\r\n\r\n            for (i=0; i < num_verts; ++i) {\r\n               float x0 = verts[i].x*scale_x, y0 = verts[i].y*scale_y;\r\n\r\n               // check against every point here rather than inside line/curve primitives -- @TODO: wrong if multiple 'moves' in a row produce a garbage point, and given culling, probably more efficient to do within line/curve\r\n               float dist2 = (x0-sx)*(x0-sx) + (y0-sy)*(y0-sy);\r\n               if (dist2 < min_dist*min_dist)\r\n                  min_dist = (float) STBTT_sqrt(dist2);\r\n\r\n               if (verts[i].type == STBTT_vline) {\r\n                  float x1 = verts[i-1].x*scale_x, y1 = verts[i-1].y*scale_y;\r\n\r\n                  // coarse culling against bbox\r\n                  //if (sx > STBTT_min(x0,x1)-min_dist && sx < STBTT_max(x0,x1)+min_dist &&\r\n                  //    sy > STBTT_min(y0,y1)-min_dist && sy < STBTT_max(y0,y1)+min_dist)\r\n                  float dist = (float) STBTT_fabs((x1-x0)*(y0-sy) - (y1-y0)*(x0-sx)) * precompute[i];\r\n                  STBTT_assert(i != 0);\r\n                  if (dist < min_dist) {\r\n                     // check position along line\r\n                     // x' = x0 + t*(x1-x0), y' = y0 + t*(y1-y0)\r\n                     // minimize (x'-sx)*(x'-sx)+(y'-sy)*(y'-sy)\r\n                     float dx = x1-x0, dy = y1-y0;\r\n                     float px = x0-sx, py = y0-sy;\r\n                     // minimize (px+t*dx)^2 + (py+t*dy)^2 = px*px + 2*px*dx*t + t^2*dx*dx + py*py + 2*py*dy*t + t^2*dy*dy\r\n                     // derivative: 2*px*dx + 2*py*dy + (2*dx*dx+2*dy*dy)*t, set to 0 and solve\r\n                     float t = -(px*dx + py*dy) / (dx*dx + dy*dy);\r\n                     if (t >= 0.0f && t <= 1.0f)\r\n                        min_dist = dist;\r\n                  }\r\n               } else if (verts[i].type == STBTT_vcurve) {\r\n                  float x2 = verts[i-1].x *scale_x, y2 = verts[i-1].y *scale_y;\r\n                  float x1 = verts[i  ].cx*scale_x, y1 = verts[i  ].cy*scale_y;\r\n                  float box_x0 = STBTT_min(STBTT_min(x0,x1),x2);\r\n                  float box_y0 = STBTT_min(STBTT_min(y0,y1),y2);\r\n                  float box_x1 = STBTT_max(STBTT_max(x0,x1),x2);\r\n                  float box_y1 = STBTT_max(STBTT_max(y0,y1),y2);\r\n                  // coarse culling against bbox to avoid computing cubic unnecessarily\r\n                  if (sx > box_x0-min_dist && sx < box_x1+min_dist && sy > box_y0-min_dist && sy < box_y1+min_dist) {\r\n                     int num=0;\r\n                     float ax = x1-x0, ay = y1-y0;\r\n                     float bx = x0 - 2*x1 + x2, by = y0 - 2*y1 + y2;\r\n                     float mx = x0 - sx, my = y0 - sy;\r\n                     float res[3],px,py,t,it;\r\n                     float a_inv = precompute[i];\r\n                     if (a_inv == 0.0) { // if a_inv is 0, it's 2nd degree so use quadratic formula\r\n                        float a = 3*(ax*bx + ay*by);\r\n                        float b = 2*(ax*ax + ay*ay) + (mx*bx+my*by);\r\n                        float c = mx*ax+my*ay;\r\n                        if (a == 0.0) { // if a is 0, it's linear\r\n                           if (b != 0.0) {\r\n                              res[num++] = -c/b;\r\n                           }\r\n                        } else {\r\n                           float discriminant = b*b - 4*a*c;\r\n                           if (discriminant < 0)\r\n                              num = 0;\r\n                           else {\r\n                              float root = (float) STBTT_sqrt(discriminant);\r\n                              res[0] = (-b - root)/(2*a);\r\n                              res[1] = (-b + root)/(2*a);\r\n                              num = 2; // don't bother distinguishing 1-solution case, as code below will still work\r\n                           }\r\n                        }\r\n                     } else {\r\n                        float b = 3*(ax*bx + ay*by) * a_inv; // could precompute this as it doesn't depend on sample point\r\n                        float c = (2*(ax*ax + ay*ay) + (mx*bx+my*by)) * a_inv;\r\n                        float d = (mx*ax+my*ay) * a_inv;\r\n                        num = stbtt__solve_cubic(b, c, d, res);\r\n                     }\r\n                     if (num >= 1 && res[0] >= 0.0f && res[0] <= 1.0f) {\r\n                        t = res[0], it = 1.0f - t;\r\n                        px = it*it*x0 + 2*t*it*x1 + t*t*x2;\r\n                        py = it*it*y0 + 2*t*it*y1 + t*t*y2;\r\n                        dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy);\r\n                        if (dist2 < min_dist * min_dist)\r\n                           min_dist = (float) STBTT_sqrt(dist2);\r\n                     }\r\n                     if (num >= 2 && res[1] >= 0.0f && res[1] <= 1.0f) {\r\n                        t = res[1], it = 1.0f - t;\r\n                        px = it*it*x0 + 2*t*it*x1 + t*t*x2;\r\n                        py = it*it*y0 + 2*t*it*y1 + t*t*y2;\r\n                        dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy);\r\n                        if (dist2 < min_dist * min_dist)\r\n                           min_dist = (float) STBTT_sqrt(dist2);\r\n                     }\r\n                     if (num >= 3 && res[2] >= 0.0f && res[2] <= 1.0f) {\r\n                        t = res[2], it = 1.0f - t;\r\n                        px = it*it*x0 + 2*t*it*x1 + t*t*x2;\r\n                        py = it*it*y0 + 2*t*it*y1 + t*t*y2;\r\n                        dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy);\r\n                        if (dist2 < min_dist * min_dist)\r\n                           min_dist = (float) STBTT_sqrt(dist2);\r\n                     }\r\n                  }\r\n               }\r\n            }\r\n            if (winding == 0)\r\n               min_dist = -min_dist;  // if outside the shape, value is negative\r\n            val = onedge_value + pixel_dist_scale * min_dist;\r\n            if (val < 0)\r\n               val = 0;\r\n            else if (val > 255)\r\n               val = 255;\r\n            data[(y-iy0)*w+(x-ix0)] = (unsigned char) val;\r\n         }\r\n      }\r\n      STBTT_free(precompute, info->userdata);\r\n      STBTT_free(verts, info->userdata);\r\n   }\r\n   return data;\r\n}\r\n\r\nSTBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff)\r\n{\r\n   return stbtt_GetGlyphSDF(info, scale, stbtt_FindGlyphIndex(info, codepoint), padding, onedge_value, pixel_dist_scale, width, height, xoff, yoff);\r\n}\r\n\r\nSTBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata)\r\n{\r\n   STBTT_free(bitmap, userdata);\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////////////\r\n//\r\n// font name matching -- recommended not to use this\r\n//\r\n\r\n// check if a utf8 string contains a prefix which is the utf16 string; if so return length of matching utf8 string\r\nstatic stbtt_int32 stbtt__CompareUTF8toUTF16_bigendian_prefix(stbtt_uint8 *s1, stbtt_int32 len1, stbtt_uint8 *s2, stbtt_int32 len2)\r\n{\r\n   stbtt_int32 i=0;\r\n\r\n   // convert utf16 to utf8 and compare the results while converting\r\n   while (len2) {\r\n      stbtt_uint16 ch = s2[0]*256 + s2[1];\r\n      if (ch < 0x80) {\r\n         if (i >= len1) return -1;\r\n         if (s1[i++] != ch) return -1;\r\n      } else if (ch < 0x800) {\r\n         if (i+1 >= len1) return -1;\r\n         if (s1[i++] != 0xc0 + (ch >> 6)) return -1;\r\n         if (s1[i++] != 0x80 + (ch & 0x3f)) return -1;\r\n      } else if (ch >= 0xd800 && ch < 0xdc00) {\r\n         stbtt_uint32 c;\r\n         stbtt_uint16 ch2 = s2[2]*256 + s2[3];\r\n         if (i+3 >= len1) return -1;\r\n         c = ((ch - 0xd800) << 10) + (ch2 - 0xdc00) + 0x10000;\r\n         if (s1[i++] != 0xf0 + (c >> 18)) return -1;\r\n         if (s1[i++] != 0x80 + ((c >> 12) & 0x3f)) return -1;\r\n         if (s1[i++] != 0x80 + ((c >>  6) & 0x3f)) return -1;\r\n         if (s1[i++] != 0x80 + ((c      ) & 0x3f)) return -1;\r\n         s2 += 2; // plus another 2 below\r\n         len2 -= 2;\r\n      } else if (ch >= 0xdc00 && ch < 0xe000) {\r\n         return -1;\r\n      } else {\r\n         if (i+2 >= len1) return -1;\r\n         if (s1[i++] != 0xe0 + (ch >> 12)) return -1;\r\n         if (s1[i++] != 0x80 + ((ch >> 6) & 0x3f)) return -1;\r\n         if (s1[i++] != 0x80 + ((ch     ) & 0x3f)) return -1;\r\n      }\r\n      s2 += 2;\r\n      len2 -= 2;\r\n   }\r\n   return i;\r\n}\r\n\r\nstatic int stbtt_CompareUTF8toUTF16_bigendian_internal(char *s1, int len1, char *s2, int len2)\r\n{\r\n   return len1 == stbtt__CompareUTF8toUTF16_bigendian_prefix((stbtt_uint8*) s1, len1, (stbtt_uint8*) s2, len2);\r\n}\r\n\r\n// returns results in whatever encoding you request... but note that 2-byte encodings\r\n// will be BIG-ENDIAN... use stbtt_CompareUTF8toUTF16_bigendian() to compare\r\nSTBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID)\r\n{\r\n   stbtt_int32 i,count,stringOffset;\r\n   stbtt_uint8 *fc = font->data;\r\n   stbtt_uint32 offset = font->fontstart;\r\n   stbtt_uint32 nm = stbtt__find_table(fc, offset, \"name\");\r\n   if (!nm) return NULL;\r\n\r\n   count = ttUSHORT(fc+nm+2);\r\n   stringOffset = nm + ttUSHORT(fc+nm+4);\r\n   for (i=0; i < count; ++i) {\r\n      stbtt_uint32 loc = nm + 6 + 12 * i;\r\n      if (platformID == ttUSHORT(fc+loc+0) && encodingID == ttUSHORT(fc+loc+2)\r\n          && languageID == ttUSHORT(fc+loc+4) && nameID == ttUSHORT(fc+loc+6)) {\r\n         *length = ttUSHORT(fc+loc+8);\r\n         return (const char *) (fc+stringOffset+ttUSHORT(fc+loc+10));\r\n      }\r\n   }\r\n   return NULL;\r\n}\r\n\r\nstatic int stbtt__matchpair(stbtt_uint8 *fc, stbtt_uint32 nm, stbtt_uint8 *name, stbtt_int32 nlen, stbtt_int32 target_id, stbtt_int32 next_id)\r\n{\r\n   stbtt_int32 i;\r\n   stbtt_int32 count = ttUSHORT(fc+nm+2);\r\n   stbtt_int32 stringOffset = nm + ttUSHORT(fc+nm+4);\r\n\r\n   for (i=0; i < count; ++i) {\r\n      stbtt_uint32 loc = nm + 6 + 12 * i;\r\n      stbtt_int32 id = ttUSHORT(fc+loc+6);\r\n      if (id == target_id) {\r\n         // find the encoding\r\n         stbtt_int32 platform = ttUSHORT(fc+loc+0), encoding = ttUSHORT(fc+loc+2), language = ttUSHORT(fc+loc+4);\r\n\r\n         // is this a Unicode encoding?\r\n         if (platform == 0 || (platform == 3 && encoding == 1) || (platform == 3 && encoding == 10)) {\r\n            stbtt_int32 slen = ttUSHORT(fc+loc+8);\r\n            stbtt_int32 off = ttUSHORT(fc+loc+10);\r\n\r\n            // check if there's a prefix match\r\n            stbtt_int32 matchlen = stbtt__CompareUTF8toUTF16_bigendian_prefix(name, nlen, fc+stringOffset+off,slen);\r\n            if (matchlen >= 0) {\r\n               // check for target_id+1 immediately following, with same encoding & language\r\n               if (i+1 < count && ttUSHORT(fc+loc+12+6) == next_id && ttUSHORT(fc+loc+12) == platform && ttUSHORT(fc+loc+12+2) == encoding && ttUSHORT(fc+loc+12+4) == language) {\r\n                  slen = ttUSHORT(fc+loc+12+8);\r\n                  off = ttUSHORT(fc+loc+12+10);\r\n                  if (slen == 0) {\r\n                     if (matchlen == nlen)\r\n                        return 1;\r\n                  } else if (matchlen < nlen && name[matchlen] == ' ') {\r\n                     ++matchlen;\r\n                     if (stbtt_CompareUTF8toUTF16_bigendian_internal((char*) (name+matchlen), nlen-matchlen, (char*)(fc+stringOffset+off),slen))\r\n                        return 1;\r\n                  }\r\n               } else {\r\n                  // if nothing immediately following\r\n                  if (matchlen == nlen)\r\n                     return 1;\r\n               }\r\n            }\r\n         }\r\n\r\n         // @TODO handle other encodings\r\n      }\r\n   }\r\n   return 0;\r\n}\r\n\r\nstatic int stbtt__matches(stbtt_uint8 *fc, stbtt_uint32 offset, stbtt_uint8 *name, stbtt_int32 flags)\r\n{\r\n   stbtt_int32 nlen = (stbtt_int32) STBTT_strlen((char *) name);\r\n   stbtt_uint32 nm,hd;\r\n   if (!stbtt__isfont(fc+offset)) return 0;\r\n\r\n   // check italics/bold/underline flags in macStyle...\r\n   if (flags) {\r\n      hd = stbtt__find_table(fc, offset, \"head\");\r\n      if ((ttUSHORT(fc+hd+44) & 7) != (flags & 7)) return 0;\r\n   }\r\n\r\n   nm = stbtt__find_table(fc, offset, \"name\");\r\n   if (!nm) return 0;\r\n\r\n   if (flags) {\r\n      // if we checked the macStyle flags, then just check the family and ignore the subfamily\r\n      if (stbtt__matchpair(fc, nm, name, nlen, 16, -1))  return 1;\r\n      if (stbtt__matchpair(fc, nm, name, nlen,  1, -1))  return 1;\r\n      if (stbtt__matchpair(fc, nm, name, nlen,  3, -1))  return 1;\r\n   } else {\r\n      if (stbtt__matchpair(fc, nm, name, nlen, 16, 17))  return 1;\r\n      if (stbtt__matchpair(fc, nm, name, nlen,  1,  2))  return 1;\r\n      if (stbtt__matchpair(fc, nm, name, nlen,  3, -1))  return 1;\r\n   }\r\n\r\n   return 0;\r\n}\r\n\r\nstatic int stbtt_FindMatchingFont_internal(unsigned char *font_collection, char *name_utf8, stbtt_int32 flags)\r\n{\r\n   stbtt_int32 i;\r\n   for (i=0;;++i) {\r\n      stbtt_int32 off = stbtt_GetFontOffsetForIndex(font_collection, i);\r\n      if (off < 0) return off;\r\n      if (stbtt__matches((stbtt_uint8 *) font_collection, off, (stbtt_uint8*) name_utf8, flags))\r\n         return off;\r\n   }\r\n}\r\n\r\n#if defined(__GNUC__) || defined(__clang__)\r\n#pragma GCC diagnostic push\r\n#pragma GCC diagnostic ignored \"-Wcast-qual\"\r\n#endif\r\n\r\nSTBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset,\r\n                                float pixel_height, unsigned char *pixels, int pw, int ph,\r\n                                int first_char, int num_chars, stbtt_bakedchar *chardata)\r\n{\r\n   return stbtt_BakeFontBitmap_internal((unsigned char *) data, offset, pixel_height, pixels, pw, ph, first_char, num_chars, chardata);\r\n}\r\n\r\nSTBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index)\r\n{\r\n   return stbtt_GetFontOffsetForIndex_internal((unsigned char *) data, index);\r\n}\r\n\r\nSTBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data)\r\n{\r\n   return stbtt_GetNumberOfFonts_internal((unsigned char *) data);\r\n}\r\n\r\nSTBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset)\r\n{\r\n   return stbtt_InitFont_internal(info, (unsigned char *) data, offset);\r\n}\r\n\r\nSTBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags)\r\n{\r\n   return stbtt_FindMatchingFont_internal((unsigned char *) fontdata, (char *) name, flags);\r\n}\r\n\r\nSTBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2)\r\n{\r\n   return stbtt_CompareUTF8toUTF16_bigendian_internal((char *) s1, len1, (char *) s2, len2);\r\n}\r\n\r\n#if defined(__GNUC__) || defined(__clang__)\r\n#pragma GCC diagnostic pop\r\n#endif\r\n\r\n#endif // STB_TRUETYPE_IMPLEMENTATION\r\n\r\n\r\n// FULL VERSION HISTORY\r\n//\r\n//   1.19 (2018-02-11) OpenType GPOS kerning (horizontal only), STBTT_fmod\r\n//   1.18 (2018-01-29) add missing function\r\n//   1.17 (2017-07-23) make more arguments const; doc fix\r\n//   1.16 (2017-07-12) SDF support\r\n//   1.15 (2017-03-03) make more arguments const\r\n//   1.14 (2017-01-16) num-fonts-in-TTC function\r\n//   1.13 (2017-01-02) support OpenType fonts, certain Apple fonts\r\n//   1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual\r\n//   1.11 (2016-04-02) fix unused-variable warning\r\n//   1.10 (2016-04-02) allow user-defined fabs() replacement\r\n//                     fix memory leak if fontsize=0.0\r\n//                     fix warning from duplicate typedef\r\n//   1.09 (2016-01-16) warning fix; avoid crash on outofmem; use alloc userdata for PackFontRanges\r\n//   1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges\r\n//   1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints;\r\n//                     allow PackFontRanges to pack and render in separate phases;\r\n//                     fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?);\r\n//                     fixed an assert() bug in the new rasterizer\r\n//                     replace assert() with STBTT_assert() in new rasterizer\r\n//   1.06 (2015-07-14) performance improvements (~35% faster on x86 and x64 on test machine)\r\n//                     also more precise AA rasterizer, except if shapes overlap\r\n//                     remove need for STBTT_sort\r\n//   1.05 (2015-04-15) fix misplaced definitions for STBTT_STATIC\r\n//   1.04 (2015-04-15) typo in example\r\n//   1.03 (2015-04-12) STBTT_STATIC, fix memory leak in new packing, various fixes\r\n//   1.02 (2014-12-10) fix various warnings & compile issues w/ stb_rect_pack, C++\r\n//   1.01 (2014-12-08) fix subpixel position when oversampling to exactly match\r\n//                        non-oversampled; STBTT_POINT_SIZE for packed case only\r\n//   1.00 (2014-12-06) add new PackBegin etc. API, w/ support for oversampling\r\n//   0.99 (2014-09-18) fix multiple bugs with subpixel rendering (ryg)\r\n//   0.9  (2014-08-07) support certain mac/iOS fonts without an MS platformID\r\n//   0.8b (2014-07-07) fix a warning\r\n//   0.8  (2014-05-25) fix a few more warnings\r\n//   0.7  (2013-09-25) bugfix: subpixel glyph bug fixed in 0.5 had come back\r\n//   0.6c (2012-07-24) improve documentation\r\n//   0.6b (2012-07-20) fix a few more warnings\r\n//   0.6  (2012-07-17) fix warnings; added stbtt_ScaleForMappingEmToPixels,\r\n//                        stbtt_GetFontBoundingBox, stbtt_IsGlyphEmpty\r\n//   0.5  (2011-12-09) bugfixes:\r\n//                        subpixel glyph renderer computed wrong bounding box\r\n//                        first vertex of shape can be off-curve (FreeSans)\r\n//   0.4b (2011-12-03) fixed an error in the font baking example\r\n//   0.4  (2011-12-01) kerning, subpixel rendering (tor)\r\n//                    bugfixes for:\r\n//                        codepoint-to-glyph conversion using table fmt=12\r\n//                        codepoint-to-glyph conversion using table fmt=4\r\n//                        stbtt_GetBakedQuad with non-square texture (Zer)\r\n//                    updated Hello World! sample to use kerning and subpixel\r\n//                    fixed some warnings\r\n//   0.3  (2009-06-24) cmap fmt=12, compound shapes (MM)\r\n//                    userdata, malloc-from-userdata, non-zero fill (stb)\r\n//   0.2  (2009-03-11) Fix unsigned/signed char warnings\r\n//   0.1  (2009-03-09) First public release\r\n//\r\n\r\n/*\r\n------------------------------------------------------------------------------\r\nThis software is available under 2 licenses -- choose whichever you prefer.\r\n------------------------------------------------------------------------------\r\nALTERNATIVE A - MIT License\r\nCopyright (c) 2017 Sean Barrett\r\nPermission is hereby granted, free of charge, to any person obtaining a copy of\r\nthis software and associated documentation files (the \"Software\"), to deal in\r\nthe Software without restriction, including without limitation the rights to\r\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\r\nof the Software, and to permit persons to whom the Software is furnished to do\r\nso, subject to the following conditions:\r\nThe above copyright notice and this permission notice shall be included in all\r\ncopies or substantial portions of the Software.\r\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\nSOFTWARE.\r\n------------------------------------------------------------------------------\r\nALTERNATIVE B - Public Domain (www.unlicense.org)\r\nThis is free and unencumbered software released into the public domain.\r\nAnyone is free to copy, modify, publish, use, compile, sell, or distribute this\r\nsoftware, either in source code form or as a compiled binary, for any purpose,\r\ncommercial or non-commercial, and by any means.\r\nIn jurisdictions that recognize copyright laws, the author or authors of this\r\nsoftware dedicate any and all copyright interest in the software to the public\r\ndomain. We make this dedication for the benefit of the public at large and to\r\nthe detriment of our heirs and successors. We intend this dedication to be an\r\novert act of relinquishment in perpetuity of all present and future rights to\r\nthis software under copyright law.\r\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\nAUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\r\nACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\r\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n------------------------------------------------------------------------------\r\n*/\r\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/imgui_markdown/License.txt",
    "content": "Copyright (c) 2019 Juliette Foucaut and Doug Binks\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 acknowledgement 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."
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/imgui_markdown/README.md",
    "content": "Support development of imgui_markdown through our [Patreon](https://www.patreon.com/enkisoftware)\n\n[<img src=\"https://c5.patreon.com/external/logo/become_a_patron_button@2x.png\" alt=\"Become a Patron\" width=\"150\"/>](https://www.patreon.com/enkisoftware)\n\n# imgui_markdown\n\n## Markdown for Dear ImGui\n\nA permissively licensed markdown single-header library for [Dear ImGui](https://github.com/ocornut/imgui).\n\nCurrently requires C++14\n\nimgui_markdown currently supports the following markdown functionality:\n\n  * Wrapped text\n  * Headers H1, H2, H3\n  * Indented text, multi levels\n  * Unordered lists and sub-lists\n  * Links\n  * Images\n\n![imgui_markdown demo live editing](https://github.com/juliettef/Media/blob/master/imgui_markdown_demo_live_editing.gif)\n\n*Note - the gif above is heavily compressed due to GitHub limitations. There's a [(slightly) better version of it on twitter](https://twitter.com/juulcat/status/1090996799266000898).*\n\n## Syntax\n\n### Wrapping\nText wraps automatically. To add a new line, use 'Return'.\n### Headers\n```\n# H1\n## H2\n### H3\n```\n### Lists\n#### Indents\nOn a new line, at the start of the line, add two spaces per indent.\n```\nNormal text\n··Indent level 1\n····Indent level 2\n······Indent level 3\nNormal text\n```\n#### Unordered lists\nOn a new line, at the start of the line, add two spaces, an asterisks and a space. For nested lists, add two additional spaces in front of the asterisk per list level increment.\n```\nNormal text\n··*·Unordered List level 1\n····*·Unordered List level 2\n······*·Unordered List level 3\n······*·Unordered List level 3\n··*·Unordered List level 1\nNormal text\n```\n### Links\n```\n[link description](https://...)\n```\n### Images\n```\n![image alt text](image identifier e.g. filename)\n```\n\n\n![Example use of imgui_markdown with icon fonts](https://github.com/juliettef/Media/blob/master/imgui_markdown_icon_font.jpg)\n\n## Example use on Windows with links opening in a browser\n\n```Cpp\n\n#include \"ImGui.h\"                // https://github.com/ocornut/imgui\n#include \"imgui_markdown.h\"       // https://github.com/juliettef/imgui_markdown\n#include \"IconsFontAwesome5.h\"    // https://github.com/juliettef/IconFontCppHeaders\n\n// Following includes for Windows LinkCallback\n#define WIN32_LEAN_AND_MEAN\n#include <Windows.h>\n#include \"Shellapi.h\"\n#include <string>\n\nvoid LinkCallback( ImGui::MarkdownLinkCallbackData data_ );\ninline ImGui::MarkdownImageData ImageCallback( ImGui::MarkdownLinkCallbackData data_ );\n\n// You can make your own Markdown function with your prefered string container and markdown config.\nstatic ImGui::MarkdownConfig mdConfig{ LinkCallback, NULL, ImageCallback, ICON_FA_LINK, { { NULL, true }, { NULL, true }, { NULL, false } }, NULL };\n\nvoid LinkCallback( ImGui::MarkdownLinkCallbackData data_ )\n{\n    std::string url( data_.link, data_.linkLength );\n    if( !data_.isImage )\n    {\n        ShellExecuteA( NULL, \"open\", url.c_str(), NULL, NULL, SW_SHOWNORMAL );\n    }\n}\n\ninline ImGui::MarkdownImageData ImageCallback( ImGui::MarkdownLinkCallbackData data_ )\n{\n    // In your application you would load an image based on data_ input. Here we just use the imgui font texture.\n    ImTextureID image = ImGui::GetIO().Fonts->TexID;\n    ImGui::MarkdownImageData imageData{ true, false, image, ImVec2( 40.0f, 20.0f ) };\n    return imageData;\n}\n\nvoid LoadFonts( float fontSize_ = 12.0f )\n{\n    ImGuiIO& io = ImGui::GetIO();\n    io.Fonts->Clear();\n    // Base font\n    io.Fonts->AddFontFromFileTTF( \"myfont.ttf\", fontSize_ );\n    // Bold headings H2 and H3\n    mdConfig.headingFormats[ 1 ].font = io.Fonts->AddFontFromFileTTF( \"myfont-bold.ttf\", fontSize_ );\n    mdConfig.headingFormats[ 2 ].font = mdConfig.headingFormats[ 1 ].font;\n    // bold heading H1\n    float fontSizeH1 = fontSize_ * 1.1f;\n    mdConfig.headingFormats[ 0 ].font = io.Fonts->AddFontFromFileTTF( \"myfont-bold.ttf\", fontSizeH1 );\n}\n\nvoid Markdown( const std::string& markdown_ )\n{\n    // fonts for, respectively, headings H1, H2, H3 and beyond\n    ImGui::Markdown( markdown_.c_str(), markdown_.length(), mdConfig );\n}\n\nvoid MarkdownExample()\n{\n    const std::string markdownText = u8R\"(\n# H1 Header: Text and Links\nYou can add [links like this one to enkisoftware](https://www.enkisoftware.com/) and lines will wrap well.\n## H2 Header: indented text.\n  This text has an indent (two leading spaces).\n    This one has two.\n### H3 Header: Lists\n  * Unordered lists\n    * Lists can be indented with two extra spaces.\n  * Lists can have [links like this one to Avoyd](https://www.avoyd.com/)\n)\";\n    Markdown( markdownText );\n}\n```\n\n## Projects using imgui_markdown\n\n### [Avoyd](https://www.enkisoftware.com/avoyd)\nAvoyd is an abstract 6 degrees of freedom voxel game.  \n[www.avoyd.com](https://www.avoyd.com)  \n\nThe game and the voxel editor's help and tutorials use imgui_markdown with Dear ImGui.  \n\n![Avoyd screenshot](https://github.com/juliettef/Media/blob/master/imgui_markdown_Avoyd_about_OSS.png?raw=true)\n\n### [bgfx](https://github.com/bkaradzic/bgfx)\nCross-platform rendering library.  \n[bkaradzic.github.io/bgfx/overview](https://bkaradzic.github.io/bgfx/overview.html)\n\n### [Imogen](https://github.com/CedricGuillemet/Imogen)\nGPU/CPU Texture Generator  \n[skaven.fr/imogen](http://skaven.fr/imogen/)\n\n![Imogen screenshot](https://camo.githubusercontent.com/28347bc0c1627aa4f289e1b2b769afcb3a5de370/68747470733a2f2f692e696d6775722e636f6d2f7351664f3542722e706e67)\n\n### [Light Tracer](https://lighttracer.org/)\nExperimental GPU ray tracer for web\n\n![Light Tracer screenshot](https://github.com/juliettef/Media/blob/master/imgui_markdown_Light_Tracer.png?raw=true)\n\n### [Visual 6502 Remix](https://github.com/floooh/v6502r)\nTransistor level 6502 Hardware Simulation  \n[hfloooh.github.io/visual6502remix](https://floooh.github.io/visual6502remix/)  \n\nUsing imgui_markdown as help viewer for Visual 6502 Remix with internal and external links: \n \n[![Using imgui_markdown as help viewer for Visual 6502 Remix with internal and external links - animated gif](https://user-images.githubusercontent.com/1699414/69185510-320baa00-0b17-11ea-9fd5-82ed6e02a05c.gif)\n![Using imgui_markdown as help viewer for Visual 6502 Remix - screenshot](https://user-images.githubusercontent.com/1699414/69185626-67b09300-0b17-11ea-85a8-fed54a0082b4.png)](https://github.com/ocornut/imgui/issues/2847#issuecomment-555710973)  \n\n![Using imgui_markdown in the About page for Visual 6502 Remix - screenshot](https://github.com/juliettef/Media/blob/master/imgui_markdown_Visual_6502_Remix_About.png?raw=true)\n\n## Credits\n\nDesign and implementation - [Doug Binks](http://www.enkisoftware.com/about.html#doug) - [@dougbinks](https://github.com/dougbinks)  \nImplementation and maintenance - [Juliette Foucaut](http://www.enkisoftware.com/about.html#juliette) - [@juliettef](https://github.com/juliettef)  \nThanks to [Omar Cornut for Dear ImGui](https://github.com/ocornut/imgui).\n\n## License (zlib)\n\nCopyright (c) 2019 Juliette Foucaut and Doug Binks\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"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/imgui_markdown/imgui_markdown.h",
    "content": "#pragma once\n\n// License: zlib\n// Copyright (c) 2019 Juliette Foucaut & Doug Binks\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/*\nAPI BREAKING CHANGES\n====================\n- 2020/04/22 - Added tooltipCallback parameter to ImGui::MarkdownConfig\n- 2019/02/01 - Changed LinkCallback parameters, see https://github.com/juliettef/imgui_markdown/issues/2\n- 2019/02/05 - Added imageCallback parameter to ImGui::MarkdownConfig\n- 2019/02/06 - Added useLinkCallback member variable to MarkdownImageData to configure using images as links\n*/\n\n/*\nimgui_markdown https://github.com/juliettef/imgui_markdown\nMarkdown for Dear ImGui\n\nA permissively licensed markdown single-header library for https://github.com/ocornut/imgui\n\nCurrently requires C++14\n\nimgui_markdown currently supports the following markdown functionality:\n - Wrapped text\n - Headers H1, H2, H3\n - Indented text, multi levels\n - Unordered lists and sub-lists\n - Links\n - Images\n \nSyntax\n\nWrapping: \nText wraps automatically. To add a new line, use 'Return'.\n\nHeaders:\n# H1\n## H2\n### H3\n\nIndents: \nOn a new line, at the start of the line, add two spaces per indent.\nIndent level 1\nIndent level 2\n\nUnordered lists: \nOn a new line, at the start of the line, add two spaces, an asterisks and a space. \nFor nested lists, add two additional spaces in front of the asterisk per list level increment.\n*Unordered List level 1\n*Unordered List level 2\n\nLinks:\n[link description](https://...)\n\nImages:\n![image alt text](image identifier e.g. filename)\n\n===============================================================================\n\n// Example use on Windows with links opening in a browser\n\n#include \"ImGui.h\"                // https://github.com/ocornut/imgui\n#include \"imgui_markdown.h\"       // https://github.com/juliettef/imgui_markdown\n#include \"IconsFontAwesome5.h\"    // https://github.com/juliettef/IconFontCppHeaders\n\n// Following includes for Windows LinkCallback\n#define WIN32_LEAN_AND_MEAN\n#include <Windows.h>\n#include \"Shellapi.h\"\n#include <string>\n\nvoid LinkCallback( ImGui::MarkdownLinkCallbackData data_ );\ninline ImGui::MarkdownImageData ImageCallback( ImGui::MarkdownLinkCallbackData data_ );\n\n// You can make your own Markdown function with your prefered string container and markdown config.\nstatic ImGui::MarkdownConfig mdConfig{ LinkCallback, NULL, ImageCallback, ICON_FA_LINK, { { NULL, true }, { NULL, true }, { NULL, false } }, NULL };\n\nvoid LinkCallback( ImGui::MarkdownLinkCallbackData data_ )\n{\n    std::string url( data_.link, data_.linkLength );\n    if( !data_.isImage )\n    {\n        ShellExecuteA( NULL, \"open\", url.c_str(), NULL, NULL, SW_SHOWNORMAL );\n    }\n}\n\ninline ImGui::MarkdownImageData ImageCallback( ImGui::MarkdownLinkCallbackData data_ )\n{\n    // In your application you would load an image based on data_ input. Here we just use the imgui font texture.\n    ImTextureID image = ImGui::GetIO().Fonts->TexID;\n    ImGui::MarkdownImageData imageData{ true, false, image, ImVec2( 40.0f, 20.0f ) };\n    return imageData;\n}\n\nvoid LoadFonts( float fontSize_ = 12.0f )\n{\n    ImGuiIO& io = ImGui::GetIO();\n    io.Fonts->Clear();\n    // Base font\n    io.Fonts->AddFontFromFileTTF( \"myfont.ttf\", fontSize_ );\n    // Bold headings H2 and H3\n    mdConfig.headingFormats[ 1 ].font = io.Fonts->AddFontFromFileTTF( \"myfont-bold.ttf\", fontSize_ );\n    mdConfig.headingFormats[ 2 ].font = mdConfig.headingFormats[ 1 ].font;\n    // bold heading H1\n    float fontSizeH1 = fontSize_ * 1.1f;\n    mdConfig.headingFormats[ 0 ].font = io.Fonts->AddFontFromFileTTF( \"myfont-bold.ttf\", fontSizeH1 );\n}\n\nvoid Markdown( const std::string& markdown_ )\n{\n    // fonts for, respectively, headings H1, H2, H3 and beyond\n    ImGui::Markdown( markdown_.c_str(), markdown_.length(), mdConfig );\n}\n\nvoid MarkdownExample()\n{\n    const std::string markdownText = u8R\"(\n# H1 Header: Text and Links\nYou can add [links like this one to enkisoftware](https://www.enkisoftware.com/) and lines will wrap well.\n## H2 Header: indented text.\n  This text has an indent (two leading spaces).\n    This one has two.\n### H3 Header: Lists\n  * Unordered lists\n    * Lists can be indented with two extra spaces.\n  * Lists can have [links like this one to Avoyd](https://www.avoyd.com/)\n)\";\n    Markdown( markdownText );\n}\n\n===============================================================================\n*/\n\n\n#include <stdint.h>\n\nnamespace ImGui\n{\n    //-----------------------------------------------------------------------------\n    // Basic types\n    //-----------------------------------------------------------------------------\n\n    struct Link;\n    struct MarkdownConfig;\n\n    struct MarkdownLinkCallbackData                                 // for both links and images\n    {\n        const char*             text;                               // text between square brackets []\n        int                     textLength;\n        const char*             link;                               // text between brackets ()\n        int                     linkLength;\n        void*                   userData;\n        bool                    isImage;                            // true if '!' is detected in front of the link syntax\n    };\n\n    struct MarkdownTooltipCallbackData                              // for tooltips\n    {\n        MarkdownLinkCallbackData linkData;\n        const char*              linkIcon;\n    };\n    \n    struct MarkdownImageData\n    {\n        bool                    isValid = false;                    // if true, will draw the image\n        bool                    useLinkCallback = false;            // if true, linkCallback will be called when image is clicked\n        ImTextureID             user_texture_id;                    // see ImGui::Image\n        const ImVec2&           size;                               // see ImGui::Image\n        const ImVec2&           uv0 = ImVec2( 0, 0 );               // see ImGui::Image\n        const ImVec2&           uv1 = ImVec2( 1, 1 );               // see ImGui::Image\n        const ImVec4&           tint_col = ImVec4( 1, 1, 1, 1 );    // see ImGui::Image\n        const ImVec4&           border_col = ImVec4( 0, 0, 0, 0 );  // see ImGui::Image\n    };\n\n    typedef void                MarkdownLinkCallback( MarkdownLinkCallbackData data );    \n    typedef void                MarkdownTooltipCallback( MarkdownTooltipCallbackData data );\n\n    inline void defaultMarkdownTooltipCallback( MarkdownTooltipCallbackData data_ )\n    {\n        if( data_.linkData.isImage )\n        {\n            ImGui::SetTooltip( \"%.*s\", data_.linkData.linkLength, data_.linkData.link );\n        }\n        else\n        {\n            ImGui::SetTooltip( \"%s Open in browser\\n%.*s\", data_.linkIcon, data_.linkData.linkLength, data_.linkData.link );\n        }\n    }\n\n    typedef MarkdownImageData   MarkdownImageCallback( MarkdownLinkCallbackData data );\n\n    struct MarkdownHeadingFormat\n    {   \n        ImFont*                 font;                               // ImGui font\n        bool                    separator;                          // if true, an underlined separator is drawn after the header\n    };\n\n    // Configuration struct for Markdown\n    // - linkCallback is called when a link is clicked on\n    // - linkIcon is a string which encode a \"Link\" icon, if available in the current font (e.g. linkIcon = ICON_FA_LINK with FontAwesome + IconFontCppHeaders https://github.com/juliettef/IconFontCppHeaders)\n    // - HeadingFormat controls the format of heading H1 to H3, those above H3 use H3 format\n    struct MarkdownConfig\n    {\n        static const int        NUMHEADINGS = 3;\n\n        MarkdownLinkCallback*   linkCallback = NULL;\n        MarkdownTooltipCallback* tooltipCallback = NULL;\n        MarkdownImageCallback*  imageCallback = NULL;\n        const char*             linkIcon = \"\";                      // icon displayd in link tooltip\n        MarkdownHeadingFormat   headingFormats[ NUMHEADINGS ] = { { NULL, true }, { NULL, true }, { NULL, true } };\n        void*                   userData = NULL;\n    };\n\n    //-----------------------------------------------------------------------------\n    // External interface\n    //-----------------------------------------------------------------------------\n\n    inline void Markdown( const char* markdown_, size_t markdownLength_, const MarkdownConfig& mdConfig_ );\n\n    //-----------------------------------------------------------------------------\n    // Internals\n    //-----------------------------------------------------------------------------\n\n    struct TextRegion;\n    struct Line;\n    inline void UnderLine( ImColor col_ );\n    inline void RenderLine( const char* markdown_, Line& line_, TextRegion& textRegion_, const MarkdownConfig& mdConfig_ );\n\n    struct TextRegion\n    {\n        TextRegion() : indentX( 0.0f )\n        {\n        }\n        ~TextRegion()\n        {\n            ResetIndent();\n        }\n\n        // ImGui::TextWrapped will wrap at the starting position\n        // so to work around this we render using our own wrapping for the first line\n        void RenderTextWrapped( const char* text_, const char* text_end_, bool bIndentToHere_ = false )\n        {\n            const float scale = 1.0f;\n            float       widthLeft = GetContentRegionAvail().x;\n            const char* endLine = ImGui::GetFont()->CalcWordWrapPositionA( scale, text_, text_end_, widthLeft );\n            ImGui::TextUnformatted( text_, endLine );\n            if( bIndentToHere_ )\n            {\n                float indentNeeded = GetContentRegionAvail().x - widthLeft;\n                if( indentNeeded )\n                {\n                    ImGui::Indent( indentNeeded );\n                    indentX += indentNeeded;\n                }\n            }\n            widthLeft = GetContentRegionAvail().x;\n            while( endLine < text_end_ )\n            {\n                text_ = endLine;\n                if( *text_ == ' ' ) { ++text_; }    // skip a space at start of line\n                endLine = ImGui::GetFont()->CalcWordWrapPositionA( scale, text_, text_end_, widthLeft );\n                if( text_ == endLine ) \n                {\n                    endLine++;\n                }\n                ImGui::TextUnformatted( text_, endLine );\n            }\n        }\n\n        void RenderListTextWrapped( const char* text_, const char* text_end_ )\n        {\n            ImGui::Bullet();\n            ImGui::SameLine();\n            RenderTextWrapped( text_, text_end_, true );\n        }\n\n        bool RenderLinkText( const char* text_, const char* text_end_, const Link& link_, const ImGuiStyle& style_, \n            const char* markdown_, const MarkdownConfig& mdConfig_, const char** linkHoverStart_ );\n\n        void RenderLinkTextWrapped( const char* text_, const char* text_end_, const Link& link_, const ImGuiStyle& style_,\n            const char* markdown_, const MarkdownConfig& mdConfig_, const char** linkHoverStart_, bool bIndentToHere_ = false );\n\n        void ResetIndent()\n        {\n            if( indentX > 0.0f )\n            {\n                ImGui::Unindent( indentX );\n            }\n            indentX = 0.0f;\n        }\n\n    private:\n        float       indentX;\n    };\n\n    // Text that starts after a new line (or at beginning) and ends with a newline (or at end)\n    struct Line {\n        bool isHeading = false;\n        bool isUnorderedListStart = false;\n        bool isLeadingSpace = true;     // spaces at start of line\n        int  leadSpaceCount = 0;\n        int  headingCount = 0;\n        int  lineStart = 0;\n        int  lineEnd   = 0;\n        int  lastRenderPosition = 0;     // lines may get rendered in multiple pieces\n    };\n\n    struct TextBlock {                  // subset of line\n        int start = 0;\n        int stop  = 0;\n        int size() const\n        {\n            return stop - start;\n        }\n    };\n\n    struct Link {\n        enum LinkState {\n            NO_LINK,\n            HAS_SQUARE_BRACKET_OPEN,\n            HAS_SQUARE_BRACKETS,\n            HAS_SQUARE_BRACKETS_ROUND_BRACKET_OPEN,\n        };\n        LinkState state = NO_LINK;\n        TextBlock text;\n        TextBlock url;\n        bool isImage = false;\n    };\n\n    inline void UnderLine( ImColor col_ )\n    {\n        ImVec2 min = ImGui::GetItemRectMin();\n        ImVec2 max = ImGui::GetItemRectMax();\n        min.y = max.y;\n        ImGui::GetWindowDrawList()->AddLine( min, max, col_, 1.0f );\n    }\n\n    inline void RenderLine( const char* markdown_, Line& line_, TextRegion& textRegion_, const MarkdownConfig& mdConfig_ )\n    {\n        // indent\n        int indentStart = 0;\n        if( line_.isUnorderedListStart )    // ImGui unordered list render always adds one indent\n        { \n            indentStart = 1; \n        }\n        for( int j = indentStart; j < line_.leadSpaceCount / 2; ++j )    // add indents\n        {\n            ImGui::Indent();\n        }\n\n        // render\n        int textStart = line_.lastRenderPosition + 1;\n        int textSize = line_.lineEnd - textStart;\n        if( line_.isUnorderedListStart )    // render unordered list\n        {\n            const char* text = markdown_ + textStart + 1;\n            textRegion_.RenderListTextWrapped( text, text + textSize - 1 );\n        }\n        else if( line_.isHeading )          // render heading\n        {\n            MarkdownHeadingFormat fmt;\n            if( line_.headingCount > mdConfig_.NUMHEADINGS )\n            {\n                fmt = mdConfig_.headingFormats[ mdConfig_.NUMHEADINGS - 1 ];\n            }\n            else\n            {\n                 fmt = mdConfig_.headingFormats[ line_.headingCount - 1 ];\n            }\n\n            bool popFontRequired = false;\n            if( fmt.font && fmt.font != ImGui::GetFont() )\n            {\n                ImGui::PushFont( fmt.font );\n                popFontRequired = true;\n            }\n            const char* text = markdown_ + textStart + 1;\n            ImGui::NewLine();\n            textRegion_.RenderTextWrapped( text, text + textSize - 1 );\n            if( fmt.separator )\n            {\n                ImGui::Separator();\n            }\n            ImGui::NewLine();\n            if( popFontRequired )\n            {\n                ImGui::PopFont();\n            }\n        }\n        else                                // render a normal paragraph chunk\n        {\n            const char* text = markdown_ + textStart;\n            textRegion_.RenderTextWrapped( text, text + textSize );\n        }\n            \n        // unindent\n        for( int j = indentStart; j < line_.leadSpaceCount / 2; ++j )\n        {\n            ImGui::Unindent();\n        }\n    }\n    \n    // render markdown\n    inline void Markdown( const char* markdown_, size_t markdownLength_, const MarkdownConfig& mdConfig_ )\n    {\n        static const char* linkHoverStart = NULL; // we need to preserve status of link hovering between frames\n        ImGuiStyle& style = ImGui::GetStyle();\n        Line        line;\n        Link        link;\n        TextRegion  textRegion;\n\n        char c = 0;\n        for( int i=0; i < (int)markdownLength_; ++i )\n        {\n            c = markdown_[i];               // get the character at index\n            if( c == 0 ) { break; }         // shouldn't happen but don't go beyond 0.\n\n            // If we're at the beginning of the line, count any spaces\n            if( line.isLeadingSpace )\n            {\n                if( c == ' ' )\n                {\n                    ++line.leadSpaceCount;\n                    continue;\n                }\n                else\n                {\n                    line.isLeadingSpace = false;\n                    line.lastRenderPosition = i - 1;\n                    if(( c == '*' ) && ( line.leadSpaceCount >= 2 ))\n                    {\n                        if(( (int)markdownLength_ > i + 1 ) && ( markdown_[ i + 1 ] == ' ' ))    // space after '*'\n                        {\n                            line.isUnorderedListStart = true;\n                            ++i;\n                            ++line.lastRenderPosition;\n                        }\n                        continue;\n                    }\n                    else if( c == '#' )\n                    {\n                        line.headingCount++;\n                        bool bContinueChecking = true;\n                        uint32_t j = i;\n                        while( ++j < (int)markdownLength_ && bContinueChecking )\n                        {\n                            c = markdown_[j];\n                            switch( c )\n                            {\n                            case '#':\n                                line.headingCount++;\n                                break;\n                            case ' ':\n                                line.lastRenderPosition = j - 1;\n                                i = j;\n                                line.isHeading = true;\n                                bContinueChecking = false;\n                                break;\n                            default:\n                                line.isHeading = false;\n                                bContinueChecking = false;\n                                break;\n                            }\n                        }\n                        if( line.isHeading ) { continue; }\n                    }\n                }\n            }\n\n            // Test to see if we have a link\n            switch( link.state )\n            {\n            case Link::NO_LINK:\n                if( c == '[' )\n                {\n                    link.state = Link::HAS_SQUARE_BRACKET_OPEN;\n                    link.text.start = i + 1;\n                    if( i > 0 && markdown_[i - 1] == '!' )\n                    {\n                        link.isImage = true;\n                    }\n                }\n                break;\n            case Link::HAS_SQUARE_BRACKET_OPEN:\n                if( c == ']' )\n                {\n                    link.state = Link::HAS_SQUARE_BRACKETS;\n                    link.text.stop = i;\n                }\n                break;\n            case Link::HAS_SQUARE_BRACKETS:\n                if( c == '(' )\n                {\n                    link.state = Link::HAS_SQUARE_BRACKETS_ROUND_BRACKET_OPEN;\n                    link.url.start = i + 1;\n                }\n                break;\n            case Link::HAS_SQUARE_BRACKETS_ROUND_BRACKET_OPEN:\n                if( c == ')' )\n                {\n                    // render previous line content\n                    line.lineEnd = link.text.start - ( link.isImage ? 2 : 1 );\n                    RenderLine( markdown_, line, textRegion, mdConfig_ );\n                    line.leadSpaceCount = 0;\n                    link.url.stop = i;\n                    line.isUnorderedListStart = false;    // the following text shouldn't have bullets\n                    ImGui::SameLine( 0.0f, 0.0f );\n                    if( link.isImage )   // it's an image, render it.\n                    {\n                        bool drawnImage = false;\n                        bool useLinkCallback = false;\n                        if( mdConfig_.imageCallback )\n                        {\n                            MarkdownImageData imageData = mdConfig_.imageCallback({ markdown_ + link.text.start, link.text.size(), markdown_ + link.url.start, link.url.size(), mdConfig_.userData, true });\n                            useLinkCallback = imageData.useLinkCallback;\n                            if( imageData.isValid )\n                            {\n                                ImGui::Image( imageData.user_texture_id, imageData.size, imageData.uv0, imageData.uv1, imageData.tint_col, imageData.border_col );\n                                drawnImage = true;\n                            }\n                        }\n                        if( !drawnImage )\n                        {\n                            ImGui::Text( \"( Image %.*s not loaded )\", link.url.size(), markdown_ + link.url.start );\n                        }\n                        if( ImGui::IsItemHovered() )\n                        {\n                            if( ImGui::IsMouseClicked( 0 ) && mdConfig_.linkCallback && useLinkCallback )\n                            {\n                                mdConfig_.linkCallback( { markdown_ + link.text.start, link.text.size(), markdown_ + link.url.start, link.url.size(), mdConfig_.userData, true } );\n                            }\n                            if( link.text.size() > 0 && mdConfig_.tooltipCallback )\n                            {\n                                mdConfig_.tooltipCallback( {{ markdown_ + link.text.start, link.text.size(), markdown_ + link.url.start, link.url.size(), mdConfig_.userData, true }, mdConfig_.linkIcon } );\n                            }\n                        }\n                    }\n                    else                 // it's a link, render it.\n                    {\n                        textRegion.RenderLinkTextWrapped( markdown_ + link.text.start, markdown_ + link.text.start + link.text.size(), link, style, markdown_, mdConfig_, &linkHoverStart, false );\n                    }\n                    ImGui::SameLine( 0.0f, 0.0f );\n                    // reset the link by reinitializing it\n                    link = Link();\n                    line.lastRenderPosition = i;\n                    break;\n                }\n            }\n\n            // handle end of line (render)\n            if( c == '\\n' )\n            {\n                // render the line\n                line.lineEnd = i;\n                RenderLine( markdown_, line, textRegion, mdConfig_ );\n\n                // reset the line\n                line = Line();\n                line.lineStart = i + 1;\n                line.lastRenderPosition = i;\n\n                textRegion.ResetIndent();\n                \n                // reset the link\n                link = Link();\n            }\n        }\n\n        // render any remaining text if last char wasn't 0\n        if( markdownLength_ && line.lineStart < (int)markdownLength_ && markdown_[ line.lineStart ] != 0 )\n        {\n            // handle both null terminated and non null terminated strings\n            line.lineEnd = (int)markdownLength_;\n            if( 0 == markdown_[ line.lineEnd - 1 ] )\n            {\n                --line.lineEnd;\n            }\n            RenderLine( markdown_, line, textRegion, mdConfig_ );\n        }\n    }\n\n\n    inline bool TextRegion::RenderLinkText( const char* text_, const char* text_end_, const Link& link_, const ImGuiStyle& style_,\n        const char* markdown_, const MarkdownConfig& mdConfig_, const char** linkHoverStart_ )\n    {\n        ImGui::PushStyleColor( ImGuiCol_Text, style_.Colors[ImGuiCol_ButtonHovered] );\n        ImGui::PushTextWrapPos( -1.0f );\n        ImGui::TextUnformatted( text_, text_end_ );\n        ImGui::PopTextWrapPos();\n        ImGui::PopStyleColor();\n\n        bool bThisItemHovered = ImGui::IsItemHovered();\n        if(bThisItemHovered)\n        {\n            *linkHoverStart_ = markdown_ + link_.text.start;\n        }\n        bool bHovered = bThisItemHovered || ( *linkHoverStart_ == ( markdown_ + link_.text.start ) );\n\n        if(bHovered)\n        {\n            if(ImGui::IsMouseClicked( 0 ) && mdConfig_.linkCallback)\n            {\n                mdConfig_.linkCallback( { markdown_ + link_.text.start, link_.text.size(), markdown_ + link_.url.start, link_.url.size(), mdConfig_.userData, false } );\n            }\n            ImGui::UnderLine( style_.Colors[ImGuiCol_ButtonHovered] );\n            if( mdConfig_.tooltipCallback )\n            {\n                mdConfig_.tooltipCallback( {{ markdown_ + link_.text.start, link_.text.size(), markdown_ + link_.url.start, link_.url.size(), mdConfig_.userData, false }, mdConfig_.linkIcon } );\n            }\n        }\n        else\n        {\n            ImGui::UnderLine( style_.Colors[ImGuiCol_Button] );\n        }\n        return bThisItemHovered;\n    }\n\n    inline void TextRegion::RenderLinkTextWrapped( const char* text_, const char* text_end_, const Link& link_, const ImGuiStyle& style_,\n        const char* markdown_, const MarkdownConfig& mdConfig_, const char** linkHoverStart_, bool bIndentToHere_ )\n        {\n            const float scale = 1.0f;\n            float       widthLeft = GetContentRegionAvail().x;\n            const char* endLine = ImGui::GetFont()->CalcWordWrapPositionA( scale, text_, text_end_, widthLeft );\n            bool bHovered = RenderLinkText( text_, endLine, link_, style_, markdown_, mdConfig_, linkHoverStart_ );\n            if( bIndentToHere_ )\n            {\n                float indentNeeded = GetContentRegionAvail().x - widthLeft;\n                if( indentNeeded )\n                {\n                    ImGui::Indent( indentNeeded );\n                    indentX += indentNeeded;\n                }\n            }\n            widthLeft = GetContentRegionAvail().x;\n            while( endLine < text_end_ )\n            {\n                text_ = endLine;\n                if( *text_ == ' ' ) { ++text_; }    // skip a space at start of line\n                endLine = ImGui::GetFont()->CalcWordWrapPositionA( scale, text_, text_end_, widthLeft );\n                if( text_ == endLine ) \n                {\n                    endLine++;\n                }\n                bool bThisLineHovered = RenderLinkText( text_, endLine, link_, style_, markdown_, mdConfig_, linkHoverStart_ );\n                bHovered = bHovered || bThisLineHovered;\n            }\n            if( !bHovered && *linkHoverStart_ == markdown_ + link_.text.start )\n            {\n                *linkHoverStart_ = NULL;\n            }\n        }\n}\n\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/imgui_remote/imgui_remote.h",
    "content": "//-----------------------------------------------------------------------------\n// Remote ImGui https://github.com/JordiRos/remoteimgui\n// Uses\n// ImGui https://github.com/ocornut/imgui 1.3\n// Webby https://github.com/deplinenoise/webby\n// LZ4   https://code.google.com/p/lz4/\n//-----------------------------------------------------------------------------\n\n#include \"lz4/lz4.h\"\n#include <stdio.h>\n\n#define IMGUI_REMOTE_KEY_FRAME    60  // send keyframe every 30 frames\n#define IMGUI_REMOTE_INPUT_FRAMES 60 // input valid during 120 frames\n\nnamespace ImGui {\n\n\t//------------------\n\t// ImGuiRemoteInput\n\t// - a structure to store input received from remote imgui, so you can use it on your whole app (keys, mouse) or just in imgui engine\n\t// - use GetImGuiRemoteInput to read input data safely (valid for IMGUI_REMOTE_INPUT_FRAMES)\n\t//------------------\n\tstruct RemoteInput\n\t{\n\t\tImVec2\tMousePos;\n\t\tint\t\tMouseButtons;\n\t\tfloat\tMouseWheelDelta;\n\t\tbool\tKeyCtrl;\n\t\tbool\tKeyShift;\n\t\tbool\tKeysDown[ 256 ];\n\t};\n\n\t//------------------\n\t// IWebSocketServer\n\t// - WebSocketServer interface\n\t//------------------\n\t/*\n\tstruct IWebSocketServer\n\t{\n\t\tenum OpCode\n\t\t{\n\t\t\tText,\n\t\t\tBinary,\n\t\t\tDisconnect,\n\t\t\tPing,\n\t\t\tPong\n\t\t};\n\t\tvoid Init(const char *bind_address, int port);\n\t\tvoid Shutdown();\n\t\tvoid SendText(const void *data, int size);\n\t\tvoid SendBinary(const void *data, int size);\n\t\t\tvirtual void OnMessage(OpCode opcode, const void *data, int size) { }\n\t\tvirtual void OnError() { }\n\t};\n\t*/\n\n\ttemplate<typename T> class Vector\n\t{\n\tprivate:\n\t\tT * Items;\n\t\tunsigned int Size;\n\t\tunsigned int Capacity;\n\tpublic:\n\t\tVector()\n\t\t\t: Items( NULL )\n\t\t\t, Size( 0 )\n\t\t\t, Capacity( 0 )\n\t\t{\n\t\t\treserve( 16 );\n\t\t}\n\t\tVector( unsigned int initialCapacity )\n\t\t\t: Items( NULL )\n\t\t\t, Size( 0 )\n\t\t\t, Capacity( 0 )\n\t\t{\n\t\t\treserve( initialCapacity );\n\t\t}\n\t\t~Vector()\n\t\t{\n\t\t\tif ( Items )\n\t\t\t{\n\t\t\t\tImGui::MemFree( Items );\n\t\t\t\tItems = nullptr;\n\t\t\t}\n\t\t}\n\t\tvoid push_back( T item )\n\t\t{\n\t\t\tif ( Size >= Capacity )\n\t\t\t{\n\t\t\t\treserve( Capacity * 2 );\n\t\t\t}\n\t\t\tItems[ Size++ ] = item;\n\t\t}\n\t\tvoid clear()\n\t\t{\n\t\t\tSize = 0;\n\t\t}\n\t\tvoid reserve( const unsigned int newCapacity )\n\t\t{\n\t\t\tif ( newCapacity <= Capacity )\n\t\t\t{\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tT * newItems = (T*) ImGui::MemAlloc( newCapacity * sizeof( T ) );\n\t\t\tif ( Items )\n\t\t\t{\n\t\t\t\tmemcpy( newItems, Items, Capacity * sizeof( T ) );\n\t\t\t\tImGui::MemFree( Items );\n\t\t\t}\n\n\t\t\tItems = newItems;\n\t\t\tCapacity = newCapacity;\n\t\t}\n\t\tconst unsigned int size()\n\t\t{\n\t\t\treturn Size;\n\t\t}\n\t\tT & operator[]( unsigned int index )\n\t\t{\n\t\t\treturn Items[ index ];\n\t\t}\n\t};\n\n#include \"imgui_remote_webby.h\"\n\n\t//------------------\n\t// WebSocketServer\n\t// - ImGui web socket server connection\n\t//------------------\n\tstruct WebSocketServer : public IWebSocketServer\n\t{\n\t\tbool ClientActive;\n\t\tint Frame;\n\t\tint FrameReceived;\n\t\tint PrevPacketSize;\n\t\tbool IsKeyFrame;\n\t\tbool ForceKeyFrame;\n\t\tVector<unsigned char> Packet;\n\t\tVector<unsigned char> PrevPacket;\n\t\tRemoteInput Input;\n\n\t\tWebSocketServer()\n\t\t{\n\t\t\tClientActive = false;\n\t\t\tFrame = 0;\n\t\t\tFrameReceived = 0;\n\t\t\tIsKeyFrame = false;\n\t\t\tPrevPacketSize = 0;\n\t\t}\n\t\tinline bool mapRemoteKey( int* remoteKey, bool isCtrlPressed )\n\t\t{\n\t\t\tif ( *remoteKey == 37 )\n\t\t\t\t*remoteKey = ImGuiKey_LeftArrow;\n\t\t\telse if ( *remoteKey == 40 )\n\t\t\t\t*remoteKey = ImGuiKey_DownArrow;\n\t\t\telse if ( *remoteKey == 38 )\n\t\t\t\t*remoteKey = ImGuiKey_UpArrow;\n\t\t\telse if ( *remoteKey == 39 )\n\t\t\t\t*remoteKey = ImGuiKey_RightArrow;\n\t\t\telse if ( *remoteKey == 46 )\n\t\t\t\t*remoteKey = ImGuiKey_Delete;\n\t\t\telse if ( *remoteKey == 9 )\n\t\t\t\t*remoteKey = ImGuiKey_Tab;\n\t\t\telse if ( *remoteKey == 8 )\n\t\t\t\t*remoteKey = ImGuiKey_Backspace;\n\t\t\telse if ( *remoteKey == 65 && isCtrlPressed )\n\t\t\t\t*remoteKey = 'a';\n\t\t\telse if ( *remoteKey == 67 && isCtrlPressed )\n\t\t\t\t*remoteKey = 'c';\n\t\t\telse if ( *remoteKey == 86 && isCtrlPressed )\n\t\t\t\t*remoteKey = 'v';\n\t\t\telse if ( *remoteKey == 88 && isCtrlPressed )\n\t\t\t\t*remoteKey = 'x';\n\t\t\telse\n\t\t\t\treturn true;\n\n\t\t\treturn false;\n\t\t}\n\t\tvirtual void OnMessage( OpCode opcode, const void *data, int /*size*/ )\n\t\t{\n\t\t\tswitch ( opcode )\n\t\t\t{\n\t\t\t\t// Text message\n\t\t\tcase WebSocketServer::Text:\n\t\t\t\tif ( !ClientActive )\n\t\t\t\t{\n\t\t\t\t\tif ( !memcmp( data, \"ImInit\", 6 ) )\n\t\t\t\t\t{\n\t\t\t\t\t\tClientActive = true;\n\t\t\t\t\t\tForceKeyFrame = true;\n\t\t\t\t\t\t// Send confirmation\n\t\t\t\t\t\tSendText( \"ImInit\", 6 );\n\t\t\t\t\t\t// Send font texture\n\t\t\t\t\t\tunsigned char* pixels;\n\t\t\t\t\t\tint width, height;\n\t\t\t\t\t\tImGui::GetIO().Fonts->GetTexDataAsAlpha8( &pixels, &width, &height );\n\t\t\t\t\t\tPreparePacketTexFont( pixels, width, height );\n\t\t\t\t\t\tSendPacket();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if ( strstr( (char *) data, \"ImMouseMove\" ) )\n\t\t\t\t{\n\t\t\t\t\tint x, y, mouse_left, mouse_right;\n\t\t\t\t\tif ( sscanf( (char *) data, \"ImMouseMove=%d,%d,%d,%d\", &x, &y, &mouse_left, &mouse_right ) == 4 )\n\t\t\t\t\t{\n\t\t\t\t\t\tFrameReceived = Frame;\n\t\t\t\t\t\tInput.MousePos.x = (float) x;\n\t\t\t\t\t\tInput.MousePos.y = (float) y;\n\t\t\t\t\t\tInput.MouseButtons = mouse_left | ( mouse_right << 1 );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if ( strstr( (char *) data, \"ImMousePress\" ) )\n\t\t\t\t{\n\t\t\t\t\tint l, r;\n\t\t\t\t\tif ( sscanf( (char *) data, \"ImMousePress=%d,%d\", &l, &r ) == 2 )\n\t\t\t\t\t{\n\t\t\t\t\t\tFrameReceived = Frame;\n\t\t\t\t\t\tInput.MouseButtons = l | ( r << 1 );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if ( strstr( (char *) data, \"ImMouseWheelDelta\" ) )\n\t\t\t\t{\n\t\t\t\t\tfloat mouseWheelDelta;\n\t\t\t\t\tif ( sscanf( (char *) data, \"ImMouseWheelDelta=%f\", &mouseWheelDelta ) == 1 )\n\t\t\t\t\t{\n\t\t\t\t\t\tFrameReceived = Frame;\n\t\t\t\t\t\tInput.MouseWheelDelta = mouseWheelDelta *0.01f;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if ( strstr( (char *) data, \"ImKeyDown\" ) )\n\t\t\t\t{\n\t\t\t\t\tint key, shift, ctrl;\n\t\t\t\t\tif ( sscanf( (char *) data, \"ImKeyDown=%d,%d,%d\", &key, &shift, &ctrl ) == 3 )\n\t\t\t\t\t{\n\t\t\t\t\t\t//update key states\n\t\t\t\t\t\tFrameReceived = Frame;\n\t\t\t\t\t\tInput.KeyShift = shift > 0;\n\t\t\t\t\t\tInput.KeyCtrl = ctrl > 0;\n\t\t\t\t\t\tmapRemoteKey( &key, Input.KeyCtrl );\n\t\t\t\t\t\tInput.KeysDown[ key ] = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if ( strstr( (char *) data, \"ImKeyUp\" ) )\n\t\t\t\t{\n\t\t\t\t\tint key;\n\t\t\t\t\tif ( sscanf( (char *) data, \"ImKeyUp=%d\", &key ) == 1 )\n\t\t\t\t\t{\n\t\t\t\t\t\t//update key states\n\t\t\t\t\t\tFrameReceived = Frame;\n\t\t\t\t\t\tInput.KeysDown[ key ] = false;\n\t\t\t\t\t\tInput.KeyShift = false;\n\t\t\t\t\t\tInput.KeyCtrl = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if ( strstr( (char *) data, \"ImKeyPress\" ) )\n\t\t\t\t{\n\t\t\t\t\tunsigned int key;\n\t\t\t\t\tif ( sscanf( (char *) data, \"ImKeyPress=%d\", &key ) == 1 )\n\t\t\t\t\t\tImGui::GetIO().AddInputCharacter( ImWchar( key ) );\n\t\t\t\t}\n\t\t\t\telse if ( strstr( (char *) data, \"ImClipboard=\" ) )\n\t\t\t\t{\n\t\t\t\t\tchar *clipboard = &( (char *) data )[ strlen( \"ImClipboard=\" ) ];\n\t\t\t\t\tImGui::GetIO().SetClipboardTextFn( NULL, clipboard );\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t\t// Binary message\n\t\t\tcase WebSocketServer::Binary:\n\t\t\t\t//printf(\"ImGui client: Binary message received (%d bytes)\\n\", size);\n\t\t\t\tbreak;\n\t\t\t\t// Disconnect\n\t\t\tcase WebSocketServer::Disconnect:\n\t\t\t\tprintf( \"ImGui client: DISCONNECT\\n\" );\n\t\t\t\tClientActive = false;\n\t\t\t\tbreak;\n\t\t\t\t// Ping\n\t\t\tcase WebSocketServer::Ping:\n\t\t\t\tprintf( \"ImGui client: PING\\n\" );\n\t\t\t\tbreak;\n\t\t\t\t// Pong\n\t\t\tcase WebSocketServer::Pong:\n\t\t\t\tprintf( \"ImGui client: PONG\\n\" );\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tassert( 0 );\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n#pragma pack(1)\n\t\tstruct Cmd\n\t\t{\n\t\t\tint   elemCount;\n\t\t\tfloat clip_rect[ 4 ];\n\t\t\tvoid Set( const ImDrawCmd &draw_cmd )\n\t\t\t{\n\t\t\t\telemCount = draw_cmd.ElemCount;\n\t\t\t\tclip_rect[ 0 ] = draw_cmd.ClipRect.x;\n\t\t\t\tclip_rect[ 1 ] = draw_cmd.ClipRect.y;\n\t\t\t\tclip_rect[ 2 ] = draw_cmd.ClipRect.z;\n\t\t\t\tclip_rect[ 3 ] = draw_cmd.ClipRect.w;\n\t\t\t\t//printf(\"DrawCmd: %d ( %.2f, %.2f, %.2f, %.2f )\\n\", vtx_count, clip_rect[0], clip_rect[1], clip_rect[2], clip_rect[3]);\n\t\t\t}\n\t\t};\n\t\tstruct Vtx\n\t\t{\n\t\t\tshort x, y; // 16 short\n\t\t\tshort u, v; // 16 fixed point\n\t\t\tunsigned char r, g, b, a; // 8*4\n\t\t\tvoid Set( const ImDrawVert &vtx )\n\t\t\t{\n\t\t\t\tx = (short) ( vtx.pos.x );\n\t\t\t\ty = (short) ( vtx.pos.y );\n\t\t\t\tu = (short) ( vtx.uv.x * 32767.f );\n\t\t\t\tv = (short) ( vtx.uv.y * 32767.f );\n\t\t\t\tr = ( vtx.col >> 0 ) & 0xff;\n\t\t\t\tg = ( vtx.col >> 8 ) & 0xff;\n\t\t\t\tb = ( vtx.col >> 16 ) & 0xff;\n\t\t\t\ta = ( vtx.col >> 24 ) & 0xff;\n\t\t\t}\n\t\t};\n\t\tstruct Idx\n\t\t{\n\t\t\tunsigned short idx;\n\n\t\t\tvoid Set( ImDrawIdx _idx )\n\t\t\t{\n\t\t\t\tidx = _idx;\n\t\t\t}\n\t\t};\n#pragma pack()\n\n\t\tvoid Write( unsigned char c ) { Packet.push_back( c ); }\n\t\tvoid Write( unsigned int i )\n\t\t{\n\t\t\tif ( IsKeyFrame )\n\t\t\t\tWrite( &i, sizeof( unsigned int ) );\n\t\t\telse\n\t\t\t\tWriteDiff( &i, sizeof( unsigned int ) );\n\t\t}\n\t\tvoid Write( Cmd const &cmd )\n\t\t{\n\t\t\tif ( IsKeyFrame )\n\t\t\t\tWrite( (void *) &cmd, sizeof( Cmd ) );\n\t\t\telse\n\t\t\t\tWriteDiff( (void *) &cmd, sizeof( Cmd ) );\n\t\t}\n\t\tvoid Write( Vtx const &vtx )\n\t\t{\n\t\t\tif ( IsKeyFrame )\n\t\t\t\tWrite( (void *) &vtx, sizeof( Vtx ) );\n\t\t\telse\n\t\t\t\tWriteDiff( (void *) &vtx, sizeof( Vtx ) );\n\t\t}\n\n\t\tvoid Write( Idx const &idx )\n\t\t{\n\t\t\tif ( IsKeyFrame )\n\t\t\t\tWrite( (void *) &idx, sizeof( Idx ) );\n\t\t\telse\n\t\t\t\tWriteDiff( (void *) &idx, sizeof( Idx ) );\n\t\t}\n\n\t\tvoid Write( const void *data, int size )\n\t\t{\n\t\t\tunsigned char *src = (unsigned char *) data;\n\t\t\tfor ( int i = 0; i < size; i++ )\n\t\t\t{\n\t\t\t\tint pos = (int) Packet.size();\n\t\t\t\tWrite( src[ i ] );\n\t\t\t\tPrevPacket[ pos ] = src[ i ];\n\t\t\t}\n\t\t}\n\t\tvoid WriteDiff( const void *data, int size )\n\t\t{\n\t\t\tunsigned char *src = (unsigned char *) data;\n\t\t\tfor ( int i = 0; i < size; i++ )\n\t\t\t{\n\t\t\t\tint pos = (int) Packet.size();\n\t\t\t\tWrite( (unsigned char) ( src[ i ] - ( pos < PrevPacketSize ? PrevPacket[ pos ] : 0 ) ) );\n\t\t\t\tPrevPacket[ pos ] = src[ i ];\n\t\t\t}\n\t\t}\n\n\t\tvoid SendPacket()\n\t\t{\n\t\t\tstatic int buffer[ 65536 ];\n\t\t\tint size = (int) Packet.size();\n\t\t\tint csize = LZ4_compress_limitedOutput( (char *) &Packet[ 0 ], (char *) ( buffer + 3 ), size, 65536 * sizeof( int ) - 12 );\n\t\t\tbuffer[ 0 ] = 0xBAADFEED; // Our LZ4 header magic number (used in custom lz4.js to decompress)\n\t\t\tbuffer[ 1 ] = size;\n\t\t\tbuffer[ 2 ] = csize;\n\t\t\t//printf(\"ImWebSocket SendPacket: %s %d / %d (%.2f%%)\\n\", IsKeyFrame ? \"(KEY)\" : \"\", size, csize, (float)csize * 100.f / size);\n\t\t\tSendBinary( buffer, csize + 12 );\n\t\t\tPrevPacketSize = size;\n\t\t}\n\n\t\tvoid PreparePacket( unsigned char data_type, unsigned int data_size )\n\t\t{\n\t\t\tunsigned int size = sizeof( unsigned char ) + data_size;\n\t\t\tPacket.clear();\n\t\t\tPacket.reserve( size );\n\t\t\tPrevPacket.reserve( size );\n\t\t\twhile ( size > PrevPacket.size() )\n\t\t\t\tPrevPacket.push_back( 0 );\n\t\t\tWrite( data_type );\n\t\t}\n\n\t\t// packet types\n\t\tenum { TEX_FONT = 255, FRAME_KEY = 254, FRAME_DIFF = 253 };\n\n\t\tvoid PreparePacketTexFont( const void *data, unsigned int w, unsigned int h )\n\t\t{\n\t\t\tIsKeyFrame = true;\n\t\t\tPreparePacket( TEX_FONT, sizeof( unsigned int ) * 2 + w*h );\n\t\t\tWrite( w );\n\t\t\tWrite( h );\n\t\t\tWrite( data, w*h );\n\t\t\tForceKeyFrame = true;\n\t\t}\n\n\t\tvoid PreparePacketFrame( unsigned int size )//unsigned int cmd_count, unsigned int vtx_count, unsigned int idx_count)\n\t\t{\n\t\t\tIsKeyFrame = ( Frame%IMGUI_REMOTE_KEY_FRAME ) == 0 || ForceKeyFrame;\n\t\t\tPreparePacket( (unsigned char) ( IsKeyFrame ? FRAME_KEY : FRAME_DIFF ), size );\n\t\t\t//printf(\"ImWebSocket PreparePacket: cmd_count = %i, vtx_count = %i ( %lu bytes )\\n\", cmd_count, vtx_count, sizeof(unsigned int) + sizeof(unsigned int) + cmd_count * sizeof(Cmd) + vtx_count * sizeof(Vtx));\n\t\t\tForceKeyFrame = false;\n\t\t}\n\t};\n\n\n\tstatic WebSocketServer GServer;\n\n\n\t//------------------\n\t// RemoteGetInput\n\t// - get input received from remote safely (valid for 30 frames)\n\t//------------------\n\tbool RemoteGetInput( RemoteInput & input )\n\t{\n\t\tbool res = false;\n\t\tif ( GServer.ClientActive )\n\t\t{\n\n\t\t\tif ( GServer.Frame - GServer.FrameReceived < IMGUI_REMOTE_INPUT_FRAMES )\n\t\t\t{\n\t\t\t\tinput = GServer.Input;\n\t\t\t\tres = true;\n\t\t\t}\n\t\t}\n\t\tmemset( GServer.Input.KeysDown, 0, 256 * sizeof( bool ) );\n\t\tGServer.Input.KeyCtrl = false;\n\t\tGServer.Input.KeyShift = false;\n\t\tGServer.Input.MouseWheelDelta = 0;\n\t\treturn res;\n\t}\n\n\n\t//------------------\n\t// RemoteInit\n\t// - initialize RemoteImGui on top of your ImGui\n\t//------------------\n\tvoid RemoteInit( const char *local_address, int local_port )\n\t{\n\t\tGServer.Init( local_address, local_port );\n\t}\n\n\n\t//------------------\n\t// RemoteShutdown\n\t// - shutdown RemoteImGui\n\t//------------------\n\tvoid RemoteShutdown()\n\t{\n\t\tGServer.Shutdown();\n\t}\n\n\n\t//------------------\n\t// RemoteUpdate\n\t// - update RemoteImGui stuff\n\t//------------------\n\tvoid RemoteUpdate()\n\t{\n\t\tGServer.Frame++;\n\t\tGServer.Update();\n\t}\n\n\n\t//------------------\n\t// RemoteDraw\n\t// - send draw list commands to connected client\n\t//------------------\n\tvoid RemoteDraw( ImDrawList** const cmd_lists, int cmd_lists_count )\n\t{\n\t\tif ( GServer.ClientActive )\n\t\t{\n\t\t\tstatic int sendframe = 0;\n\t\t\tif ( sendframe++ < 2 ) // every 2 frames, @TWEAK\n\t\t\t{\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsendframe = 0;\n\n\t\t\tunsigned int totalSize = sizeof( unsigned int ); // cmd_lists_count\n\t\t\tfor ( int n = 0; n < cmd_lists_count; n++ )\n\t\t\t{\n\t\t\t\tconst ImDrawList* cmd_list = cmd_lists[ n ];\n\t\t\t\tint cmd_count = cmd_list->CmdBuffer.size();\n\t\t\t\tint vtx_count = cmd_list->VtxBuffer.size();\n\t\t\t\tint idx_count = cmd_list->IdxBuffer.size();\n\t\t\t\ttotalSize += 3 * sizeof( unsigned int ); //cmd_count, vtx_count and idx_count\n\t\t\t\ttotalSize += cmd_count * sizeof( WebSocketServer::Cmd ) + vtx_count * sizeof( WebSocketServer::Vtx ) + idx_count * sizeof( WebSocketServer::Idx );\n\t\t\t}\n\n\t\t\tGServer.PreparePacketFrame( totalSize );\n\t\t\tGServer.Write( (unsigned int) cmd_lists_count );\n\n\t\t\tfor ( int n = 0; n < cmd_lists_count; n++ )\n\t\t\t{\n\t\t\t\tconst ImDrawList* cmd_list = cmd_lists[ n ];\n\t\t\t\tconst ImDrawVert * vtx_src = cmd_list->VtxBuffer.begin();\n\t\t\t\tconst ImDrawIdx * idx_src = cmd_list->IdxBuffer.begin();\n\t\t\t\tunsigned int cmd_count = cmd_list->CmdBuffer.size();\n\t\t\t\tunsigned int vtx_count = cmd_list->VtxBuffer.size();\n\t\t\t\tunsigned int idx_count = cmd_list->IdxBuffer.size();\n\t\t\t\tGServer.Write( cmd_count );\n\t\t\t\tGServer.Write( vtx_count );\n\t\t\t\tGServer.Write( idx_count );\n\t\t\t\t// Send \n\t\t\t\t// Add all drawcmds\n\t\t\t\tWebSocketServer::Cmd cmd;\n\t\t\t\tconst ImDrawCmd* pcmd_end = cmd_list->CmdBuffer.end();\n\t\t\t\tfor ( const ImDrawCmd* pcmd = cmd_list->CmdBuffer.begin(); pcmd != pcmd_end; pcmd++ )\n\t\t\t\t{\n\t\t\t\t\tcmd.Set( *pcmd );\n\t\t\t\t\tGServer.Write( cmd );\n\t\t\t\t}\n\t\t\t\t// Add all vtx\n\t\t\t\tWebSocketServer::Vtx vtx;\n\t\t\t\tint vtx_remaining = vtx_count;\n\t\t\t\twhile ( vtx_remaining-- > 0 )\n\t\t\t\t{\n\t\t\t\t\tvtx.Set( *vtx_src++ );\n\t\t\t\t\tGServer.Write( vtx );\n\t\t\t\t}\n\n\t\t\t\t// Add all idx\n\t\t\t\tWebSocketServer::Idx idx;\n\n\t\t\t\tint idx_remaining = idx_count;\n\t\t\t\twhile ( idx_remaining-- > 0 )\n\t\t\t\t{\n\t\t\t\t\tidx.Set( *idx_src++ );\n\t\t\t\t\tGServer.Write( idx );\n\t\t\t\t}\n\n\t\t\t}\n\t\t\t// Send\n\t\t\tGServer.SendPacket();\n\t\t}\n\t}\n\n\n} // namespace\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/imgui_remote/imgui_remote_webby.h",
    "content": "//-----------------------------------------------------------------------------\n// Remote ImGui https://github.com/JordiRos/remoteimgui\n// Uses\n// ImGui https://github.com/ocornut/imgui 1.3\n// Webby https://github.com/deplinenoise/webby\n// LZ4   https://code.google.com/p/lz4/\n//-----------------------------------------------------------------------------\n\n#include \"webby/webby.h\"\n\n#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n#include <ctype.h>\n\n#ifdef _WIN32\n#include <winsock2.h>\n#endif\n\n#ifdef __APPLE__\n#include <unistd.h>\n#endif\n\nstruct IWebSocketServer;\n\nIWebSocketServer *s_WebSocketServer;\n\nstatic void onLog( const char* text );\nstatic int  onDispatch( struct WebbyConnection *connection );\nstatic int  onConnect( struct WebbyConnection *connection );\nstatic void onConnected( struct WebbyConnection *connection );\nstatic void onDisconnected( struct WebbyConnection *connection );\nstatic int  onFrame( struct WebbyConnection *connection, const struct WebbyWsFrame *frame );\n\nstruct IWebSocketServer\n{\n\tenum OpCode // based on websocket connection opcodes\n\t{\n\t\tContinuation = 0,\n\t\tText = 1,\n\t\tBinary = 2,\n\t\tDisconnect = 8,\n\t\tPing = 9,\n\t\tPong = 10,\n\t};\n\n\tvoid *Memory;\n\tint MemorySize;\n\tstruct WebbyServer *Server;\n\tstruct WebbyServerConfig ServerConfig;\n\tstruct WebbyConnection *Client;\n\n\tint Init( const char *local_address, int local_port )\n\t{\n\t\ts_WebSocketServer = this;\n\n#if defined(_WIN32)\n\t\t{\n\t\t\tWORD wsa_version = MAKEWORD( 2, 2 );\n\t\t\tWSADATA wsa_data;\n\t\t\tif ( 0 != WSAStartup( wsa_version, &wsa_data ) )\n\t\t\t\treturn -1;\n\t\t}\n#endif\n\n\t\tmemset( &ServerConfig, 0, sizeof ServerConfig );\n\t\tServerConfig.bind_address = local_address;\n\t\tServerConfig.listening_port = (unsigned short) ( local_port );\n\t\tServerConfig.flags = WEBBY_SERVER_WEBSOCKETS;\n\t\tServerConfig.connection_max = 1;\n\t\tServerConfig.request_buffer_size = 2048;\n\t\tServerConfig.io_buffer_size = 8192;\n\t\tServerConfig.dispatch = &onDispatch;\n\t\tServerConfig.log = &onLog;\n\t\tServerConfig.ws_connect = &onConnect;\n\t\tServerConfig.ws_connected = &onConnected;\n\t\tServerConfig.ws_closed = &onDisconnected;\n\t\tServerConfig.ws_frame = &onFrame;\n\n\t\tMemorySize = WebbyServerMemoryNeeded( &ServerConfig );\n\t\tMemory = malloc( MemorySize );\n\t\tServer = WebbyServerInit( &ServerConfig, Memory, MemorySize );\n\t\tClient = NULL;\n\t\tif ( !Server )\n\t\t\treturn -2;\n\n\t\treturn 0;\n\t}\n\n\tvoid Update()\n\t{\n\t\tif ( Server )\n\t\t\tWebbyServerUpdate( Server );\n\t}\n\n\tvoid Shutdown()\n\t{\n\t\tif ( Server )\n\t\t{\n\t\t\tWebbyServerShutdown( Server );\n\t\t\tfree( Memory );\n\t\t}\n\n#if defined(_WIN32)\n\t\tWSACleanup();\n#endif\n\t}\n\n\tvoid WsOnConnected( struct WebbyConnection *connection )\n\t{\n\t\tClient = connection;\n\t}\n\n\tvoid WsOnDisconnected( struct WebbyConnection * /*connection*/ )\n\t{\n\t\tClient = NULL;\n\t\tOnMessage( Disconnect, NULL, 0 );\n\t}\n\n\tint WsOnFrame( struct WebbyConnection *connection, const struct WebbyWsFrame *frame )\n\t{\n\t\t//\t\tprintf(\"WebSocket frame incoming\\n\");\n\t\t//\t\tprintf(\"  Frame OpCode: %d\\n\", frame->opcode);\n\t\t//\t\tprintf(\"  Final frame?: %s\\n\", (frame->flags & WEBBY_WSF_FIN) ? \"yes\" : \"no\");\n\t\t//\t\tprintf(\"  Masked?     : %s\\n\", (frame->flags & WEBBY_WSF_MASKED) ? \"yes\" : \"no\");\n\t\t//\t\tprintf(\"  Data Length : %d\\n\", (int) frame->payload_length);\n\n\t\tVector<unsigned char> buffer( frame->payload_length + 1 );\n\t\tWebbyRead( connection, &buffer[ 0 ], frame->payload_length );\n\t\tbuffer[ frame->payload_length ] = 0;\n\t\t//        if(!strstr((char*)&buffer[0],\"ImMouseMove\"))\n\t\t//            printf(\"  Data : %s\\n\", &buffer[0]);\n\n\t\tOnMessage( (OpCode) frame->opcode, &buffer[ 0 ], frame->payload_length );\n\n\t\treturn 0;\n\t}\n\n\tvirtual void OnMessage( OpCode /*opcode*/, const void * /*data*/, int /*size*/ ) { }\n\tvirtual void OnError() { }\n\n\tvirtual void SendText( const void *data, int size )\n\t{\n\t\tif ( Client )\n\t\t{\n\t\t\tWebbySendFrame( Client, WEBBY_WS_OP_TEXT_FRAME, data, size );\n\t\t}\n\t}\n\n\tvirtual void SendBinary( const void *data, int size )\n\t{\n\t\tif ( Client )\n\t\t{\n\t\t\tWebbySendFrame( Client, WEBBY_WS_OP_BINARY_FRAME, data, size );\n\t\t}\n\t}\n};\n\n\nstatic void onLog( const char* /*text*/ )\n{\n\t//printf(\"[WsOnLog] %s\\n\", text);\n}\n\nstatic int onDispatch( struct WebbyConnection * /*connection*/ )\n{\n\t//printf(\"[WsOnDispatch] %s\\n\", connection->request.uri);\n\treturn 1;\n}\n\nstatic int onConnect( struct WebbyConnection * /*connection*/ )\n{\n\t//printf(\"[WsOnConnect] %s\\n\", connection->request.uri);\n\treturn 0;\n}\n\nstatic void onConnected( struct WebbyConnection *connection )\n{\n\t//printf(\"[WsOnConnected]\\n\");\n\ts_WebSocketServer->WsOnConnected( connection );\n}\n\nstatic void onDisconnected( struct WebbyConnection *connection )\n{\n\t//printf(\"[WsOnDisconnected]\\n\");\n\ts_WebSocketServer->WsOnDisconnected( connection );\n}\n\nstatic int onFrame( struct WebbyConnection *connection, const struct WebbyWsFrame *frame )\n{\n\t//printf(\"[WsOnFrame]\\n\");\n\treturn s_WebSocketServer->WsOnFrame( connection, frame );\n}\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/imgui_remote/lz4/LICENSE",
    "content": "LZ4 Library\nCopyright (c) 2011-2016, Yann Collet\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n  list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice, this\n  list of conditions and the following disclaimer in the documentation and/or\n  other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/imgui_remote/lz4/lz4.c",
    "content": "/*\n   LZ4 - Fast LZ compression algorithm\n   Copyright (C) 2011-2015, Yann Collet.\n   BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)\n\n   Redistribution and use in source and binary forms, with or without\n   modification, are permitted provided that the following conditions are\n   met:\n\n       * Redistributions of source code must retain the above copyright\n   notice, this list of conditions and the following disclaimer.\n       * Redistributions in binary form must reproduce the above\n   copyright notice, this list of conditions and the following disclaimer\n   in the documentation and/or other materials provided with the\n   distribution.\n\n   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n   \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n   You can contact the author at :\n   - LZ4 source repository : http://code.google.com/p/lz4\n   - LZ4 source mirror : https://github.com/Cyan4973/lz4\n   - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c\n*/\n\n\n/**************************************\n   Tuning parameters\n**************************************/\n/*\n * HEAPMODE :\n * Select how default compression functions will allocate memory for their hash table,\n * in memory stack (0:default, fastest), or in memory heap (1:requires malloc()).\n */\n#define HEAPMODE 0\n\n/*\n * CPU_HAS_EFFICIENT_UNALIGNED_MEMORY_ACCESS :\n * By default, the source code expects the compiler to correctly optimize\n * 4-bytes and 8-bytes read on architectures able to handle it efficiently.\n * This is not always the case. In some circumstances (ARM notably),\n * the compiler will issue cautious code even when target is able to correctly handle unaligned memory accesses.\n *\n * You can force the compiler to use unaligned memory access by uncommenting the line below.\n * One of the below scenarios will happen :\n * 1 - Your target CPU correctly handle unaligned access, and was not well optimized by compiler (good case).\n *     You will witness large performance improvements (+50% and up).\n *     Keep the line uncommented and send a word to upstream (https://groups.google.com/forum/#!forum/lz4c)\n *     The goal is to automatically detect such situations by adding your target CPU within an exception list.\n * 2 - Your target CPU correctly handle unaligned access, and was already already optimized by compiler\n *     No change will be experienced.\n * 3 - Your target CPU inefficiently handle unaligned access.\n *     You will experience a performance loss. Comment back the line.\n * 4 - Your target CPU does not handle unaligned access.\n *     Program will crash.\n * If uncommenting results in better performance (case 1)\n * please report your configuration to upstream (https://groups.google.com/forum/#!forum/lz4c)\n * An automatic detection macro will be added to match your case within future versions of the library.\n */\n/* #define CPU_HAS_EFFICIENT_UNALIGNED_MEMORY_ACCESS 1 */\n\n\n/**************************************\n   CPU Feature Detection\n**************************************/\n/*\n * Automated efficient unaligned memory access detection\n * Based on known hardware architectures\n * This list will be updated thanks to feedbacks\n */\n#if defined(CPU_HAS_EFFICIENT_UNALIGNED_MEMORY_ACCESS) \\\n    || defined(__ARM_FEATURE_UNALIGNED) \\\n    || defined(__i386__) || defined(__x86_64__) \\\n    || defined(_M_IX86) || defined(_M_X64) \\\n    || defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_8__) \\\n    || (defined(_M_ARM) && (_M_ARM >= 7))\n#  define LZ4_UNALIGNED_ACCESS 1\n#else\n#  define LZ4_UNALIGNED_ACCESS 0\n#endif\n\n/*\n * LZ4_FORCE_SW_BITCOUNT\n * Define this parameter if your target system or compiler does not support hardware bit count\n */\n#if defined(_MSC_VER) && defined(_WIN32_WCE)   /* Visual Studio for Windows CE does not support Hardware bit count */\n#  define LZ4_FORCE_SW_BITCOUNT\n#endif\n\n\n/**************************************\n   Compiler Options\n**************************************/\n#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)   /* C99 */\n/* \"restrict\" is a known keyword */\n#else\n#  define restrict /* Disable restrict */\n#endif\n\n#ifdef _MSC_VER    /* Visual Studio */\n#  define FORCE_INLINE static __forceinline\n#  include <intrin.h>\n#  pragma warning(disable : 4127)        /* disable: C4127: conditional expression is constant */\n#  pragma warning(disable : 4293)        /* disable: C4293: too large shift (32-bits) */\n#else\n#  if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)   /* C99 */\n#    ifdef __GNUC__\n#      define FORCE_INLINE static inline __attribute__((always_inline))\n#    else\n#      define FORCE_INLINE static inline\n#    endif\n#  else\n#    define FORCE_INLINE static\n#  endif   /* __STDC_VERSION__ */\n#endif  /* _MSC_VER */\n\n#define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)\n\n#if (GCC_VERSION >= 302) || (__INTEL_COMPILER >= 800) || defined(__clang__)\n#  define expect(expr,value)    (__builtin_expect ((expr),(value)) )\n#else\n#  define expect(expr,value)    (expr)\n#endif\n\n#define likely(expr)     expect((expr) != 0, 1)\n#define unlikely(expr)   expect((expr) != 0, 0)\n\n\n/**************************************\n   Memory routines\n**************************************/\n#include <stdlib.h>   /* malloc, calloc, free */\n#define ALLOCATOR(n,s) calloc(n,s)\n#define FREEMEM        free\n#include <string.h>   /* memset, memcpy */\n#define MEM_INIT       memset\n\n\n/**************************************\n   Includes\n**************************************/\n#include \"lz4.h\"\n\n\n/**************************************\n   Basic Types\n**************************************/\n#if defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)   /* C99 */\n# include <stdint.h>\n  typedef  uint8_t BYTE;\n  typedef uint16_t U16;\n  typedef uint32_t U32;\n  typedef  int32_t S32;\n  typedef uint64_t U64;\n#else\n  typedef unsigned char       BYTE;\n  typedef unsigned short      U16;\n  typedef unsigned int        U32;\n  typedef   signed int        S32;\n  typedef unsigned long long  U64;\n#endif\n\n\n/**************************************\n   Reading and writing into memory\n**************************************/\n#define STEPSIZE sizeof(size_t)\n\nstatic unsigned LZ4_64bits(void) { return sizeof(void*)==8; }\n\nstatic unsigned LZ4_isLittleEndian(void)\n{\n    const union { U32 i; BYTE c[4]; } one = { 1 };   /* don't use static : performance detrimental  */\n    return one.c[0];\n}\n\n\nstatic U16 LZ4_readLE16(const void* memPtr)\n{\n    if ((LZ4_UNALIGNED_ACCESS) && (LZ4_isLittleEndian()))\n        return *(U16*)memPtr;\n    else\n    {\n        const BYTE* p = memPtr;\n        return (U16)((U16)p[0] + (p[1]<<8));\n    }\n}\n\nstatic void LZ4_writeLE16(void* memPtr, U16 value)\n{\n    if ((LZ4_UNALIGNED_ACCESS) && (LZ4_isLittleEndian()))\n    {\n        *(U16*)memPtr = value;\n        return;\n    }\n    else\n    {\n        BYTE* p = memPtr;\n        p[0] = (BYTE) value;\n        p[1] = (BYTE)(value>>8);\n    }\n}\n\n\nstatic U16 LZ4_read16(const void* memPtr)\n{\n    if (LZ4_UNALIGNED_ACCESS)\n        return *(U16*)memPtr;\n    else\n    {\n        U16 val16;\n        memcpy(&val16, memPtr, 2);\n        return val16;\n    }\n}\n\nstatic U32 LZ4_read32(const void* memPtr)\n{\n    if (LZ4_UNALIGNED_ACCESS)\n        return *(U32*)memPtr;\n    else\n    {\n        U32 val32;\n        memcpy(&val32, memPtr, 4);\n        return val32;\n    }\n}\n\nstatic U64 LZ4_read64(const void* memPtr)\n{\n    if (LZ4_UNALIGNED_ACCESS)\n        return *(U64*)memPtr;\n    else\n    {\n        U64 val64;\n        memcpy(&val64, memPtr, 8);\n        return val64;\n    }\n}\n\nstatic size_t LZ4_read_ARCH(const void* p)\n{\n    if (LZ4_64bits())\n        return (size_t)LZ4_read64(p);\n    else\n        return (size_t)LZ4_read32(p);\n}\n\n\nstatic void LZ4_copy4(void* dstPtr, const void* srcPtr)\n{\n    if (LZ4_UNALIGNED_ACCESS)\n    {\n        *(U32*)dstPtr = *(U32*)srcPtr;\n        return;\n    }\n    memcpy(dstPtr, srcPtr, 4);\n}\n\nstatic void LZ4_copy8(void* dstPtr, const void* srcPtr)\n{\n#if GCC_VERSION!=409  /* disabled on GCC 4.9, as it generates invalid opcode (crash) */\n    if (LZ4_UNALIGNED_ACCESS)\n    {\n        if (LZ4_64bits())\n            *(U64*)dstPtr = *(U64*)srcPtr;\n        else\n            ((U32*)dstPtr)[0] = ((U32*)srcPtr)[0],\n            ((U32*)dstPtr)[1] = ((U32*)srcPtr)[1];\n        return;\n    }\n#endif\n    memcpy(dstPtr, srcPtr, 8);\n}\n\n/* customized version of memcpy, which may overwrite up to 7 bytes beyond dstEnd */\nstatic void LZ4_wildCopy(void* dstPtr, const void* srcPtr, void* dstEnd)\n{\n    BYTE* d = dstPtr;\n    const BYTE* s = srcPtr;\n    BYTE* e = dstEnd;\n    do { LZ4_copy8(d,s); d+=8; s+=8; } while (d<e);\n}\n\n\n/**************************************\n   Common Constants\n**************************************/\n#define MINMATCH 4\n\n#define COPYLENGTH 8\n#define LASTLITERALS 5\n#define MFLIMIT (COPYLENGTH+MINMATCH)\nstatic const int LZ4_minLength = (MFLIMIT+1);\n\n#define KB *(1 <<10)\n#define MB *(1 <<20)\n#define GB *(1U<<30)\n\n#define MAXD_LOG 16\n#define MAX_DISTANCE ((1 << MAXD_LOG) - 1)\n\n#define ML_BITS  4\n#define ML_MASK  ((1U<<ML_BITS)-1)\n#define RUN_BITS (8-ML_BITS)\n#define RUN_MASK ((1U<<RUN_BITS)-1)\n\n\n/**************************************\n   Common Utils\n**************************************/\n#define LZ4_STATIC_ASSERT(c)    { enum { LZ4_static_assert = 1/(int)(!!(c)) }; }   /* use only *after* variable declarations */\n\n\n/********************************\n   Common functions\n********************************/\nstatic unsigned LZ4_NbCommonBytes (register size_t val)\n{\n    if (LZ4_isLittleEndian())\n    {\n        if (LZ4_64bits())\n        {\n#       if defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT)\n            unsigned long r = 0;\n            _BitScanForward64( &r, (U64)val );\n            return (int)(r>>3);\n#       elif defined(__GNUC__) && (GCC_VERSION >= 304) && !defined(LZ4_FORCE_SW_BITCOUNT)\n            return (__builtin_ctzll((U64)val) >> 3);\n#       else\n            static const int DeBruijnBytePos[64] = { 0, 0, 0, 0, 0, 1, 1, 2, 0, 3, 1, 3, 1, 4, 2, 7, 0, 2, 3, 6, 1, 5, 3, 5, 1, 3, 4, 4, 2, 5, 6, 7, 7, 0, 1, 2, 3, 3, 4, 6, 2, 6, 5, 5, 3, 4, 5, 6, 7, 1, 2, 4, 6, 4, 4, 5, 7, 2, 6, 5, 7, 6, 7, 7 };\n            return DeBruijnBytePos[((U64)((val & -(long long)val) * 0x0218A392CDABBD3FULL)) >> 58];\n#       endif\n        }\n        else /* 32 bits */\n        {\n#       if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT)\n            unsigned long r;\n            _BitScanForward( &r, (U32)val );\n            return (int)(r>>3);\n#       elif defined(__GNUC__) && (GCC_VERSION >= 304) && !defined(LZ4_FORCE_SW_BITCOUNT)\n            return (__builtin_ctz((U32)val) >> 3);\n#       else\n            static const int DeBruijnBytePos[32] = { 0, 0, 3, 0, 3, 1, 3, 0, 3, 2, 2, 1, 3, 2, 0, 1, 3, 3, 1, 2, 2, 2, 2, 0, 3, 1, 2, 0, 1, 0, 1, 1 };\n            return DeBruijnBytePos[((U32)((val & -(S32)val) * 0x077CB531U)) >> 27];\n#       endif\n        }\n    }\n    else   /* Big Endian CPU */\n    {\n        if (LZ4_64bits())\n        {\n#       if defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT)\n            unsigned long r = 0;\n            _BitScanReverse64( &r, val );\n            return (unsigned)(r>>3);\n#       elif defined(__GNUC__) && (GCC_VERSION >= 304) && !defined(LZ4_FORCE_SW_BITCOUNT)\n            return (__builtin_clzll(val) >> 3);\n#       else\n            unsigned r;\n            if (!(val>>32)) { r=4; } else { r=0; val>>=32; }\n            if (!(val>>16)) { r+=2; val>>=8; } else { val>>=24; }\n            r += (!val);\n            return r;\n#       endif\n        }\n        else /* 32 bits */\n        {\n#       if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT)\n            unsigned long r = 0;\n            _BitScanReverse( &r, (unsigned long)val );\n            return (unsigned)(r>>3);\n#       elif defined(__GNUC__) && (GCC_VERSION >= 304) && !defined(LZ4_FORCE_SW_BITCOUNT)\n            return (__builtin_clz(val) >> 3);\n#       else\n            unsigned r;\n            if (!(val>>16)) { r=2; val>>=8; } else { r=0; val>>=24; }\n            r += (!val);\n            return r;\n#       endif\n        }\n    }\n}\n\nstatic unsigned LZ4_count(const BYTE* pIn, const BYTE* pMatch, const BYTE* pInLimit)\n{\n    const BYTE* const pStart = pIn;\n\n    while (likely(pIn<pInLimit-(STEPSIZE-1)))\n    {\n        size_t diff = LZ4_read_ARCH(pMatch) ^ LZ4_read_ARCH(pIn);\n        if (!diff) { pIn+=STEPSIZE; pMatch+=STEPSIZE; continue; }\n        pIn += LZ4_NbCommonBytes(diff);\n        return (unsigned)(pIn - pStart);\n    }\n\n    if (LZ4_64bits()) if ((pIn<(pInLimit-3)) && (LZ4_read32(pMatch) == LZ4_read32(pIn))) { pIn+=4; pMatch+=4; }\n    if ((pIn<(pInLimit-1)) && (LZ4_read16(pMatch) == LZ4_read16(pIn))) { pIn+=2; pMatch+=2; }\n    if ((pIn<pInLimit) && (*pMatch == *pIn)) pIn++;\n    return (unsigned)(pIn - pStart);\n}\n\n\n#ifndef LZ4_COMMONDEFS_ONLY\n/**************************************\n   Local Constants\n**************************************/\n#define LZ4_HASHLOG   (LZ4_MEMORY_USAGE-2)\n#define HASHTABLESIZE (1 << LZ4_MEMORY_USAGE)\n#define HASH_SIZE_U32 (1 << LZ4_HASHLOG)       /* required as macro for static allocation */\n\nstatic const int LZ4_64Klimit = ((64 KB) + (MFLIMIT-1));\nstatic const U32 LZ4_skipTrigger = 6;  /* Increase this value ==> compression run slower on incompressible data */\n\n\n/**************************************\n   Local Utils\n**************************************/\nint LZ4_versionNumber (void) { return LZ4_VERSION_NUMBER; }\nint LZ4_compressBound(int isize)  { return LZ4_COMPRESSBOUND(isize); }\n\n\n/**************************************\n   Local Structures and types\n**************************************/\ntypedef struct {\n    U32 hashTable[HASH_SIZE_U32];\n    U32 currentOffset;\n    U32 initCheck;\n    const BYTE* dictionary;\n    const BYTE* bufferStart;\n    U32 dictSize;\n} LZ4_stream_t_internal;\n\ntypedef enum { notLimited = 0, limitedOutput = 1 } limitedOutput_directive;\ntypedef enum { byPtr, byU32, byU16 } tableType_t;\n\ntypedef enum { noDict = 0, withPrefix64k, usingExtDict } dict_directive;\ntypedef enum { noDictIssue = 0, dictSmall } dictIssue_directive;\n\ntypedef enum { endOnOutputSize = 0, endOnInputSize = 1 } endCondition_directive;\ntypedef enum { full = 0, partial = 1 } earlyEnd_directive;\n\n\n\n/********************************\n   Compression functions\n********************************/\n\nstatic U32 LZ4_hashSequence(U32 sequence, tableType_t tableType)\n{\n    if (tableType == byU16)\n        return (((sequence) * 2654435761U) >> ((MINMATCH*8)-(LZ4_HASHLOG+1)));\n    else\n        return (((sequence) * 2654435761U) >> ((MINMATCH*8)-LZ4_HASHLOG));\n}\n\nstatic U32 LZ4_hashPosition(const BYTE* p, tableType_t tableType) { return LZ4_hashSequence(LZ4_read32(p), tableType); }\n\nstatic void LZ4_putPositionOnHash(const BYTE* p, U32 h, void* tableBase, tableType_t tableType, const BYTE* srcBase)\n{\n    switch (tableType)\n    {\n    case byPtr: { const BYTE** hashTable = (const BYTE**)tableBase; hashTable[h] = p; return; }\n    case byU32: { U32* hashTable = (U32*) tableBase; hashTable[h] = (U32)(p-srcBase); return; }\n    case byU16: { U16* hashTable = (U16*) tableBase; hashTable[h] = (U16)(p-srcBase); return; }\n    }\n}\n\nstatic void LZ4_putPosition(const BYTE* p, void* tableBase, tableType_t tableType, const BYTE* srcBase)\n{\n    U32 h = LZ4_hashPosition(p, tableType);\n    LZ4_putPositionOnHash(p, h, tableBase, tableType, srcBase);\n}\n\nstatic const BYTE* LZ4_getPositionOnHash(U32 h, void* tableBase, tableType_t tableType, const BYTE* srcBase)\n{\n    if (tableType == byPtr) { const BYTE** hashTable = (const BYTE**) tableBase; return hashTable[h]; }\n    if (tableType == byU32) { U32* hashTable = (U32*) tableBase; return hashTable[h] + srcBase; }\n    { U16* hashTable = (U16*) tableBase; return hashTable[h] + srcBase; }   /* default, to ensure a return */\n}\n\nstatic const BYTE* LZ4_getPosition(const BYTE* p, void* tableBase, tableType_t tableType, const BYTE* srcBase)\n{\n    U32 h = LZ4_hashPosition(p, tableType);\n    return LZ4_getPositionOnHash(h, tableBase, tableType, srcBase);\n}\n\nstatic int LZ4_compress_generic(\n                 void* ctx,\n                 const char* source,\n                 char* dest,\n                 int inputSize,\n                 int maxOutputSize,\n                 limitedOutput_directive outputLimited,\n                 tableType_t tableType,\n                 dict_directive dict,\n                 dictIssue_directive dictIssue)\n{\n    LZ4_stream_t_internal* const dictPtr = (LZ4_stream_t_internal*)ctx;\n\n    const BYTE* ip = (const BYTE*) source;\n    const BYTE* base;\n    const BYTE* lowLimit;\n    const BYTE* const lowRefLimit = ip - dictPtr->dictSize;\n    const BYTE* const dictionary = dictPtr->dictionary;\n    const BYTE* const dictEnd = dictionary + dictPtr->dictSize;\n    const size_t dictDelta = dictEnd - (const BYTE*)source;\n    const BYTE* anchor = (const BYTE*) source;\n    const BYTE* const iend = ip + inputSize;\n    const BYTE* const mflimit = iend - MFLIMIT;\n    const BYTE* const matchlimit = iend - LASTLITERALS;\n\n    BYTE* op = (BYTE*) dest;\n    BYTE* const olimit = op + maxOutputSize;\n\n    U32 forwardH;\n    size_t refDelta=0;\n\n    /* Init conditions */\n    if ((U32)inputSize > (U32)LZ4_MAX_INPUT_SIZE) return 0;          /* Unsupported input size, too large (or negative) */\n    switch(dict)\n    {\n    case noDict:\n    default:\n        base = (const BYTE*)source;\n        lowLimit = (const BYTE*)source;\n        break;\n    case withPrefix64k:\n        base = (const BYTE*)source - dictPtr->currentOffset;\n        lowLimit = (const BYTE*)source - dictPtr->dictSize;\n        break;\n    case usingExtDict:\n        base = (const BYTE*)source - dictPtr->currentOffset;\n        lowLimit = (const BYTE*)source;\n        break;\n    }\n    if ((tableType == byU16) && (inputSize>=LZ4_64Klimit)) return 0;   /* Size too large (not within 64K limit) */\n    if (inputSize<LZ4_minLength) goto _last_literals;                  /* Input too small, no compression (all literals) */\n\n    /* First Byte */\n    LZ4_putPosition(ip, ctx, tableType, base);\n    ip++; forwardH = LZ4_hashPosition(ip, tableType);\n\n    /* Main Loop */\n    for ( ; ; )\n    {\n        const BYTE* match;\n        BYTE* token;\n        {\n            const BYTE* forwardIp = ip;\n            unsigned step=1;\n            unsigned searchMatchNb = (1U << LZ4_skipTrigger);\n\n            /* Find a match */\n            do {\n                U32 h = forwardH;\n                ip = forwardIp;\n                forwardIp += step;\n                step = searchMatchNb++ >> LZ4_skipTrigger;\n\n                if (unlikely(forwardIp > mflimit)) goto _last_literals;\n\n                match = LZ4_getPositionOnHash(h, ctx, tableType, base);\n                if (dict==usingExtDict)\n                {\n                    if (match<(const BYTE*)source)\n                    {\n                        refDelta = dictDelta;\n                        lowLimit = dictionary;\n                    }\n                    else\n                    {\n                        refDelta = 0;\n                        lowLimit = (const BYTE*)source;\n                    }\n                }\n                forwardH = LZ4_hashPosition(forwardIp, tableType);\n                LZ4_putPositionOnHash(ip, h, ctx, tableType, base);\n\n            } while ( ((dictIssue==dictSmall) ? (match < lowRefLimit) : 0)\n                || ((tableType==byU16) ? 0 : (match + MAX_DISTANCE < ip))\n                || (LZ4_read32(match+refDelta) != LZ4_read32(ip)) );\n        }\n\n        /* Catch up */\n        while ((ip>anchor) && (match+refDelta > lowLimit) && (unlikely(ip[-1]==match[refDelta-1]))) { ip--; match--; }\n\n        {\n            /* Encode Literal length */\n            unsigned litLength = (unsigned)(ip - anchor);\n            token = op++;\n            if ((outputLimited) && (unlikely(op + litLength + (2 + 1 + LASTLITERALS) + (litLength/255) > olimit)))\n                return 0;   /* Check output limit */\n            if (litLength>=RUN_MASK)\n            {\n                int len = (int)litLength-RUN_MASK;\n                *token=(RUN_MASK<<ML_BITS);\n                for(; len >= 255 ; len-=255) *op++ = 255;\n                *op++ = (BYTE)len;\n            }\n            else *token = (BYTE)(litLength<<ML_BITS);\n\n            /* Copy Literals */\n            LZ4_wildCopy(op, anchor, op+litLength);\n            op+=litLength;\n        }\n\n_next_match:\n        /* Encode Offset */\n        LZ4_writeLE16(op, (U16)(ip-match)); op+=2;\n\n        /* Encode MatchLength */\n        {\n            unsigned matchLength;\n\n            if ((dict==usingExtDict) && (lowLimit==dictionary))\n            {\n                const BYTE* limit;\n                match += refDelta;\n                limit = ip + (dictEnd-match);\n                if (limit > matchlimit) limit = matchlimit;\n                matchLength = LZ4_count(ip+MINMATCH, match+MINMATCH, limit);\n                ip += MINMATCH + matchLength;\n                if (ip==limit)\n                {\n                    unsigned more = LZ4_count(ip, (const BYTE*)source, matchlimit);\n                    matchLength += more;\n                    ip += more;\n                }\n            }\n            else\n            {\n                matchLength = LZ4_count(ip+MINMATCH, match+MINMATCH, matchlimit);\n                ip += MINMATCH + matchLength;\n            }\n\n            if ((outputLimited) && (unlikely(op + (1 + LASTLITERALS) + (matchLength>>8) > olimit)))\n                return 0;    /* Check output limit */\n            if (matchLength>=ML_MASK)\n            {\n                *token += ML_MASK;\n                matchLength -= ML_MASK;\n                for (; matchLength >= 510 ; matchLength-=510) { *op++ = 255; *op++ = 255; }\n                if (matchLength >= 255) { matchLength-=255; *op++ = 255; }\n                *op++ = (BYTE)matchLength;\n            }\n            else *token += (BYTE)(matchLength);\n        }\n\n        anchor = ip;\n\n        /* Test end of chunk */\n        if (ip > mflimit) break;\n\n        /* Fill table */\n        LZ4_putPosition(ip-2, ctx, tableType, base);\n\n        /* Test next position */\n        match = LZ4_getPosition(ip, ctx, tableType, base);\n        if (dict==usingExtDict)\n        {\n            if (match<(const BYTE*)source)\n            {\n                refDelta = dictDelta;\n                lowLimit = dictionary;\n            }\n            else\n            {\n                refDelta = 0;\n                lowLimit = (const BYTE*)source;\n            }\n        }\n        LZ4_putPosition(ip, ctx, tableType, base);\n        if ( ((dictIssue==dictSmall) ? (match>=lowRefLimit) : 1)\n            && (match+MAX_DISTANCE>=ip)\n            && (LZ4_read32(match+refDelta)==LZ4_read32(ip)) )\n        { token=op++; *token=0; goto _next_match; }\n\n        /* Prepare next loop */\n        forwardH = LZ4_hashPosition(++ip, tableType);\n    }\n\n_last_literals:\n    /* Encode Last Literals */\n    {\n        int lastRun = (int)(iend - anchor);\n        if ((outputLimited) && (((char*)op - dest) + lastRun + 1 + ((lastRun+255-RUN_MASK)/255) > (U32)maxOutputSize))\n            return 0;   /* Check output limit */\n        if (lastRun>=(int)RUN_MASK) { *op++=(RUN_MASK<<ML_BITS); lastRun-=RUN_MASK; for(; lastRun >= 255 ; lastRun-=255) *op++ = 255; *op++ = (BYTE) lastRun; }\n        else *op++ = (BYTE)(lastRun<<ML_BITS);\n        memcpy(op, anchor, iend - anchor);\n        op += iend-anchor;\n    }\n\n    /* End */\n    return (int) (((char*)op)-dest);\n}\n\n\nint LZ4_compress(const char* source, char* dest, int inputSize)\n{\n#if (HEAPMODE)\n    void* ctx = ALLOCATOR(LZ4_STREAMSIZE_U64, 8);   /* Aligned on 8-bytes boundaries */\n#else\n    U64 ctx[LZ4_STREAMSIZE_U64] = {0};      /* Ensure data is aligned on 8-bytes boundaries */\n#endif\n    int result;\n\n    if (inputSize < LZ4_64Klimit)\n        result = LZ4_compress_generic((void*)ctx, source, dest, inputSize, 0, notLimited, byU16, noDict, noDictIssue);\n    else\n        result = LZ4_compress_generic((void*)ctx, source, dest, inputSize, 0, notLimited, LZ4_64bits() ? byU32 : byPtr, noDict, noDictIssue);\n\n#if (HEAPMODE)\n    FREEMEM(ctx);\n#endif\n    return result;\n}\n\nint LZ4_compress_limitedOutput(const char* source, char* dest, int inputSize, int maxOutputSize)\n{\n#if (HEAPMODE)\n    void* ctx = ALLOCATOR(LZ4_STREAMSIZE_U64, 8);   /* Aligned on 8-bytes boundaries */\n#else\n    U64 ctx[LZ4_STREAMSIZE_U64] = {0};      /* Ensure data is aligned on 8-bytes boundaries */\n#endif\n    int result;\n\n    if (inputSize < LZ4_64Klimit)\n        result = LZ4_compress_generic((void*)ctx, source, dest, inputSize, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue);\n    else\n        result = LZ4_compress_generic((void*)ctx, source, dest, inputSize, maxOutputSize, limitedOutput, LZ4_64bits() ? byU32 : byPtr, noDict, noDictIssue);\n\n#if (HEAPMODE)\n    FREEMEM(ctx);\n#endif\n    return result;\n}\n\n\n/*****************************************\n   Experimental : Streaming functions\n*****************************************/\n\n/*\n * LZ4_initStream\n * Use this function once, to init a newly allocated LZ4_stream_t structure\n * Return : 1 if OK, 0 if error\n */\nvoid LZ4_resetStream (LZ4_stream_t* LZ4_stream)\n{\n    MEM_INIT(LZ4_stream, 0, sizeof(LZ4_stream_t));\n}\n\nLZ4_stream_t* LZ4_createStream(void)\n{\n    LZ4_stream_t* lz4s = (LZ4_stream_t*)ALLOCATOR(8, LZ4_STREAMSIZE_U64);\n    LZ4_STATIC_ASSERT(LZ4_STREAMSIZE >= sizeof(LZ4_stream_t_internal));    /* A compilation error here means LZ4_STREAMSIZE is not large enough */\n    LZ4_resetStream(lz4s);\n    return lz4s;\n}\n\nint LZ4_freeStream (LZ4_stream_t* LZ4_stream)\n{\n    FREEMEM(LZ4_stream);\n    return (0);\n}\n\n\nint LZ4_loadDict (LZ4_stream_t* LZ4_dict, const char* dictionary, int dictSize)\n{\n    LZ4_stream_t_internal* dict = (LZ4_stream_t_internal*) LZ4_dict;\n    const BYTE* p = (const BYTE*)dictionary;\n    const BYTE* const dictEnd = p + dictSize;\n    const BYTE* base;\n\n    if (dict->initCheck) LZ4_resetStream(LZ4_dict);                         /* Uninitialized structure detected */\n\n    if (dictSize < MINMATCH)\n    {\n        dict->dictionary = NULL;\n        dict->dictSize = 0;\n        return 0;\n    }\n\n    if (p <= dictEnd - 64 KB) p = dictEnd - 64 KB;\n    base = p - dict->currentOffset;\n    dict->dictionary = p;\n    dict->dictSize = (U32)(dictEnd - p);\n    dict->currentOffset += dict->dictSize;\n\n    while (p <= dictEnd-MINMATCH)\n    {\n        LZ4_putPosition(p, dict, byU32, base);\n        p+=3;\n    }\n\n    return dict->dictSize;\n}\n\n\nstatic void LZ4_renormDictT(LZ4_stream_t_internal* LZ4_dict, const BYTE* src)\n{\n    if ((LZ4_dict->currentOffset > 0x80000000) ||\n        ((size_t)LZ4_dict->currentOffset > (size_t)src))   /* address space overflow */\n    {\n        /* rescale hash table */\n        U32 delta = LZ4_dict->currentOffset - 64 KB;\n        const BYTE* dictEnd = LZ4_dict->dictionary + LZ4_dict->dictSize;\n        int i;\n        for (i=0; i<HASH_SIZE_U32; i++)\n        {\n            if (LZ4_dict->hashTable[i] < delta) LZ4_dict->hashTable[i]=0;\n            else LZ4_dict->hashTable[i] -= delta;\n        }\n        LZ4_dict->currentOffset = 64 KB;\n        if (LZ4_dict->dictSize > 64 KB) LZ4_dict->dictSize = 64 KB;\n        LZ4_dict->dictionary = dictEnd - LZ4_dict->dictSize;\n    }\n}\n\n\nFORCE_INLINE int LZ4_compress_continue_generic (void* LZ4_stream, const char* source, char* dest, int inputSize,\n                                                int maxOutputSize, limitedOutput_directive limit)\n{\n    LZ4_stream_t_internal* streamPtr = (LZ4_stream_t_internal*)LZ4_stream;\n    const BYTE* const dictEnd = streamPtr->dictionary + streamPtr->dictSize;\n\n    const BYTE* smallest = (const BYTE*) source;\n    if (streamPtr->initCheck) return 0;   /* Uninitialized structure detected */\n    if ((streamPtr->dictSize>0) && (smallest>dictEnd)) smallest = dictEnd;\n    LZ4_renormDictT(streamPtr, smallest);\n\n    /* Check overlapping input/dictionary space */\n    {\n        const BYTE* sourceEnd = (const BYTE*) source + inputSize;\n        if ((sourceEnd > streamPtr->dictionary) && (sourceEnd < dictEnd))\n        {\n            streamPtr->dictSize = (U32)(dictEnd - sourceEnd);\n            if (streamPtr->dictSize > 64 KB) streamPtr->dictSize = 64 KB;\n            if (streamPtr->dictSize < 4) streamPtr->dictSize = 0;\n            streamPtr->dictionary = dictEnd - streamPtr->dictSize;\n        }\n    }\n\n    /* prefix mode : source data follows dictionary */\n    if (dictEnd == (const BYTE*)source)\n    {\n        int result;\n        if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset))\n            result = LZ4_compress_generic(LZ4_stream, source, dest, inputSize, maxOutputSize, limit, byU32, withPrefix64k, dictSmall);\n        else\n            result = LZ4_compress_generic(LZ4_stream, source, dest, inputSize, maxOutputSize, limit, byU32, withPrefix64k, noDictIssue);\n        streamPtr->dictSize += (U32)inputSize;\n        streamPtr->currentOffset += (U32)inputSize;\n        return result;\n    }\n\n    /* external dictionary mode */\n    {\n        int result;\n        if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset))\n            result = LZ4_compress_generic(LZ4_stream, source, dest, inputSize, maxOutputSize, limit, byU32, usingExtDict, dictSmall);\n        else\n            result = LZ4_compress_generic(LZ4_stream, source, dest, inputSize, maxOutputSize, limit, byU32, usingExtDict, noDictIssue);\n        streamPtr->dictionary = (const BYTE*)source;\n        streamPtr->dictSize = (U32)inputSize;\n        streamPtr->currentOffset += (U32)inputSize;\n        return result;\n    }\n}\n\nint LZ4_compress_continue (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize)\n{\n    return LZ4_compress_continue_generic(LZ4_stream, source, dest, inputSize, 0, notLimited);\n}\n\nint LZ4_compress_limitedOutput_continue (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize, int maxOutputSize)\n{\n    return LZ4_compress_continue_generic(LZ4_stream, source, dest, inputSize, maxOutputSize, limitedOutput);\n}\n\n\n/* Hidden debug function, to force separate dictionary mode */\nint LZ4_compress_forceExtDict (LZ4_stream_t* LZ4_dict, const char* source, char* dest, int inputSize)\n{\n    LZ4_stream_t_internal* streamPtr = (LZ4_stream_t_internal*)LZ4_dict;\n    int result;\n    const BYTE* const dictEnd = streamPtr->dictionary + streamPtr->dictSize;\n\n    const BYTE* smallest = dictEnd;\n    if (smallest > (const BYTE*) source) smallest = (const BYTE*) source;\n    LZ4_renormDictT((LZ4_stream_t_internal*)LZ4_dict, smallest);\n\n    result = LZ4_compress_generic(LZ4_dict, source, dest, inputSize, 0, notLimited, byU32, usingExtDict, noDictIssue);\n\n    streamPtr->dictionary = (const BYTE*)source;\n    streamPtr->dictSize = (U32)inputSize;\n    streamPtr->currentOffset += (U32)inputSize;\n\n    return result;\n}\n\n\nint LZ4_saveDict (LZ4_stream_t* LZ4_dict, char* safeBuffer, int dictSize)\n{\n    LZ4_stream_t_internal* dict = (LZ4_stream_t_internal*) LZ4_dict;\n    const BYTE* previousDictEnd = dict->dictionary + dict->dictSize;\n\n    if ((U32)dictSize > 64 KB) dictSize = 64 KB;   /* useless to define a dictionary > 64 KB */\n    if ((U32)dictSize > dict->dictSize) dictSize = dict->dictSize;\n\n    memmove(safeBuffer, previousDictEnd - dictSize, dictSize);\n\n    dict->dictionary = (const BYTE*)safeBuffer;\n    dict->dictSize = (U32)dictSize;\n\n    return dictSize;\n}\n\n\n\n/****************************\n   Decompression functions\n****************************/\n/*\n * This generic decompression function cover all use cases.\n * It shall be instantiated several times, using different sets of directives\n * Note that it is essential this generic function is really inlined,\n * in order to remove useless branches during compilation optimization.\n */\nFORCE_INLINE int LZ4_decompress_generic(\n                 const char* const source,\n                 char* const dest,\n                 int inputSize,\n                 int outputSize,         /* If endOnInput==endOnInputSize, this value is the max size of Output Buffer. */\n\n                 int endOnInput,         /* endOnOutputSize, endOnInputSize */\n                 int partialDecoding,    /* full, partial */\n                 int targetOutputSize,   /* only used if partialDecoding==partial */\n                 int dict,               /* noDict, withPrefix64k, usingExtDict */\n                 const BYTE* const lowPrefix,  /* == dest if dict == noDict */\n                 const BYTE* const dictStart,  /* only if dict==usingExtDict */\n                 const size_t dictSize         /* note : = 0 if noDict */\n                 )\n{\n    /* Local Variables */\n    const BYTE* restrict ip = (const BYTE*) source;\n    const BYTE* const iend = ip + inputSize;\n\n    BYTE* op = (BYTE*) dest;\n    BYTE* const oend = op + outputSize;\n    BYTE* cpy;\n    BYTE* oexit = op + targetOutputSize;\n    const BYTE* const lowLimit = lowPrefix - dictSize;\n\n    const BYTE* const dictEnd = (const BYTE*)dictStart + dictSize;\n    const size_t dec32table[] = {4, 1, 2, 1, 4, 4, 4, 4};\n    const size_t dec64table[] = {0, 0, 0, (size_t)-1, 0, 1, 2, 3};\n\n    const int safeDecode = (endOnInput==endOnInputSize);\n    const int checkOffset = ((safeDecode) && (dictSize < (int)(64 KB)));\n\n\n    /* Special cases */\n    if ((partialDecoding) && (oexit> oend-MFLIMIT)) oexit = oend-MFLIMIT;                         /* targetOutputSize too high => decode everything */\n    if ((endOnInput) && (unlikely(outputSize==0))) return ((inputSize==1) && (*ip==0)) ? 0 : -1;  /* Empty output buffer */\n    if ((!endOnInput) && (unlikely(outputSize==0))) return (*ip==0?1:-1);\n\n\n    /* Main Loop */\n    while (1)\n    {\n        unsigned token;\n        size_t length;\n        const BYTE* match;\n\n        /* get literal length */\n        token = *ip++;\n        if ((length=(token>>ML_BITS)) == RUN_MASK)\n        {\n            unsigned s;\n            do\n            {\n                s = *ip++;\n                length += s;\n            }\n            while (likely((endOnInput)?ip<iend-RUN_MASK:1) && (s==255));\n            if ((safeDecode) && unlikely((size_t)(op+length)<(size_t)(op))) goto _output_error;   /* overflow detection */\n            if ((safeDecode) && unlikely((size_t)(ip+length)<(size_t)(ip))) goto _output_error;   /* overflow detection */\n        }\n\n        /* copy literals */\n        cpy = op+length;\n        if (((endOnInput) && ((cpy>(partialDecoding?oexit:oend-MFLIMIT)) || (ip+length>iend-(2+1+LASTLITERALS))) )\n            || ((!endOnInput) && (cpy>oend-COPYLENGTH)))\n        {\n            if (partialDecoding)\n            {\n                if (cpy > oend) goto _output_error;                           /* Error : write attempt beyond end of output buffer */\n                if ((endOnInput) && (ip+length > iend)) goto _output_error;   /* Error : read attempt beyond end of input buffer */\n            }\n            else\n            {\n                if ((!endOnInput) && (cpy != oend)) goto _output_error;       /* Error : block decoding must stop exactly there */\n                if ((endOnInput) && ((ip+length != iend) || (cpy > oend))) goto _output_error;   /* Error : input must be consumed */\n            }\n            memcpy(op, ip, length);\n            ip += length;\n            op += length;\n            break;     /* Necessarily EOF, due to parsing restrictions */\n        }\n        LZ4_wildCopy(op, ip, cpy);\n        ip += length; op = cpy;\n\n        /* get offset */\n        match = cpy - LZ4_readLE16(ip); ip+=2;\n        if ((checkOffset) && (unlikely(match < lowLimit))) goto _output_error;   /* Error : offset outside destination buffer */\n\n        /* get matchlength */\n        length = token & ML_MASK;\n        if (length == ML_MASK)\n        {\n            unsigned s;\n            do\n            {\n                if ((endOnInput) && (ip > iend-LASTLITERALS)) goto _output_error;\n                s = *ip++;\n                length += s;\n            } while (s==255);\n            if ((safeDecode) && unlikely((size_t)(op+length)<(size_t)op)) goto _output_error;   /* overflow detection */\n        }\n        length += MINMATCH;\n\n        /* check external dictionary */\n        if ((dict==usingExtDict) && (match < lowPrefix))\n        {\n            if (unlikely(op+length > oend-LASTLITERALS)) goto _output_error;   /* doesn't respect parsing restriction */\n\n            if (length <= (size_t)(lowPrefix-match))\n            {\n                /* match can be copied as a single segment from external dictionary */\n                match = dictEnd - (lowPrefix-match);\n                memcpy(op, match, length);\n                op += length;\n            }\n            else\n            {\n                /* match encompass external dictionary and current segment */\n                size_t copySize = (size_t)(lowPrefix-match);\n                memcpy(op, dictEnd - copySize, copySize);\n                op += copySize;\n                copySize = length - copySize;\n                if (copySize > (size_t)(op-lowPrefix))   /* overlap within current segment */\n                {\n                    BYTE* const endOfMatch = op + copySize;\n                    const BYTE* copyFrom = lowPrefix;\n                    while (op < endOfMatch) *op++ = *copyFrom++;\n                }\n                else\n                {\n                    memcpy(op, lowPrefix, copySize);\n                    op += copySize;\n                }\n            }\n            continue;\n        }\n\n        /* copy repeated sequence */\n        cpy = op + length;\n        if (unlikely((op-match)<8))\n        {\n            const size_t dec64 = dec64table[op-match];\n            op[0] = match[0];\n            op[1] = match[1];\n            op[2] = match[2];\n            op[3] = match[3];\n            match += dec32table[op-match];\n            LZ4_copy4(op+4, match);\n            op += 8; match -= dec64;\n        } else { LZ4_copy8(op, match); op+=8; match+=8; }\n\n        if (unlikely(cpy>oend-12))\n        {\n            if (cpy > oend-LASTLITERALS) goto _output_error;    /* Error : last LASTLITERALS bytes must be literals */\n            if (op < oend-8)\n            {\n                LZ4_wildCopy(op, match, oend-8);\n                match += (oend-8) - op;\n                op = oend-8;\n            }\n            while (op<cpy) *op++ = *match++;\n        }\n        else\n            LZ4_wildCopy(op, match, cpy);\n        op=cpy;   /* correction */\n    }\n\n    /* end of decoding */\n    if (endOnInput)\n       return (int) (((char*)op)-dest);     /* Nb of output bytes decoded */\n    else\n       return (int) (((char*)ip)-source);   /* Nb of input bytes read */\n\n    /* Overflow error detected */\n_output_error:\n    return (int) (-(((char*)ip)-source))-1;\n}\n\n\nint LZ4_decompress_safe(const char* source, char* dest, int compressedSize, int maxDecompressedSize)\n{\n    return LZ4_decompress_generic(source, dest, compressedSize, maxDecompressedSize, endOnInputSize, full, 0, noDict, (BYTE*)dest, NULL, 0);\n}\n\nint LZ4_decompress_safe_partial(const char* source, char* dest, int compressedSize, int targetOutputSize, int maxDecompressedSize)\n{\n    return LZ4_decompress_generic(source, dest, compressedSize, maxDecompressedSize, endOnInputSize, partial, targetOutputSize, noDict, (BYTE*)dest, NULL, 0);\n}\n\nint LZ4_decompress_fast(const char* source, char* dest, int originalSize)\n{\n    return LZ4_decompress_generic(source, dest, 0, originalSize, endOnOutputSize, full, 0, withPrefix64k, (BYTE*)(dest - 64 KB), NULL, 64 KB);\n}\n\n\n/* streaming decompression functions */\n\ntypedef struct\n{\n    BYTE* externalDict;\n    size_t extDictSize;\n    BYTE* prefixEnd;\n    size_t prefixSize;\n} LZ4_streamDecode_t_internal;\n\n/*\n * If you prefer dynamic allocation methods,\n * LZ4_createStreamDecode()\n * provides a pointer (void*) towards an initialized LZ4_streamDecode_t structure.\n */\nLZ4_streamDecode_t* LZ4_createStreamDecode(void)\n{\n    LZ4_streamDecode_t* lz4s = (LZ4_streamDecode_t*) ALLOCATOR(sizeof(U64), LZ4_STREAMDECODESIZE_U64);\n    return lz4s;\n}\n\nint LZ4_freeStreamDecode (LZ4_streamDecode_t* LZ4_stream)\n{\n    FREEMEM(LZ4_stream);\n    return 0;\n}\n\n/*\n * LZ4_setStreamDecode\n * Use this function to instruct where to find the dictionary\n * This function is not necessary if previous data is still available where it was decoded.\n * Loading a size of 0 is allowed (same effect as no dictionary).\n * Return : 1 if OK, 0 if error\n */\nint LZ4_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const char* dictionary, int dictSize)\n{\n    LZ4_streamDecode_t_internal* lz4sd = (LZ4_streamDecode_t_internal*) LZ4_streamDecode;\n    lz4sd->prefixSize = (size_t) dictSize;\n    lz4sd->prefixEnd = (BYTE*) dictionary + dictSize;\n    lz4sd->externalDict = NULL;\n    lz4sd->extDictSize  = 0;\n    return 1;\n}\n\n/*\n*_continue() :\n    These decoding functions allow decompression of multiple blocks in \"streaming\" mode.\n    Previously decoded blocks must still be available at the memory position where they were decoded.\n    If it's not possible, save the relevant part of decoded data into a safe buffer,\n    and indicate where it stands using LZ4_setStreamDecode()\n*/\nint LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int compressedSize, int maxOutputSize)\n{\n    LZ4_streamDecode_t_internal* lz4sd = (LZ4_streamDecode_t_internal*) LZ4_streamDecode;\n    int result;\n\n    if (lz4sd->prefixEnd == (BYTE*)dest)\n    {\n        result = LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize,\n                                        endOnInputSize, full, 0,\n                                        usingExtDict, lz4sd->prefixEnd - lz4sd->prefixSize, lz4sd->externalDict, lz4sd->extDictSize);\n        if (result <= 0) return result;\n        lz4sd->prefixSize += result;\n        lz4sd->prefixEnd  += result;\n    }\n    else\n    {\n        lz4sd->extDictSize = lz4sd->prefixSize;\n        lz4sd->externalDict = lz4sd->prefixEnd - lz4sd->extDictSize;\n        result = LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize,\n                                        endOnInputSize, full, 0,\n                                        usingExtDict, (BYTE*)dest, lz4sd->externalDict, lz4sd->extDictSize);\n        if (result <= 0) return result;\n        lz4sd->prefixSize = result;\n        lz4sd->prefixEnd  = (BYTE*)dest + result;\n    }\n\n    return result;\n}\n\nint LZ4_decompress_fast_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int originalSize)\n{\n    LZ4_streamDecode_t_internal* lz4sd = (LZ4_streamDecode_t_internal*) LZ4_streamDecode;\n    int result;\n\n    if (lz4sd->prefixEnd == (BYTE*)dest)\n    {\n        result = LZ4_decompress_generic(source, dest, 0, originalSize,\n                                        endOnOutputSize, full, 0,\n                                        usingExtDict, lz4sd->prefixEnd - lz4sd->prefixSize, lz4sd->externalDict, lz4sd->extDictSize);\n        if (result <= 0) return result;\n        lz4sd->prefixSize += originalSize;\n        lz4sd->prefixEnd  += originalSize;\n    }\n    else\n    {\n        lz4sd->extDictSize = lz4sd->prefixSize;\n        lz4sd->externalDict = (BYTE*)dest - lz4sd->extDictSize;\n        result = LZ4_decompress_generic(source, dest, 0, originalSize,\n                                        endOnOutputSize, full, 0,\n                                        usingExtDict, (BYTE*)dest, lz4sd->externalDict, lz4sd->extDictSize);\n        if (result <= 0) return result;\n        lz4sd->prefixSize = originalSize;\n        lz4sd->prefixEnd  = (BYTE*)dest + originalSize;\n    }\n\n    return result;\n}\n\n\n/*\nAdvanced decoding functions :\n*_usingDict() :\n    These decoding functions work the same as \"_continue\" ones,\n    the dictionary must be explicitly provided within parameters\n*/\n\nFORCE_INLINE int LZ4_decompress_usingDict_generic(const char* source, char* dest, int compressedSize, int maxOutputSize, int safe, const char* dictStart, int dictSize)\n{\n    if (dictSize==0)\n        return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, safe, full, 0, noDict, (BYTE*)dest, NULL, 0);\n    if (dictStart+dictSize == dest)\n    {\n        if (dictSize >= (int)(64 KB - 1))\n            return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, safe, full, 0, withPrefix64k, (BYTE*)dest-64 KB, NULL, 0);\n        return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, safe, full, 0, noDict, (BYTE*)dest-dictSize, NULL, 0);\n    }\n    return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, safe, full, 0, usingExtDict, (BYTE*)dest, (BYTE*)dictStart, dictSize);\n}\n\nint LZ4_decompress_safe_usingDict(const char* source, char* dest, int compressedSize, int maxOutputSize, const char* dictStart, int dictSize)\n{\n    return LZ4_decompress_usingDict_generic(source, dest, compressedSize, maxOutputSize, 1, dictStart, dictSize);\n}\n\nint LZ4_decompress_fast_usingDict(const char* source, char* dest, int originalSize, const char* dictStart, int dictSize)\n{\n    return LZ4_decompress_usingDict_generic(source, dest, 0, originalSize, 0, dictStart, dictSize);\n}\n\n/* debug function */\nint LZ4_decompress_safe_forceExtDict(const char* source, char* dest, int compressedSize, int maxOutputSize, const char* dictStart, int dictSize)\n{\n    return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, endOnInputSize, full, 0, usingExtDict, (BYTE*)dest, (BYTE*)dictStart, dictSize);\n}\n\n\n/***************************************************\n    Obsolete Functions\n***************************************************/\n/*\nThese function names are deprecated and should no longer be used.\nThey are only provided here for compatibility with older user programs.\n- LZ4_uncompress is totally equivalent to LZ4_decompress_fast\n- LZ4_uncompress_unknownOutputSize is totally equivalent to LZ4_decompress_safe\n*/\nint LZ4_uncompress (const char* source, char* dest, int outputSize) { return LZ4_decompress_fast(source, dest, outputSize); }\nint LZ4_uncompress_unknownOutputSize (const char* source, char* dest, int isize, int maxOutputSize) { return LZ4_decompress_safe(source, dest, isize, maxOutputSize); }\n\n\n/* Obsolete Streaming functions */\n\nint LZ4_sizeofStreamState() { return LZ4_STREAMSIZE; }\n\nstatic void LZ4_init(LZ4_stream_t_internal* lz4ds, const BYTE* base)\n{\n    MEM_INIT(lz4ds, 0, LZ4_STREAMSIZE);\n    lz4ds->bufferStart = base;\n}\n\nint LZ4_resetStreamState(void* state, const char* inputBuffer)\n{\n    if ((((size_t)state) & 3) != 0) return 1;   /* Error : pointer is not aligned on 4-bytes boundary */\n    LZ4_init((LZ4_stream_t_internal*)state, (const BYTE*)inputBuffer);\n    return 0;\n}\n\nvoid* LZ4_create (const char* inputBuffer)\n{\n    void* lz4ds = ALLOCATOR(8, LZ4_STREAMSIZE_U64);\n    LZ4_init ((LZ4_stream_t_internal*)lz4ds, (const BYTE*)inputBuffer);\n    return lz4ds;\n}\n\nchar* LZ4_slideInputBuffer (void* LZ4_Data)\n{\n    LZ4_stream_t_internal* ctx = (LZ4_stream_t_internal*)LZ4_Data;\n    int dictSize = LZ4_saveDict((LZ4_stream_t*)ctx, (char*)ctx->bufferStart, 64 KB);\n    return (char*)(ctx->bufferStart + dictSize);\n}\n\n/*  Obsolete compresson functions using User-allocated state */\n\nint LZ4_sizeofState() { return LZ4_STREAMSIZE; }\n\nint LZ4_compress_withState (void* state, const char* source, char* dest, int inputSize)\n{\n    if (((size_t)(state)&3) != 0) return 0;   /* Error : state is not aligned on 4-bytes boundary */\n    MEM_INIT(state, 0, LZ4_STREAMSIZE);\n\n    if (inputSize < LZ4_64Klimit)\n        return LZ4_compress_generic(state, source, dest, inputSize, 0, notLimited, byU16, noDict, noDictIssue);\n    else\n        return LZ4_compress_generic(state, source, dest, inputSize, 0, notLimited, LZ4_64bits() ? byU32 : byPtr, noDict, noDictIssue);\n}\n\nint LZ4_compress_limitedOutput_withState (void* state, const char* source, char* dest, int inputSize, int maxOutputSize)\n{\n    if (((size_t)(state)&3) != 0) return 0;   /* Error : state is not aligned on 4-bytes boundary */\n    MEM_INIT(state, 0, LZ4_STREAMSIZE);\n\n    if (inputSize < LZ4_64Klimit)\n        return LZ4_compress_generic(state, source, dest, inputSize, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue);\n    else\n        return LZ4_compress_generic(state, source, dest, inputSize, maxOutputSize, limitedOutput, LZ4_64bits() ? byU32 : byPtr, noDict, noDictIssue);\n}\n\n/* Obsolete streaming decompression functions */\n\nint LZ4_decompress_safe_withPrefix64k(const char* source, char* dest, int compressedSize, int maxOutputSize)\n{\n    return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, endOnInputSize, full, 0, withPrefix64k, (BYTE*)dest - 64 KB, NULL, 64 KB);\n}\n\nint LZ4_decompress_fast_withPrefix64k(const char* source, char* dest, int originalSize)\n{\n    return LZ4_decompress_generic(source, dest, 0, originalSize, endOnOutputSize, full, 0, withPrefix64k, (BYTE*)dest - 64 KB, NULL, 64 KB);\n}\n\n#endif   /* LZ4_COMMONDEFS_ONLY */\n\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/imgui_remote/lz4/lz4.h",
    "content": "/*\n   LZ4 - Fast LZ compression algorithm\n   Header File\n   Copyright (C) 2011-2014, Yann Collet.\n   BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)\n\n   Redistribution and use in source and binary forms, with or without\n   modification, are permitted provided that the following conditions are\n   met:\n\n       * Redistributions of source code must retain the above copyright\n   notice, this list of conditions and the following disclaimer.\n       * Redistributions in binary form must reproduce the above\n   copyright notice, this list of conditions and the following disclaimer\n   in the documentation and/or other materials provided with the\n   distribution.\n\n   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n   \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n   You can contact the author at :\n   - LZ4 source repository : http://code.google.com/p/lz4/\n   - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c\n*/\n#pragma once\n\n#if defined (__cplusplus)\nextern \"C\" {\n#endif\n\n/*\n * lz4.h provides raw compression format functions, for optimal performance and integration into programs.\n * If you need to generate data using an inter-operable format (respecting the framing specification),\n * please use lz4frame.h instead.\n*/\n\n/**************************************\n   Version\n**************************************/\n#define LZ4_VERSION_MAJOR    1    /* for breaking interface changes  */\n#define LZ4_VERSION_MINOR    5    /* for new (non-breaking) interface capabilities */\n#define LZ4_VERSION_RELEASE  0    /* for tweaks, bug-fixes, or development */\n#define LZ4_VERSION_NUMBER (LZ4_VERSION_MAJOR *100*100 + LZ4_VERSION_MINOR *100 + LZ4_VERSION_RELEASE)\nint LZ4_versionNumber (void);\n\n/**************************************\n   Tuning parameter\n**************************************/\n/*\n * LZ4_MEMORY_USAGE :\n * Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.)\n * Increasing memory usage improves compression ratio\n * Reduced memory usage can improve speed, due to cache effect\n * Default value is 14, for 16KB, which nicely fits into Intel x86 L1 cache\n */\n#define LZ4_MEMORY_USAGE 14\n\n\n/**************************************\n   Simple Functions\n**************************************/\n\nint LZ4_compress        (const char* source, char* dest, int sourceSize);\nint LZ4_decompress_safe (const char* source, char* dest, int compressedSize, int maxDecompressedSize);\n\n/*\nLZ4_compress() :\n    Compresses 'sourceSize' bytes from 'source' into 'dest'.\n    Destination buffer must be already allocated,\n    and must be sized to handle worst cases situations (input data not compressible)\n    Worst case size evaluation is provided by function LZ4_compressBound()\n    inputSize : Max supported value is LZ4_MAX_INPUT_SIZE\n    return : the number of bytes written in buffer dest\n             or 0 if the compression fails\n\nLZ4_decompress_safe() :\n    compressedSize : is obviously the source size\n    maxDecompressedSize : is the size of the destination buffer, which must be already allocated.\n    return : the number of bytes decompressed into the destination buffer (necessarily <= maxDecompressedSize)\n             If the destination buffer is not large enough, decoding will stop and output an error code (<0).\n             If the source stream is detected malformed, the function will stop decoding and return a negative result.\n             This function is protected against buffer overflow exploits,\n             and never writes outside of output buffer, nor reads outside of input buffer.\n             It is also protected against malicious data packets.\n*/\n\n\n/**************************************\n   Advanced Functions\n**************************************/\n#define LZ4_MAX_INPUT_SIZE        0x7E000000   /* 2 113 929 216 bytes */\n#define LZ4_COMPRESSBOUND(isize)  ((unsigned int)(isize) > (unsigned int)LZ4_MAX_INPUT_SIZE ? 0 : (isize) + ((isize)/255) + 16)\n\n/*\nLZ4_compressBound() :\n    Provides the maximum size that LZ4 compression may output in a \"worst case\" scenario (input data not compressible)\n    This function is primarily useful for memory allocation purposes (output buffer size).\n    Macro LZ4_COMPRESSBOUND() is also provided for compilation-time evaluation (stack memory allocation for example).\n\n    isize  : is the input size. Max supported value is LZ4_MAX_INPUT_SIZE\n    return : maximum output size in a \"worst case\" scenario\n             or 0, if input size is too large ( > LZ4_MAX_INPUT_SIZE)\n*/\nint LZ4_compressBound(int isize);\n\n\n/*\nLZ4_compress_limitedOutput() :\n    Compress 'sourceSize' bytes from 'source' into an output buffer 'dest' of maximum size 'maxOutputSize'.\n    If it cannot achieve it, compression will stop, and result of the function will be zero.\n    This saves time and memory on detecting non-compressible (or barely compressible) data.\n    This function never writes outside of provided output buffer.\n\n    sourceSize  : Max supported value is LZ4_MAX_INPUT_VALUE\n    maxOutputSize : is the size of the destination buffer (which must be already allocated)\n    return : the number of bytes written in buffer 'dest'\n             or 0 if compression fails\n*/\nint LZ4_compress_limitedOutput (const char* source, char* dest, int sourceSize, int maxOutputSize);\n\n\n/*\nLZ4_compress_withState() :\n    Same compression functions, but using an externally allocated memory space to store compression state.\n    Use LZ4_sizeofState() to know how much memory must be allocated,\n    and then, provide it as 'void* state' to compression functions.\n*/\nint LZ4_sizeofState(void);\nint LZ4_compress_withState               (void* state, const char* source, char* dest, int inputSize);\nint LZ4_compress_limitedOutput_withState (void* state, const char* source, char* dest, int inputSize, int maxOutputSize);\n\n\n/*\nLZ4_decompress_fast() :\n    originalSize : is the original and therefore uncompressed size\n    return : the number of bytes read from the source buffer (in other words, the compressed size)\n             If the source stream is detected malformed, the function will stop decoding and return a negative result.\n             Destination buffer must be already allocated. Its size must be a minimum of 'originalSize' bytes.\n    note : This function fully respect memory boundaries for properly formed compressed data.\n           It is a bit faster than LZ4_decompress_safe().\n           However, it does not provide any protection against intentionally modified data stream (malicious input).\n           Use this function in trusted environment only (data to decode comes from a trusted source).\n*/\nint LZ4_decompress_fast (const char* source, char* dest, int originalSize);\n\n\n/*\nLZ4_decompress_safe_partial() :\n    This function decompress a compressed block of size 'compressedSize' at position 'source'\n    into destination buffer 'dest' of size 'maxDecompressedSize'.\n    The function tries to stop decompressing operation as soon as 'targetOutputSize' has been reached,\n    reducing decompression time.\n    return : the number of bytes decoded in the destination buffer (necessarily <= maxDecompressedSize)\n       Note : this number can be < 'targetOutputSize' should the compressed block to decode be smaller.\n             Always control how many bytes were decoded.\n             If the source stream is detected malformed, the function will stop decoding and return a negative result.\n             This function never writes outside of output buffer, and never reads outside of input buffer. It is therefore protected against malicious data packets\n*/\nint LZ4_decompress_safe_partial (const char* source, char* dest, int compressedSize, int targetOutputSize, int maxDecompressedSize);\n\n\n/***********************************************\n   Streaming Compression Functions\n***********************************************/\n\n#define LZ4_STREAMSIZE_U64 ((1 << (LZ4_MEMORY_USAGE-3)) + 4)\n#define LZ4_STREAMSIZE     (LZ4_STREAMSIZE_U64 * sizeof(long long))\n/*\n * LZ4_stream_t\n * information structure to track an LZ4 stream.\n * important : init this structure content before first use !\n * note : only allocated directly the structure if you are statically linking LZ4\n *        If you are using liblz4 as a DLL, please use below construction methods instead.\n */\ntypedef struct { long long table[LZ4_STREAMSIZE_U64]; } LZ4_stream_t;\n\n/*\n * LZ4_resetStream\n * Use this function to init an allocated LZ4_stream_t structure\n */\nvoid LZ4_resetStream (LZ4_stream_t* LZ4_streamPtr);\n\n/*\n * LZ4_createStream will allocate and initialize an LZ4_stream_t structure\n * LZ4_freeStream releases its memory.\n * In the context of a DLL (liblz4), please use these methods rather than the static struct.\n * They are more future proof, in case of a change of LZ4_stream_t size.\n */\nLZ4_stream_t* LZ4_createStream(void);\nint           LZ4_freeStream (LZ4_stream_t* LZ4_streamPtr);\n\n/*\n * LZ4_loadDict\n * Use this function to load a static dictionary into LZ4_stream.\n * Any previous data will be forgotten, only 'dictionary' will remain in memory.\n * Loading a size of 0 is allowed.\n * Return : dictionary size, in bytes (necessarily <= 64 KB)\n */\nint LZ4_loadDict (LZ4_stream_t* LZ4_streamPtr, const char* dictionary, int dictSize);\n\n/*\n * LZ4_compress_continue\n * Compress data block 'source', using blocks compressed before as dictionary to improve compression ratio\n * Previous data blocks are assumed to still be present at their previous location.\n */\nint LZ4_compress_continue (LZ4_stream_t* LZ4_streamPtr, const char* source, char* dest, int inputSize);\n\n/*\n * LZ4_compress_limitedOutput_continue\n * Same as before, but also specify a maximum target compressed size (maxOutputSize)\n * If objective cannot be met, compression exits, and returns a zero.\n */\nint LZ4_compress_limitedOutput_continue (LZ4_stream_t* LZ4_streamPtr, const char* source, char* dest, int inputSize, int maxOutputSize);\n\n/*\n * LZ4_saveDict\n * If previously compressed data block is not guaranteed to remain available at its memory location\n * save it into a safer place (char* safeBuffer)\n * Note : you don't need to call LZ4_loadDict() afterwards,\n *        dictionary is immediately usable, you can therefore call again LZ4_compress_continue()\n * Return : dictionary size in bytes, or 0 if error\n * Note : any dictSize > 64 KB will be interpreted as 64KB.\n */\nint LZ4_saveDict (LZ4_stream_t* LZ4_streamPtr, char* safeBuffer, int dictSize);\n\n\n/************************************************\n   Streaming Decompression Functions\n************************************************/\n\n#define LZ4_STREAMDECODESIZE_U64  4\n#define LZ4_STREAMDECODESIZE     (LZ4_STREAMDECODESIZE_U64 * sizeof(unsigned long long))\ntypedef struct { unsigned long long table[LZ4_STREAMDECODESIZE_U64]; } LZ4_streamDecode_t;\n/*\n * LZ4_streamDecode_t\n * information structure to track an LZ4 stream.\n * init this structure content using LZ4_setStreamDecode or memset() before first use !\n *\n * In the context of a DLL (liblz4) please prefer usage of construction methods below.\n * They are more future proof, in case of a change of LZ4_streamDecode_t size in the future.\n * LZ4_createStreamDecode will allocate and initialize an LZ4_streamDecode_t structure\n * LZ4_freeStreamDecode releases its memory.\n */\nLZ4_streamDecode_t* LZ4_createStreamDecode(void);\nint                 LZ4_freeStreamDecode (LZ4_streamDecode_t* LZ4_stream);\n\n/*\n * LZ4_setStreamDecode\n * Use this function to instruct where to find the dictionary.\n * Setting a size of 0 is allowed (same effect as reset).\n * Return : 1 if OK, 0 if error\n */\nint LZ4_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const char* dictionary, int dictSize);\n\n/*\n*_continue() :\n    These decoding functions allow decompression of multiple blocks in \"streaming\" mode.\n    Previously decoded blocks *must* remain available at the memory position where they were decoded (up to 64 KB)\n    If this condition is not possible, save the relevant part of decoded data into a safe buffer,\n    and indicate where is its new address using LZ4_setStreamDecode()\n*/\nint LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int compressedSize, int maxDecompressedSize);\nint LZ4_decompress_fast_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int originalSize);\n\n\n/*\nAdvanced decoding functions :\n*_usingDict() :\n    These decoding functions work the same as\n    a combination of LZ4_setDictDecode() followed by LZ4_decompress_x_continue()\n    They are stand-alone and don't use nor update an LZ4_streamDecode_t structure.\n*/\nint LZ4_decompress_safe_usingDict (const char* source, char* dest, int compressedSize, int maxDecompressedSize, const char* dictStart, int dictSize);\nint LZ4_decompress_fast_usingDict (const char* source, char* dest, int originalSize, const char* dictStart, int dictSize);\n\n\n\n/**************************************\n   Obsolete Functions\n**************************************/\n/*\nObsolete decompression functions\nThese function names are deprecated and should no longer be used.\nThey are only provided here for compatibility with older user programs.\n- LZ4_uncompress is the same as LZ4_decompress_fast\n- LZ4_uncompress_unknownOutputSize is the same as LZ4_decompress_safe\nThese function prototypes are now disabled; uncomment them if you really need them.\nIt is highly recommended to stop using these functions and migrate to newer ones */\n/* int LZ4_uncompress (const char* source, char* dest, int outputSize); */\n/* int LZ4_uncompress_unknownOutputSize (const char* source, char* dest, int isize, int maxOutputSize); */\n\n\n/* Obsolete streaming functions; use new streaming interface whenever possible */\nvoid* LZ4_create (const char* inputBuffer);\nint   LZ4_sizeofStreamState(void);\nint   LZ4_resetStreamState(void* state, const char* inputBuffer);\nchar* LZ4_slideInputBuffer (void* state);\n\n/* Obsolete streaming decoding functions */\nint LZ4_decompress_safe_withPrefix64k (const char* source, char* dest, int compressedSize, int maxOutputSize);\nint LZ4_decompress_fast_withPrefix64k (const char* source, char* dest, int originalSize);\n\n\n#if defined (__cplusplus)\n}\n#endif\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/imgui_remote/lz4/lz4frame.c",
    "content": "/*\nLZ4 auto-framing library\nCopyright (C) 2011-2014, Yann Collet.\nBSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n* Redistributions of source code must retain the above copyright\nnotice, this list of conditions and the following disclaimer.\n* Redistributions in binary form must reproduce the above\ncopyright notice, this list of conditions and the following disclaimer\nin the documentation and/or other materials provided with the\ndistribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(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\nYou can contact the author at :\n- LZ4 source repository : http://code.google.com/p/lz4/\n- LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c\n*/\n\n/* LZ4F is a stand-alone API to create LZ4-compressed Frames\n* fully conformant to specification v1.4.1.\n* All related operations, including memory management, are handled by the library.\n* */\n\n\n/**************************************\nCompiler Options\n**************************************/\n#ifdef _MSC_VER    /* Visual Studio */\n#  pragma warning(disable : 4127)        /* disable: C4127: conditional expression is constant */\n#endif\n\n#define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)\n#ifdef __GNUC__\n#  pragma GCC diagnostic ignored \"-Wmissing-braces\"   /* GCC bug 53119 : doesn't accept { 0 } as initializer (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53119) */\n#  pragma GCC diagnostic ignored \"-Wmissing-field-initializers\"   /* GCC bug 53119 : doesn't accept { 0 } as initializer (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53119) */\n#endif\n\n\n/**************************************\nMemory routines\n**************************************/\n#include <stdlib.h>   /* malloc, calloc, free */\n#define ALLOCATOR(s)   calloc(1,s)\n#define FREEMEM        free\n#include <string.h>   /* memset, memcpy, memmove */\n#define MEM_INIT       memset\n\n\n/**************************************\nIncludes\n**************************************/\n#include \"lz4frame_static.h\"\n#include \"lz4.h\"\n#include \"lz4hc.h\"\n#include \"xxhash.h\"\n\n\n/**************************************\nBasic Types\n**************************************/\n#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)   /* C99 */\n# include <stdint.h>\ntypedef  uint8_t BYTE;\ntypedef uint16_t U16;\ntypedef uint32_t U32;\ntypedef  int32_t S32;\ntypedef uint64_t U64;\n#else\ntypedef unsigned char       BYTE;\ntypedef unsigned short      U16;\ntypedef unsigned int        U32;\ntypedef   signed int        S32;\ntypedef unsigned long long  U64;\n#endif\n\n\n/**************************************\nConstants\n**************************************/\n#define KB *(1<<10)\n#define MB *(1<<20)\n#define GB *(1<<30)\n\n#define _1BIT  0x01\n#define _2BITS 0x03\n#define _3BITS 0x07\n#define _4BITS 0x0F\n#define _8BITS 0xFF\n\n#define LZ4F_MAGICNUMBER 0x184D2204U\n#define LZ4F_BLOCKUNCOMPRESSED_FLAG 0x80000000U\n#define LZ4F_MAXHEADERFRAME_SIZE 7\n#define LZ4F_BLOCKSIZEID_DEFAULT max64KB\n\nstatic const U32 minHClevel = 3;\n\n/**************************************\nStructures and local types\n**************************************/\ntypedef struct\n{\n    LZ4F_preferences_t prefs;\n    U32 version;\n    U32 cStage;\n    size_t maxBlockSize;\n    size_t maxBufferSize;\n    BYTE*  tmpBuff;\n    BYTE*  tmpIn;\n    size_t tmpInSize;\n    XXH32_state_t xxh;\n    void* lz4CtxPtr;\n    U32 lz4CtxLevel;     /* 0: unallocated;  1: LZ4_stream_t;  3: LZ4_streamHC_t */\n} LZ4F_cctx_internal_t;\n\ntypedef struct\n{\n    LZ4F_frameInfo_t frameInfo;\n    unsigned version;\n    unsigned dStage;\n    size_t maxBlockSize;\n    size_t maxBufferSize;\n    const BYTE* srcExpect;\n    BYTE*  tmpIn;\n    size_t tmpInSize;\n    size_t tmpInTarget;\n    BYTE*  tmpOutBuffer;\n    BYTE*  dict;\n    size_t dictSize;\n    BYTE*  tmpOut;\n    size_t tmpOutSize;\n    size_t tmpOutStart;\n    XXH32_state_t xxh;\n    BYTE   header[8];\n} LZ4F_dctx_internal_t;\n\n\n/**************************************\nMacros\n**************************************/\n\n\n/**************************************\nError management\n**************************************/\n#define LZ4F_GENERATE_STRING(STRING) #STRING,\nstatic const char* LZ4F_errorStrings[] = { LZ4F_LIST_ERRORS(LZ4F_GENERATE_STRING) };\n\n\nU32 LZ4F_isError(LZ4F_errorCode_t code)\n{\n    return (code > (LZ4F_errorCode_t)(-ERROR_maxCode));\n}\n\nconst char* LZ4F_getErrorName(LZ4F_errorCode_t code)\n{\n    static const char* codeError = \"Unspecified error code\";\n    if (LZ4F_isError(code)) return LZ4F_errorStrings[-(int)(code)];\n    return codeError;\n}\n\n\n/**************************************\nPrivate functions\n**************************************/\nstatic size_t LZ4F_getBlockSize(unsigned blockSizeID)\n{\n    static const size_t blockSizes[4] = { 64 KB, 256 KB, 1 MB, 4 MB };\n\n    if (blockSizeID == 0) blockSizeID = LZ4F_BLOCKSIZEID_DEFAULT;\n    blockSizeID -= 4;\n    if (blockSizeID > 3) return (size_t)-ERROR_maxBlockSize_invalid;\n    return blockSizes[blockSizeID];\n}\n\n\n/* unoptimized version; solves endianess & alignment issues */\nstatic void LZ4F_writeLE32 (BYTE* dstPtr, U32 value32)\n{\n    dstPtr[0] = (BYTE)value32;\n    dstPtr[1] = (BYTE)(value32 >> 8);\n    dstPtr[2] = (BYTE)(value32 >> 16);\n    dstPtr[3] = (BYTE)(value32 >> 24);\n}\n\nstatic U32 LZ4F_readLE32 (const BYTE* srcPtr)\n{\n    U32 value32 = srcPtr[0];\n    value32 += (srcPtr[1]<<8);\n    value32 += (srcPtr[2]<<16);\n    value32 += (srcPtr[3]<<24);\n    return value32;\n}\n\n\nstatic BYTE LZ4F_headerChecksum (const BYTE* header, size_t length)\n{\n    U32 xxh = XXH32(header, (U32)length, 0);\n    return (BYTE)(xxh >> 8);\n}\n\n\n/**************************************\nSimple compression functions\n**************************************/\nsize_t LZ4F_compressFrameBound(size_t srcSize, const LZ4F_preferences_t* preferencesPtr)\n{\n    LZ4F_preferences_t prefs = { 0 };\n    size_t headerSize;\n    size_t streamSize;\n\n    if (preferencesPtr!=NULL) prefs = *preferencesPtr;\n    {\n        blockSizeID_t proposedBSID = max64KB;\n        size_t maxBlockSize = 64 KB;\n        while (prefs.frameInfo.blockSizeID > proposedBSID)\n        {\n            if (srcSize <= maxBlockSize)\n            {\n                prefs.frameInfo.blockSizeID = proposedBSID;\n                break;\n            }\n            proposedBSID++;\n            maxBlockSize <<= 2;\n        }\n    }\n    prefs.autoFlush = 1;\n\n    headerSize = 7;      /* basic header size (no option) including magic number */\n    streamSize = LZ4F_compressBound(srcSize, &prefs);\n\n    return headerSize + streamSize;\n}\n\n\n/* LZ4F_compressFrame()\n* Compress an entire srcBuffer into a valid LZ4 frame, as defined by specification v1.4.1, in a single step.\n* The most important rule is that dstBuffer MUST be large enough (dstMaxSize) to ensure compression completion even in worst case.\n* You can get the minimum value of dstMaxSize by using LZ4F_compressFrameBound()\n* If this condition is not respected, LZ4F_compressFrame() will fail (result is an errorCode)\n* The LZ4F_preferences_t structure is optional : you can provide NULL as argument. All preferences will be set to default.\n* The result of the function is the number of bytes written into dstBuffer.\n* The function outputs an error code if it fails (can be tested using LZ4F_isError())\n*/\nsize_t LZ4F_compressFrame(void* dstBuffer, size_t dstMaxSize, const void* srcBuffer, size_t srcSize, const LZ4F_preferences_t* preferencesPtr)\n{\n    LZ4F_cctx_internal_t cctxI = { 0 };   /* works because no allocation */\n    LZ4F_preferences_t prefs = { 0 };\n    LZ4F_compressOptions_t options = { 0 };\n    LZ4F_errorCode_t errorCode;\n    BYTE* const dstStart = (BYTE*) dstBuffer;\n    BYTE* dstPtr = dstStart;\n    BYTE* const dstEnd = dstStart + dstMaxSize;\n\n\n    cctxI.version = LZ4F_VERSION;\n    cctxI.maxBufferSize = 5 MB;   /* mess with real buffer size to prevent allocation; works because autoflush==1 & stableSrc==1 */\n\n    if (preferencesPtr!=NULL) prefs = *preferencesPtr;\n    {\n        blockSizeID_t proposedBSID = max64KB;\n        size_t maxBlockSize = 64 KB;\n        while (prefs.frameInfo.blockSizeID > proposedBSID)\n        {\n            if (srcSize <= maxBlockSize)\n            {\n                prefs.frameInfo.blockSizeID = proposedBSID;\n                break;\n            }\n            proposedBSID++;\n            maxBlockSize <<= 2;\n        }\n    }\n    prefs.autoFlush = 1;\n    if (srcSize <= LZ4F_getBlockSize(prefs.frameInfo.blockSizeID))\n        prefs.frameInfo.blockMode = blockIndependent;   /* no need for linked blocks */\n\n    options.stableSrc = 1;\n\n    if (dstMaxSize < LZ4F_compressFrameBound(srcSize, &prefs))\n        return (size_t)-ERROR_dstMaxSize_tooSmall;\n\n    errorCode = LZ4F_compressBegin(&cctxI, dstBuffer, dstMaxSize, &prefs);  /* write header */\n    if (LZ4F_isError(errorCode)) return errorCode;\n    dstPtr += errorCode;   /* header size */\n\n    dstMaxSize -= errorCode;\n    errorCode = LZ4F_compressUpdate(&cctxI, dstPtr, dstMaxSize, srcBuffer, srcSize, &options);\n    if (LZ4F_isError(errorCode)) return errorCode;\n    dstPtr += errorCode;\n\n    errorCode = LZ4F_compressEnd(&cctxI, dstPtr, dstEnd-dstPtr, &options);   /* flush last block, and generate suffix */\n    if (LZ4F_isError(errorCode)) return errorCode;\n    dstPtr += errorCode;\n\n    FREEMEM(cctxI.lz4CtxPtr);\n\n    return (dstPtr - dstStart);\n}\n\n\n/***********************************\n* Advanced compression functions\n* *********************************/\n\n/* LZ4F_createCompressionContext() :\n* The first thing to do is to create a compressionContext object, which will be used in all compression operations.\n* This is achieved using LZ4F_createCompressionContext(), which takes as argument a version and an LZ4F_preferences_t structure.\n* The version provided MUST be LZ4F_VERSION. It is intended to track potential version differences between different binaries.\n* The function will provide a pointer to an allocated LZ4F_compressionContext_t object.\n* If the result LZ4F_errorCode_t is not OK_NoError, there was an error during context creation.\n* Object can release its memory using LZ4F_freeCompressionContext();\n*/\nLZ4F_errorCode_t LZ4F_createCompressionContext(LZ4F_compressionContext_t* LZ4F_compressionContextPtr, unsigned version)\n{\n    LZ4F_cctx_internal_t* cctxPtr;\n\n    cctxPtr = (LZ4F_cctx_internal_t*)ALLOCATOR(sizeof(LZ4F_cctx_internal_t));\n    if (cctxPtr==NULL) return (LZ4F_errorCode_t)(-ERROR_allocation_failed);\n\n    cctxPtr->version = version;\n    cctxPtr->cStage = 0;   /* Next stage : write header */\n\n    *LZ4F_compressionContextPtr = (LZ4F_compressionContext_t)cctxPtr;\n\n    return OK_NoError;\n}\n\n\nLZ4F_errorCode_t LZ4F_freeCompressionContext(LZ4F_compressionContext_t LZ4F_compressionContext)\n{\n    LZ4F_cctx_internal_t* cctxPtr = (LZ4F_cctx_internal_t*)LZ4F_compressionContext;\n\n    FREEMEM(cctxPtr->lz4CtxPtr);\n    FREEMEM(cctxPtr->tmpBuff);\n    FREEMEM(LZ4F_compressionContext);\n\n    return OK_NoError;\n}\n\n\n/* LZ4F_compressBegin() :\n* will write the frame header into dstBuffer.\n* dstBuffer must be large enough to accommodate a header (dstMaxSize). Maximum header size is LZ4F_MAXHEADERFRAME_SIZE bytes.\n* The result of the function is the number of bytes written into dstBuffer for the header\n* or an error code (can be tested using LZ4F_isError())\n*/\nsize_t LZ4F_compressBegin(LZ4F_compressionContext_t compressionContext, void* dstBuffer, size_t dstMaxSize, const LZ4F_preferences_t* preferencesPtr)\n{\n    LZ4F_preferences_t prefNull = { 0 };\n    LZ4F_cctx_internal_t* cctxPtr = (LZ4F_cctx_internal_t*)compressionContext;\n    BYTE* const dstStart = (BYTE*)dstBuffer;\n    BYTE* dstPtr = dstStart;\n    BYTE* headerStart;\n    size_t requiredBuffSize;\n\n    if (dstMaxSize < LZ4F_MAXHEADERFRAME_SIZE) return (size_t)-ERROR_dstMaxSize_tooSmall;\n    if (cctxPtr->cStage != 0) return (size_t)-ERROR_GENERIC;\n    if (preferencesPtr == NULL) preferencesPtr = &prefNull;\n    cctxPtr->prefs = *preferencesPtr;\n\n    /* ctx Management */\n    {\n        U32 targetCtxLevel = cctxPtr->prefs.compressionLevel<minHClevel ? 1 : 2;\n        if (cctxPtr->lz4CtxLevel < targetCtxLevel)\n        {\n            FREEMEM(cctxPtr->lz4CtxPtr);\n            if (cctxPtr->prefs.compressionLevel<minHClevel)\n                cctxPtr->lz4CtxPtr = (void*)LZ4_createStream();\n            else\n                cctxPtr->lz4CtxPtr = (void*)LZ4_createStreamHC();\n            cctxPtr->lz4CtxLevel = targetCtxLevel;\n        }\n    }\n\n    /* Buffer Management */\n    if (cctxPtr->prefs.frameInfo.blockSizeID == 0) cctxPtr->prefs.frameInfo.blockSizeID = LZ4F_BLOCKSIZEID_DEFAULT;\n    cctxPtr->maxBlockSize = LZ4F_getBlockSize(cctxPtr->prefs.frameInfo.blockSizeID);\n\n    requiredBuffSize = cctxPtr->maxBlockSize + ((cctxPtr->prefs.frameInfo.blockMode == blockLinked) * 128 KB);\n    if (preferencesPtr->autoFlush)\n        requiredBuffSize = (cctxPtr->prefs.frameInfo.blockMode == blockLinked) * 64 KB;   /* just needs dict */\n\n    if (cctxPtr->maxBufferSize < requiredBuffSize)\n    {\n        cctxPtr->maxBufferSize = requiredBuffSize;\n        FREEMEM(cctxPtr->tmpBuff);\n        cctxPtr->tmpBuff = (BYTE*)ALLOCATOR(requiredBuffSize);\n        if (cctxPtr->tmpBuff == NULL) return (size_t)-ERROR_allocation_failed;\n    }\n    cctxPtr->tmpIn = cctxPtr->tmpBuff;\n    cctxPtr->tmpInSize = 0;\n    XXH32_reset(&(cctxPtr->xxh), 0);\n    if (cctxPtr->prefs.compressionLevel<minHClevel)\n        LZ4_resetStream((LZ4_stream_t*)(cctxPtr->lz4CtxPtr));\n    else\n        LZ4_resetStreamHC((LZ4_streamHC_t*)(cctxPtr->lz4CtxPtr), cctxPtr->prefs.compressionLevel);\n\n    /* Magic Number */\n    LZ4F_writeLE32(dstPtr, LZ4F_MAGICNUMBER);\n    dstPtr += 4;\n    headerStart = dstPtr;\n\n    /* FLG Byte */\n    *dstPtr++ = ((1 & _2BITS) << 6)    /* Version('01') */\n        + ((cctxPtr->prefs.frameInfo.blockMode & _1BIT ) << 5)    /* Block mode */\n        + (char)((cctxPtr->prefs.frameInfo.contentChecksumFlag & _1BIT ) << 2);   /* Stream checksum */\n    /* BD Byte */\n    *dstPtr++ = (char)((cctxPtr->prefs.frameInfo.blockSizeID & _3BITS) << 4);\n    /* CRC Byte */\n    *dstPtr++ = LZ4F_headerChecksum(headerStart, 2);\n\n    cctxPtr->cStage = 1;   /* header written, wait for data block */\n\n    return (dstPtr - dstStart);\n}\n\n\n/* LZ4F_compressBound() : gives the size of Dst buffer given a srcSize to handle worst case situations.\n*                        The LZ4F_frameInfo_t structure is optional :\n*                        you can provide NULL as argument, all preferences will then be set to default.\n* */\nsize_t LZ4F_compressBound(size_t srcSize, const LZ4F_preferences_t* preferencesPtr)\n{\n    const LZ4F_preferences_t prefsNull = { 0 };\n    const LZ4F_preferences_t* prefsPtr = (preferencesPtr==NULL) ? &prefsNull : preferencesPtr;\n    blockSizeID_t bid = prefsPtr->frameInfo.blockSizeID;\n    size_t blockSize = LZ4F_getBlockSize(bid);\n    unsigned nbBlocks = (unsigned)(srcSize / blockSize) + 1;\n    size_t lastBlockSize = prefsPtr->autoFlush ? srcSize % blockSize : blockSize;\n    size_t blockInfo = 4;   /* default, without block CRC option */\n    size_t frameEnd = 4 + (prefsPtr->frameInfo.contentChecksumFlag*4);\n    size_t result = (blockInfo * nbBlocks) + (blockSize * (nbBlocks-1)) + lastBlockSize + frameEnd;\n\n    return result;\n}\n\n\ntypedef int (*compressFunc_t)(void* ctx, const char* src, char* dst, int srcSize, int dstSize, int level);\n\nstatic size_t LZ4F_compressBlock(void* dst, const void* src, size_t srcSize, compressFunc_t compress, void* lz4ctx, int level)\n{\n    /* compress one block */\n    BYTE* cSizePtr = (BYTE*)dst;\n    U32 cSize;\n    cSize = (U32)compress(lz4ctx, (const char*)src, (char*)(cSizePtr+4), (int)(srcSize), (int)(srcSize-1), level);\n    LZ4F_writeLE32(cSizePtr, cSize);\n    if (cSize == 0)   /* compression failed */\n    {\n        cSize = (U32)srcSize;\n        LZ4F_writeLE32(cSizePtr, cSize + LZ4F_BLOCKUNCOMPRESSED_FLAG);\n        memcpy(cSizePtr+4, src, srcSize);\n    }\n    return cSize + 4;\n}\n\n\nstatic int LZ4F_localLZ4_compress_limitedOutput_withState(void* ctx, const char* src, char* dst, int srcSize, int dstSize, int level)\n{\n    (void) level;\n    return LZ4_compress_limitedOutput_withState(ctx, src, dst, srcSize, dstSize);\n}\n\nstatic int LZ4F_localLZ4_compress_limitedOutput_continue(void* ctx, const char* src, char* dst, int srcSize, int dstSize, int level)\n{\n    (void) level;\n    return LZ4_compress_limitedOutput_continue((LZ4_stream_t*)ctx, src, dst, srcSize, dstSize);\n}\n\nstatic int LZ4F_localLZ4_compressHC_limitedOutput_continue(void* ctx, const char* src, char* dst, int srcSize, int dstSize, int level)\n{\n    (void) level;\n    return LZ4_compressHC_limitedOutput_continue((LZ4_streamHC_t*)ctx, src, dst, srcSize, dstSize);\n}\n\nstatic compressFunc_t LZ4F_selectCompression(blockMode_t blockMode, U32 level)\n{\n    if (level < minHClevel)\n    {\n        if (blockMode == blockIndependent) return LZ4F_localLZ4_compress_limitedOutput_withState;\n        return LZ4F_localLZ4_compress_limitedOutput_continue;\n    }\n    if (blockMode == blockIndependent) return LZ4_compressHC2_limitedOutput_withStateHC;\n    return LZ4F_localLZ4_compressHC_limitedOutput_continue;\n}\n\nstatic int LZ4F_localSaveDict(LZ4F_cctx_internal_t* cctxPtr)\n{\n    if (cctxPtr->prefs.compressionLevel < minHClevel)\n        return LZ4_saveDict ((LZ4_stream_t*)(cctxPtr->lz4CtxPtr), (char*)(cctxPtr->tmpBuff), 64 KB);\n    return LZ4_saveDictHC ((LZ4_streamHC_t*)(cctxPtr->lz4CtxPtr), (char*)(cctxPtr->tmpBuff), 64 KB);\n}\n\ntypedef enum { notDone, fromTmpBuffer, fromSrcBuffer } LZ4F_lastBlockStatus;\n\n/* LZ4F_compressUpdate()\n* LZ4F_compressUpdate() can be called repetitively to compress as much data as necessary.\n* The most important rule is that dstBuffer MUST be large enough (dstMaxSize) to ensure compression completion even in worst case.\n* If this condition is not respected, LZ4F_compress() will fail (result is an errorCode)\n* You can get the minimum value of dstMaxSize by using LZ4F_compressBound()\n* The LZ4F_compressOptions_t structure is optional : you can provide NULL as argument.\n* The result of the function is the number of bytes written into dstBuffer : it can be zero, meaning input data was just buffered.\n* The function outputs an error code if it fails (can be tested using LZ4F_isError())\n*/\nsize_t LZ4F_compressUpdate(LZ4F_compressionContext_t compressionContext, void* dstBuffer, size_t dstMaxSize, const void* srcBuffer, size_t srcSize, const LZ4F_compressOptions_t* compressOptionsPtr)\n{\n    LZ4F_compressOptions_t cOptionsNull = { 0 };\n    LZ4F_cctx_internal_t* cctxPtr = (LZ4F_cctx_internal_t*)compressionContext;\n    size_t blockSize = cctxPtr->maxBlockSize;\n    const BYTE* srcPtr = (const BYTE*)srcBuffer;\n    const BYTE* const srcEnd = srcPtr + srcSize;\n    BYTE* const dstStart = (BYTE*)dstBuffer;\n    BYTE* dstPtr = dstStart;\n    LZ4F_lastBlockStatus lastBlockCompressed = notDone;\n    compressFunc_t compress;\n\n\n    if (cctxPtr->cStage != 1) return (size_t)-ERROR_GENERIC;\n    if (dstMaxSize < LZ4F_compressBound(srcSize, &(cctxPtr->prefs))) return (size_t)-ERROR_dstMaxSize_tooSmall;\n    if (compressOptionsPtr == NULL) compressOptionsPtr = &cOptionsNull;\n\n    /* select compression function */\n    compress = LZ4F_selectCompression(cctxPtr->prefs.frameInfo.blockMode, cctxPtr->prefs.compressionLevel);\n\n    /* complete tmp buffer */\n    if (cctxPtr->tmpInSize > 0)   /* some data already within tmp buffer */\n    {\n        size_t sizeToCopy = blockSize - cctxPtr->tmpInSize;\n        if (sizeToCopy > srcSize)\n        {\n            /* add src to tmpIn buffer */\n            memcpy(cctxPtr->tmpIn + cctxPtr->tmpInSize, srcBuffer, srcSize);\n            srcPtr = srcEnd;\n            cctxPtr->tmpInSize += srcSize;\n            /* still needs some CRC */\n        }\n        else\n        {\n            /* complete tmpIn block and then compress it */\n            lastBlockCompressed = fromTmpBuffer;\n            memcpy(cctxPtr->tmpIn + cctxPtr->tmpInSize, srcBuffer, sizeToCopy);\n            srcPtr += sizeToCopy;\n\n            dstPtr += LZ4F_compressBlock(dstPtr, cctxPtr->tmpIn, blockSize, compress, cctxPtr->lz4CtxPtr, cctxPtr->prefs.compressionLevel);\n\n            if (cctxPtr->prefs.frameInfo.blockMode==blockLinked) cctxPtr->tmpIn += blockSize;\n            cctxPtr->tmpInSize = 0;\n        }\n    }\n\n    while ((size_t)(srcEnd - srcPtr) >= blockSize)\n    {\n        /* compress full block */\n        lastBlockCompressed = fromSrcBuffer;\n        dstPtr += LZ4F_compressBlock(dstPtr, srcPtr, blockSize, compress, cctxPtr->lz4CtxPtr, cctxPtr->prefs.compressionLevel);\n        srcPtr += blockSize;\n    }\n\n    if ((cctxPtr->prefs.autoFlush) && (srcPtr < srcEnd))\n    {\n        /* compress remaining input < blockSize */\n        lastBlockCompressed = fromSrcBuffer;\n        dstPtr += LZ4F_compressBlock(dstPtr, srcPtr, srcEnd - srcPtr, compress, cctxPtr->lz4CtxPtr, cctxPtr->prefs.compressionLevel);\n        srcPtr  = srcEnd;\n    }\n\n    /* preserve dictionary if necessary */\n    if ((cctxPtr->prefs.frameInfo.blockMode==blockLinked) && (lastBlockCompressed==fromSrcBuffer))\n    {\n        if (compressOptionsPtr->stableSrc)\n        {\n            cctxPtr->tmpIn = cctxPtr->tmpBuff;\n        }\n        else\n        {\n            int realDictSize = LZ4F_localSaveDict(cctxPtr);\n            if (realDictSize==0) return (size_t)-ERROR_GENERIC;\n            cctxPtr->tmpIn = cctxPtr->tmpBuff + realDictSize;\n        }\n    }\n\n    /* keep tmpIn within limits */\n    if ((cctxPtr->tmpIn + blockSize) > (cctxPtr->tmpBuff + cctxPtr->maxBufferSize)   /* necessarily blockLinked && lastBlockCompressed==fromTmpBuffer */\n        && !(cctxPtr->prefs.autoFlush))\n    {\n        LZ4F_localSaveDict(cctxPtr);\n        cctxPtr->tmpIn = cctxPtr->tmpBuff + 64 KB;\n    }\n\n    /* some input data left, necessarily < blockSize */\n    if (srcPtr < srcEnd)\n    {\n        /* fill tmp buffer */\n        size_t sizeToCopy = srcEnd - srcPtr;\n        memcpy(cctxPtr->tmpIn, srcPtr, sizeToCopy);\n        cctxPtr->tmpInSize = sizeToCopy;\n    }\n\n    if (cctxPtr->prefs.frameInfo.contentChecksumFlag == contentChecksumEnabled)\n        XXH32_update(&(cctxPtr->xxh), srcBuffer, (unsigned)srcSize);\n\n    return dstPtr - dstStart;\n}\n\n\n/* LZ4F_flush()\n* Should you need to create compressed data immediately, without waiting for a block to be filled,\n* you can call LZ4_flush(), which will immediately compress any remaining data stored within compressionContext.\n* The result of the function is the number of bytes written into dstBuffer\n* (it can be zero, this means there was no data left within compressionContext)\n* The function outputs an error code if it fails (can be tested using LZ4F_isError())\n* The LZ4F_compressOptions_t structure is optional : you can provide NULL as argument.\n*/\nsize_t LZ4F_flush(LZ4F_compressionContext_t compressionContext, void* dstBuffer, size_t dstMaxSize, const LZ4F_compressOptions_t* compressOptionsPtr)\n{\n    LZ4F_compressOptions_t cOptionsNull = { 0 };\n    LZ4F_cctx_internal_t* cctxPtr = (LZ4F_cctx_internal_t*)compressionContext;\n    BYTE* const dstStart = (BYTE*)dstBuffer;\n    BYTE* dstPtr = dstStart;\n    compressFunc_t compress;\n\n\n    if (cctxPtr->tmpInSize == 0) return 0;   /* nothing to flush */\n    if (cctxPtr->cStage != 1) return (size_t)-ERROR_GENERIC;\n    if (dstMaxSize < (cctxPtr->tmpInSize + 16)) return (size_t)-ERROR_dstMaxSize_tooSmall;\n    if (compressOptionsPtr == NULL) compressOptionsPtr = &cOptionsNull;\n    (void)compressOptionsPtr;   /* not yet useful */\n\n    /* select compression function */\n    compress = LZ4F_selectCompression(cctxPtr->prefs.frameInfo.blockMode, cctxPtr->prefs.compressionLevel);\n\n    /* compress tmp buffer */\n    dstPtr += LZ4F_compressBlock(dstPtr, cctxPtr->tmpIn, cctxPtr->tmpInSize, compress, cctxPtr->lz4CtxPtr, cctxPtr->prefs.compressionLevel);\n    if (cctxPtr->prefs.frameInfo.blockMode==blockLinked) cctxPtr->tmpIn += cctxPtr->tmpInSize;\n    cctxPtr->tmpInSize = 0;\n\n    /* keep tmpIn within limits */\n    if ((cctxPtr->tmpIn + cctxPtr->maxBlockSize) > (cctxPtr->tmpBuff + cctxPtr->maxBufferSize))   /* necessarily blockLinked */\n    {\n        LZ4F_localSaveDict(cctxPtr);\n        cctxPtr->tmpIn = cctxPtr->tmpBuff + 64 KB;\n    }\n\n    return dstPtr - dstStart;\n}\n\n\n/* LZ4F_compressEnd()\n* When you want to properly finish the compressed frame, just call LZ4F_compressEnd().\n* It will flush whatever data remained within compressionContext (like LZ4_flush())\n* but also properly finalize the frame, with an endMark and a checksum.\n* The result of the function is the number of bytes written into dstBuffer (necessarily >= 4 (endMark size))\n* The function outputs an error code if it fails (can be tested using LZ4F_isError())\n* The LZ4F_compressOptions_t structure is optional : you can provide NULL as argument.\n* compressionContext can then be used again, starting with LZ4F_compressBegin(). The preferences will remain the same.\n*/\nsize_t LZ4F_compressEnd(LZ4F_compressionContext_t compressionContext, void* dstBuffer, size_t dstMaxSize, const LZ4F_compressOptions_t* compressOptionsPtr)\n{\n    LZ4F_cctx_internal_t* cctxPtr = (LZ4F_cctx_internal_t*)compressionContext;\n    BYTE* const dstStart = (BYTE*)dstBuffer;\n    BYTE* dstPtr = dstStart;\n    size_t errorCode;\n\n    errorCode = LZ4F_flush(compressionContext, dstBuffer, dstMaxSize, compressOptionsPtr);\n    if (LZ4F_isError(errorCode)) return errorCode;\n    dstPtr += errorCode;\n\n    LZ4F_writeLE32(dstPtr, 0);\n    dstPtr+=4;   /* endMark */\n\n    if (cctxPtr->prefs.frameInfo.contentChecksumFlag == contentChecksumEnabled)\n    {\n        U32 xxh = XXH32_digest(&(cctxPtr->xxh));\n        LZ4F_writeLE32(dstPtr, xxh);\n        dstPtr+=4;   /* content Checksum */\n    }\n\n    cctxPtr->cStage = 0;   /* state is now re-usable (with identical preferences) */\n\n    return dstPtr - dstStart;\n}\n\n\n/***********************************\n* Decompression functions\n* *********************************/\n\n/* Resource management */\n\n/* LZ4F_createDecompressionContext() :\n* The first thing to do is to create a decompressionContext object, which will be used in all decompression operations.\n* This is achieved using LZ4F_createDecompressionContext().\n* The function will provide a pointer to a fully allocated and initialized LZ4F_decompressionContext object.\n* If the result LZ4F_errorCode_t is not zero, there was an error during context creation.\n* Object can release its memory using LZ4F_freeDecompressionContext();\n*/\nLZ4F_errorCode_t LZ4F_createDecompressionContext(LZ4F_compressionContext_t* LZ4F_decompressionContextPtr, unsigned versionNumber)\n{\n    LZ4F_dctx_internal_t* dctxPtr;\n\n    dctxPtr = ALLOCATOR(sizeof(LZ4F_dctx_internal_t));\n    if (dctxPtr==NULL) return (LZ4F_errorCode_t)-ERROR_GENERIC;\n\n    dctxPtr->version = versionNumber;\n    *LZ4F_decompressionContextPtr = (LZ4F_compressionContext_t)dctxPtr;\n    return OK_NoError;\n}\n\nLZ4F_errorCode_t LZ4F_freeDecompressionContext(LZ4F_compressionContext_t LZ4F_decompressionContext)\n{\n    LZ4F_dctx_internal_t* dctxPtr = (LZ4F_dctx_internal_t*)LZ4F_decompressionContext;\n    FREEMEM(dctxPtr->tmpIn);\n    FREEMEM(dctxPtr->tmpOutBuffer);\n    FREEMEM(dctxPtr);\n    return OK_NoError;\n}\n\n\n/* Decompression */\n\nstatic size_t LZ4F_decodeHeader(LZ4F_dctx_internal_t* dctxPtr, const BYTE* srcPtr, size_t srcSize)\n{\n    BYTE FLG, BD, HC;\n    unsigned version, blockMode, blockChecksumFlag, contentSizeFlag, contentChecksumFlag, dictFlag, blockSizeID;\n    size_t bufferNeeded;\n\n    /* need to decode header to get frameInfo */\n    if (srcSize < 7) return (size_t)-ERROR_GENERIC;   /* minimal header size */\n\n    /* control magic number */\n    if (LZ4F_readLE32(srcPtr) != LZ4F_MAGICNUMBER) return (size_t)-ERROR_GENERIC;\n    srcPtr += 4;\n\n    /* Flags */\n    FLG = srcPtr[0];\n    version = (FLG>>6)&_2BITS;\n    blockMode = (FLG>>5) & _1BIT;\n    blockChecksumFlag = (FLG>>4) & _1BIT;\n    contentSizeFlag = (FLG>>3) & _1BIT;\n    contentChecksumFlag = (FLG>>2) & _1BIT;\n    dictFlag = (FLG>>0) & _1BIT;\n    BD = srcPtr[1];\n    blockSizeID = (BD>>4) & _3BITS;\n\n    /* check */\n    HC = LZ4F_headerChecksum(srcPtr, 2);\n    if (HC != srcPtr[2]) return (size_t)-ERROR_GENERIC;   /* Bad header checksum error */\n\n    /* validate */\n    if (version != 1) return (size_t)-ERROR_GENERIC;   /* Version Number, only supported value */\n    if (blockChecksumFlag != 0) return (size_t)-ERROR_GENERIC;   /* Only supported value for the time being */\n    if (contentSizeFlag != 0) return (size_t)-ERROR_GENERIC;   /* Only supported value for the time being */\n    if (((FLG>>1)&_1BIT) != 0) return (size_t)-ERROR_GENERIC;   /* Reserved bit */\n    if (dictFlag != 0) return (size_t)-ERROR_GENERIC;   /* Only supported value for the time being */\n    if (((BD>>7)&_1BIT) != 0) return (size_t)-ERROR_GENERIC;   /* Reserved bit */\n    if (blockSizeID < 4) return (size_t)-ERROR_GENERIC;   /* Only supported values for the time being */\n    if (((BD>>0)&_4BITS) != 0) return (size_t)-ERROR_GENERIC;   /* Reserved bits */\n\n    /* save */\n    dctxPtr->frameInfo.blockMode = blockMode;\n    dctxPtr->frameInfo.contentChecksumFlag = contentChecksumFlag;\n    dctxPtr->frameInfo.blockSizeID = blockSizeID;\n    dctxPtr->maxBlockSize = LZ4F_getBlockSize(blockSizeID);\n\n    /* init */\n    if (contentChecksumFlag) XXH32_reset(&(dctxPtr->xxh), 0);\n\n    /* alloc */\n    bufferNeeded = dctxPtr->maxBlockSize + ((dctxPtr->frameInfo.blockMode==blockLinked) * 128 KB);\n    if (bufferNeeded > dctxPtr->maxBufferSize)   /* tmp buffers too small */\n    {\n        FREEMEM(dctxPtr->tmpIn);\n        FREEMEM(dctxPtr->tmpOutBuffer);\n        dctxPtr->maxBufferSize = bufferNeeded;\n        dctxPtr->tmpIn = ALLOCATOR(dctxPtr->maxBlockSize);\n        if (dctxPtr->tmpIn == NULL) return (size_t)-ERROR_GENERIC;\n        dctxPtr->tmpOutBuffer= ALLOCATOR(dctxPtr->maxBufferSize);\n        if (dctxPtr->tmpOutBuffer== NULL) return (size_t)-ERROR_GENERIC;\n    }\n    dctxPtr->tmpInSize = 0;\n    dctxPtr->tmpInTarget = 0;\n    dctxPtr->dict = dctxPtr->tmpOutBuffer;\n    dctxPtr->dictSize = 0;\n    dctxPtr->tmpOut = dctxPtr->tmpOutBuffer;\n    dctxPtr->tmpOutStart = 0;\n    dctxPtr->tmpOutSize = 0;\n\n    return 7;\n}\n\n\ntypedef enum { dstage_getHeader=0, dstage_storeHeader, dstage_decodeHeader,\n    dstage_getCBlockSize, dstage_storeCBlockSize, dstage_decodeCBlockSize,\n    dstage_copyDirect,\n    dstage_getCBlock, dstage_storeCBlock, dstage_decodeCBlock,\n    dstage_decodeCBlock_intoDst, dstage_decodeCBlock_intoTmp, dstage_flushOut,\n    dstage_getSuffix, dstage_storeSuffix, dstage_checkSuffix\n} dStage_t;\n\n\n/* LZ4F_getFrameInfo()\n* This function decodes frame header information, such as blockSize.\n* It is optional : you could start by calling directly LZ4F_decompress() instead.\n* The objective is to extract header information without starting decompression, typically for allocation purposes.\n* LZ4F_getFrameInfo() can also be used *after* starting decompression, on a valid LZ4F_decompressionContext_t.\n* The number of bytes read from srcBuffer will be provided within *srcSizePtr (necessarily <= original value).\n* You are expected to resume decompression from where it stopped (srcBuffer + *srcSizePtr)\n* The function result is an hint of the better srcSize to use for next call to LZ4F_decompress,\n* or an error code which can be tested using LZ4F_isError().\n*/\nLZ4F_errorCode_t LZ4F_getFrameInfo(LZ4F_decompressionContext_t decompressionContext, LZ4F_frameInfo_t* frameInfoPtr, const void* srcBuffer, size_t* srcSizePtr)\n{\n    LZ4F_dctx_internal_t* dctxPtr = (LZ4F_dctx_internal_t*)decompressionContext;\n\n    if (dctxPtr->dStage == dstage_getHeader)\n    {\n        LZ4F_errorCode_t errorCode = LZ4F_decodeHeader(dctxPtr, srcBuffer, *srcSizePtr);\n        if (LZ4F_isError(errorCode)) return errorCode;\n        *srcSizePtr = errorCode;\n        *frameInfoPtr = dctxPtr->frameInfo;\n        dctxPtr->srcExpect = NULL;\n        dctxPtr->dStage = dstage_getCBlockSize;\n        return 4;\n    }\n\n    /* frameInfo already decoded */\n    *srcSizePtr = 0;\n    *frameInfoPtr = dctxPtr->frameInfo;\n    return 0;\n}\n\n\nstatic int LZ4F_decompress_safe (const char* source, char* dest, int compressedSize, int maxDecompressedSize, const char* dictStart, int dictSize)\n{\n    (void)dictStart;\n    (void)dictSize;\n    return LZ4_decompress_safe (source, dest, compressedSize, maxDecompressedSize);\n}\n\n\n\nstatic void LZ4F_updateDict(LZ4F_dctx_internal_t* dctxPtr, const BYTE* dstPtr, size_t dstSize, const BYTE* dstPtr0, unsigned withinTmp)\n{\n    if (dctxPtr->dictSize==0)\n        dctxPtr->dict = (BYTE*)dstPtr;   /* priority to dictionary continuity */\n\n    if (dctxPtr->dict + dctxPtr->dictSize == dstPtr)   /* dictionary continuity */\n    {\n        dctxPtr->dictSize += dstSize;\n        return;\n    }\n\n    if (dstPtr - dstPtr0 + dstSize >= 64 KB)   /* dstBuffer large enough to become dictionary */\n    {\n        dctxPtr->dict = (BYTE*)dstPtr0;\n        dctxPtr->dictSize = dstPtr - dstPtr0 + dstSize;\n        return;\n    }\n\n    if ((withinTmp) && (dctxPtr->dict == dctxPtr->tmpOutBuffer))\n    {\n        /* assumption : dctxPtr->dict + dctxPtr->dictSize == dctxPtr->tmpOut + dctxPtr->tmpOutStart */\n        dctxPtr->dictSize += dstSize;\n        return;\n    }\n\n    if (withinTmp) /* copy relevant dict portion in front of tmpOut within tmpOutBuffer */\n    {\n#if 0\n        size_t savedDictSize = dctxPtr->tmpOut - dctxPtr->tmpOutBuffer;\n        memcpy(dctxPtr->tmpOutBuffer, dctxPtr->dict + dctxPtr->dictSize - dctxPtr->tmpOutStart- savedDictSize, savedDictSize);\n        dctxPtr->dict = dctxPtr->tmpOutBuffer;\n        dctxPtr->dictSize = savedDictSize + dctxPtr->tmpOutStart + dstSize;\n        return;\n\n#else\n\n        size_t preserveSize = dctxPtr->tmpOut - dctxPtr->tmpOutBuffer;\n        size_t copySize = 64 KB - dctxPtr->tmpOutSize;\n        BYTE* oldDictEnd = dctxPtr->dict + dctxPtr->dictSize - dctxPtr->tmpOutStart;\n        if (dctxPtr->tmpOutSize > 64 KB) copySize = 0;\n        if (copySize > preserveSize) copySize = preserveSize;\n\n        memcpy(dctxPtr->tmpOutBuffer + preserveSize - copySize, oldDictEnd - copySize, copySize);\n\n        dctxPtr->dict = dctxPtr->tmpOutBuffer;\n        dctxPtr->dictSize = preserveSize + dctxPtr->tmpOutStart + dstSize;\n        return;\n#endif\n    }\n\n    if (dctxPtr->dict == dctxPtr->tmpOutBuffer)     /* copy dst into tmp to complete dict */\n    {\n        if (dctxPtr->dictSize + dstSize > dctxPtr->maxBufferSize)   /* tmp buffer not large enough */\n        {\n            size_t preserveSize = 64 KB - dstSize;   /* note : dstSize < 64 KB */\n            memcpy(dctxPtr->dict, dctxPtr->dict + dctxPtr->dictSize - preserveSize, preserveSize);\n            dctxPtr->dictSize = preserveSize;\n        }\n        memcpy(dctxPtr->dict + dctxPtr->dictSize, dstPtr, dstSize);\n        dctxPtr->dictSize += dstSize;\n        return;\n    }\n\n    /* join dict & dest into tmp */\n    {\n        size_t preserveSize = 64 KB - dstSize;   /* note : dstSize < 64 KB */\n        if (preserveSize > dctxPtr->dictSize) preserveSize = dctxPtr->dictSize;\n        memcpy(dctxPtr->tmpOutBuffer, dctxPtr->dict + dctxPtr->dictSize - preserveSize, preserveSize);\n        memcpy(dctxPtr->tmpOutBuffer + preserveSize, dstPtr, dstSize);\n        dctxPtr->dict = dctxPtr->tmpOutBuffer;\n        dctxPtr->dictSize = preserveSize + dstSize;\n    }\n}\n\n\n\n/* LZ4F_decompress()\n* Call this function repetitively to regenerate data compressed within srcBuffer.\n* The function will attempt to decode *srcSizePtr from srcBuffer, into dstBuffer of maximum size *dstSizePtr.\n*\n* The number of bytes regenerated into dstBuffer will be provided within *dstSizePtr (necessarily <= original value).\n*\n* The number of bytes effectively read from srcBuffer will be provided within *srcSizePtr (necessarily <= original value).\n* If the number of bytes read is < number of bytes provided, then the decompression operation is not complete.\n* You will have to call it again, continuing from where it stopped.\n*\n* The function result is an hint of the better srcSize to use for next call to LZ4F_decompress.\n* Basically, it's the size of the current (or remaining) compressed block + header of next block.\n* Respecting the hint provides some boost to performance, since it allows less buffer shuffling.\n* Note that this is just a hint, you can always provide any srcSize you want.\n* When a frame is fully decoded, the function result will be 0.\n* If decompression failed, function result is an error code which can be tested using LZ4F_isError().\n*/\nsize_t LZ4F_decompress(LZ4F_decompressionContext_t decompressionContext,\n                       void* dstBuffer, size_t* dstSizePtr,\n                       const void* srcBuffer, size_t* srcSizePtr,\n                       const LZ4F_decompressOptions_t* decompressOptionsPtr)\n{\n    LZ4F_dctx_internal_t* dctxPtr = (LZ4F_dctx_internal_t*)decompressionContext;\n    static const LZ4F_decompressOptions_t optionsNull = { 0 };\n    const BYTE* const srcStart = (const BYTE*)srcBuffer;\n    const BYTE* const srcEnd = srcStart + *srcSizePtr;\n    const BYTE* srcPtr = srcStart;\n    BYTE* const dstStart = (BYTE*)dstBuffer;\n    BYTE* const dstEnd = dstStart + *dstSizePtr;\n    BYTE* dstPtr = dstStart;\n    const BYTE* selectedIn=NULL;\n    unsigned doAnotherStage = 1;\n    size_t nextSrcSizeHint = 1;\n\n\n    if (decompressOptionsPtr==NULL) decompressOptionsPtr = &optionsNull;\n    *srcSizePtr = 0;\n    *dstSizePtr = 0;\n\n    /* expect to continue decoding src buffer where it left previously */\n    if (dctxPtr->srcExpect != NULL)\n    {\n        if (srcStart != dctxPtr->srcExpect) return (size_t)-ERROR_GENERIC;\n    }\n\n    /* programmed as a state machine */\n\n    while (doAnotherStage)\n    {\n\n        switch(dctxPtr->dStage)\n        {\n\n        case dstage_getHeader:\n            {\n                if (srcEnd-srcPtr >= 7)\n                {\n                    selectedIn = srcPtr;\n                    srcPtr += 7;\n                    dctxPtr->dStage = dstage_decodeHeader;\n                    break;\n                }\n                dctxPtr->tmpInSize = 0;\n                dctxPtr->dStage = dstage_storeHeader;\n                break;\n            }\n\n        case dstage_storeHeader:\n            {\n                size_t sizeToCopy = 7 - dctxPtr->tmpInSize;\n                if (sizeToCopy > (size_t)(srcEnd - srcPtr)) sizeToCopy =  srcEnd - srcPtr;\n                memcpy(dctxPtr->header + dctxPtr->tmpInSize, srcPtr, sizeToCopy);\n                dctxPtr->tmpInSize += sizeToCopy;\n                srcPtr += sizeToCopy;\n                if (dctxPtr->tmpInSize < 7)\n                {\n                    nextSrcSizeHint = (7 - dctxPtr->tmpInSize) + 4;\n                    doAnotherStage = 0;   /* no enough src, wait to get some more */\n                    break;\n                }\n                selectedIn = dctxPtr->header;\n                dctxPtr->dStage = dstage_decodeHeader;\n                break;\n            }\n\n        case dstage_decodeHeader:\n            {\n                LZ4F_errorCode_t errorCode = LZ4F_decodeHeader(dctxPtr, selectedIn, 7);\n                if (LZ4F_isError(errorCode)) return errorCode;\n                dctxPtr->dStage = dstage_getCBlockSize;\n                break;\n            }\n\n        case dstage_getCBlockSize:\n            {\n                if ((srcEnd - srcPtr) >= 4)\n                {\n                    selectedIn = srcPtr;\n                    srcPtr += 4;\n                    dctxPtr->dStage = dstage_decodeCBlockSize;\n                    break;\n                }\n                /* not enough input to read cBlockSize field */\n                dctxPtr->tmpInSize = 0;\n                dctxPtr->dStage = dstage_storeCBlockSize;\n                break;\n            }\n\n        case dstage_storeCBlockSize:\n            {\n                size_t sizeToCopy = 4 - dctxPtr->tmpInSize;\n                if (sizeToCopy > (size_t)(srcEnd - srcPtr)) sizeToCopy = srcEnd - srcPtr;\n                memcpy(dctxPtr->tmpIn + dctxPtr->tmpInSize, srcPtr, sizeToCopy);\n                srcPtr += sizeToCopy;\n                dctxPtr->tmpInSize += sizeToCopy;\n                if (dctxPtr->tmpInSize < 4) /* not enough input to get full cBlockSize; wait for more */\n                {\n                    nextSrcSizeHint = 4 - dctxPtr->tmpInSize;\n                    doAnotherStage=0;\n                    break;\n                }\n                selectedIn = dctxPtr->tmpIn;\n                dctxPtr->dStage = dstage_decodeCBlockSize;\n                break;\n            }\n\n        case dstage_decodeCBlockSize:\n            {\n                size_t nextCBlockSize = LZ4F_readLE32(selectedIn) & 0x7FFFFFFFU;\n                if (nextCBlockSize==0)   /* frameEnd signal, no more CBlock */\n                {\n                    dctxPtr->dStage = dstage_getSuffix;\n                    break;\n                }\n                if (nextCBlockSize > dctxPtr->maxBlockSize) return (size_t)-ERROR_GENERIC;   /* invalid cBlockSize */\n                dctxPtr->tmpInTarget = nextCBlockSize;\n                if (LZ4F_readLE32(selectedIn) & LZ4F_BLOCKUNCOMPRESSED_FLAG)\n                {\n                    dctxPtr->dStage = dstage_copyDirect;\n                    break;\n                }\n                dctxPtr->dStage = dstage_getCBlock;\n                if (dstPtr==dstEnd)\n                {\n                    nextSrcSizeHint = nextCBlockSize + 4;\n                    doAnotherStage = 0;\n                }\n                break;\n            }\n\n        case dstage_copyDirect:   /* uncompressed block */\n            {\n                size_t sizeToCopy = dctxPtr->tmpInTarget;\n                if ((size_t)(srcEnd-srcPtr) < sizeToCopy) sizeToCopy = srcEnd - srcPtr;  /* not enough input to read full block */\n                if ((size_t)(dstEnd-dstPtr) < sizeToCopy) sizeToCopy = dstEnd - dstPtr;\n                memcpy(dstPtr, srcPtr, sizeToCopy);\n                if (dctxPtr->frameInfo.contentChecksumFlag) XXH32_update(&(dctxPtr->xxh), srcPtr, (U32)sizeToCopy);\n\n                /* dictionary management */\n                if (dctxPtr->frameInfo.blockMode==blockLinked)\n                    LZ4F_updateDict(dctxPtr, dstPtr, sizeToCopy, dstStart, 0);\n\n                srcPtr += sizeToCopy;\n                dstPtr += sizeToCopy;\n                if (sizeToCopy == dctxPtr->tmpInTarget)   /* all copied */\n                {\n                    dctxPtr->dStage = dstage_getCBlockSize;\n                    break;\n                }\n                dctxPtr->tmpInTarget -= sizeToCopy;   /* still need to copy more */\n                nextSrcSizeHint = dctxPtr->tmpInTarget + 4;\n                doAnotherStage = 0;\n                break;\n            }\n\n        case dstage_getCBlock:   /* entry from dstage_decodeCBlockSize */\n            {\n                if ((size_t)(srcEnd-srcPtr) < dctxPtr->tmpInTarget)\n                {\n                    dctxPtr->tmpInSize = 0;\n                    dctxPtr->dStage = dstage_storeCBlock;\n                    break;\n                }\n                selectedIn = srcPtr;\n                srcPtr += dctxPtr->tmpInTarget;\n                dctxPtr->dStage = dstage_decodeCBlock;\n                break;\n            }\n\n        case dstage_storeCBlock:\n            {\n                size_t sizeToCopy = dctxPtr->tmpInTarget - dctxPtr->tmpInSize;\n                if (sizeToCopy > (size_t)(srcEnd-srcPtr)) sizeToCopy = srcEnd-srcPtr;\n                memcpy(dctxPtr->tmpIn + dctxPtr->tmpInSize, srcPtr, sizeToCopy);\n                dctxPtr->tmpInSize += sizeToCopy;\n                srcPtr += sizeToCopy;\n                if (dctxPtr->tmpInSize < dctxPtr->tmpInTarget)  /* need more input */\n                {\n                    nextSrcSizeHint = (dctxPtr->tmpInTarget - dctxPtr->tmpInSize) + 4;\n                    doAnotherStage=0;\n                    break;\n                }\n                selectedIn = dctxPtr->tmpIn;\n                dctxPtr->dStage = dstage_decodeCBlock;\n                break;\n            }\n\n        case dstage_decodeCBlock:\n            {\n                if ((size_t)(dstEnd-dstPtr) < dctxPtr->maxBlockSize)   /* not enough place into dst : decode into tmpOut */\n                    dctxPtr->dStage = dstage_decodeCBlock_intoTmp;\n                else\n                    dctxPtr->dStage = dstage_decodeCBlock_intoDst;\n                break;\n            }\n\n        case dstage_decodeCBlock_intoDst:\n            {\n                int (*decoder)(const char*, char*, int, int, const char*, int);\n                int decodedSize;\n\n                if (dctxPtr->frameInfo.blockMode == blockLinked)\n                    decoder = LZ4_decompress_safe_usingDict;\n                else\n                    decoder = LZ4F_decompress_safe;\n\n                decodedSize = decoder((const char*)selectedIn, (char*)dstPtr, (int)dctxPtr->tmpInTarget, (int)dctxPtr->maxBlockSize, (const char*)dctxPtr->dict, (int)dctxPtr->dictSize);\n                if (decodedSize < 0) return (size_t)-ERROR_GENERIC;   /* decompression failed */\n                if (dctxPtr->frameInfo.contentChecksumFlag) XXH32_update(&(dctxPtr->xxh), dstPtr, decodedSize);\n\n                /* dictionary management */\n                if (dctxPtr->frameInfo.blockMode==blockLinked)\n                    LZ4F_updateDict(dctxPtr, dstPtr, decodedSize, dstStart, 0);\n\n                dstPtr += decodedSize;\n                dctxPtr->dStage = dstage_getCBlockSize;\n                break;\n            }\n\n        case dstage_decodeCBlock_intoTmp:\n            {\n                /* not enough place into dst : decode into tmpOut */\n                int (*decoder)(const char*, char*, int, int, const char*, int);\n                int decodedSize;\n\n                if (dctxPtr->frameInfo.blockMode == blockLinked)\n                    decoder = LZ4_decompress_safe_usingDict;\n                else\n                    decoder = LZ4F_decompress_safe;\n\n                /* ensure enough place for tmpOut */\n                if (dctxPtr->frameInfo.blockMode == blockLinked)\n                {\n                    if (dctxPtr->dict == dctxPtr->tmpOutBuffer)\n                    {\n                        if (dctxPtr->dictSize > 128 KB)\n                        {\n                            memcpy(dctxPtr->dict, dctxPtr->dict + dctxPtr->dictSize - 64 KB, 64 KB);\n                            dctxPtr->dictSize = 64 KB;\n                        }\n                        dctxPtr->tmpOut = dctxPtr->dict + dctxPtr->dictSize;\n                    }\n                    else   /* dict not within tmp */\n                    {\n                        size_t reservedDictSpace = dctxPtr->dictSize;\n                        if (reservedDictSpace > 64 KB) reservedDictSpace = 64 KB;\n                        dctxPtr->tmpOut = dctxPtr->tmpOutBuffer + reservedDictSpace;\n                    }\n                }\n\n                /* Decode */\n                decodedSize = decoder((const char*)selectedIn, (char*)dctxPtr->tmpOut, (int)dctxPtr->tmpInTarget, (int)dctxPtr->maxBlockSize, (const char*)dctxPtr->dict, (int)dctxPtr->dictSize);\n                if (decodedSize < 0) return (size_t)-ERROR_decompressionFailed;   /* decompression failed */\n                if (dctxPtr->frameInfo.contentChecksumFlag) XXH32_update(&(dctxPtr->xxh), dctxPtr->tmpOut, decodedSize);\n                dctxPtr->tmpOutSize = decodedSize;\n                dctxPtr->tmpOutStart = 0;\n                dctxPtr->dStage = dstage_flushOut;\n                break;\n            }\n\n        case dstage_flushOut:  /* flush decoded data from tmpOut to dstBuffer */\n            {\n                size_t sizeToCopy = dctxPtr->tmpOutSize - dctxPtr->tmpOutStart;\n                if (sizeToCopy > (size_t)(dstEnd-dstPtr)) sizeToCopy = dstEnd-dstPtr;\n                memcpy(dstPtr, dctxPtr->tmpOut + dctxPtr->tmpOutStart, sizeToCopy);\n\n                /* dictionary management */\n                if (dctxPtr->frameInfo.blockMode==blockLinked)\n                    LZ4F_updateDict(dctxPtr, dstPtr, sizeToCopy, dstStart, 1);\n\n                dctxPtr->tmpOutStart += sizeToCopy;\n                dstPtr += sizeToCopy;\n\n                /* end of flush ? */\n                if (dctxPtr->tmpOutStart == dctxPtr->tmpOutSize)\n                {\n                    dctxPtr->dStage = dstage_getCBlockSize;\n                    break;\n                }\n                nextSrcSizeHint = 4;\n                doAnotherStage = 0;   /* still some data to flush */\n                break;\n            }\n\n        case dstage_getSuffix:\n            {\n                size_t suffixSize = dctxPtr->frameInfo.contentChecksumFlag * 4;\n                if (suffixSize == 0)   /* frame completed */\n                {\n                    nextSrcSizeHint = 0;\n                    dctxPtr->dStage = dstage_getHeader;\n                    doAnotherStage = 0;\n                    break;\n                }\n                if ((srcEnd - srcPtr) >= 4)   /* CRC present */\n                {\n                    selectedIn = srcPtr;\n                    srcPtr += 4;\n                    dctxPtr->dStage = dstage_checkSuffix;\n                    break;\n                }\n                dctxPtr->tmpInSize = 0;\n                dctxPtr->dStage = dstage_storeSuffix;\n                break;\n            }\n\n        case dstage_storeSuffix:\n            {\n                size_t sizeToCopy = 4 - dctxPtr->tmpInSize;\n                if (sizeToCopy > (size_t)(srcEnd - srcPtr)) sizeToCopy = srcEnd - srcPtr;\n                memcpy(dctxPtr->tmpIn + dctxPtr->tmpInSize, srcPtr, sizeToCopy);\n                srcPtr += sizeToCopy;\n                dctxPtr->tmpInSize += sizeToCopy;\n                if (dctxPtr->tmpInSize < 4)  /* not enough input to read complete suffix */\n                {\n                    nextSrcSizeHint = 4 - dctxPtr->tmpInSize;\n                    doAnotherStage=0;\n                    break;\n                }\n                selectedIn = dctxPtr->tmpIn;\n                dctxPtr->dStage = dstage_checkSuffix;\n                break;\n            }\n\n        case dstage_checkSuffix:\n            {\n                U32 readCRC = LZ4F_readLE32(selectedIn);\n                U32 resultCRC = XXH32_digest(&(dctxPtr->xxh));\n                if (readCRC != resultCRC) return (size_t)-ERROR_checksum_invalid;\n                nextSrcSizeHint = 0;\n                dctxPtr->dStage = dstage_getHeader;\n                doAnotherStage = 0;\n                break;\n            }\n        }\n    }\n\n    /* preserve dictionary within tmp if necessary */\n    if ( (dctxPtr->frameInfo.blockMode==blockLinked)\n        &&(dctxPtr->dict != dctxPtr->tmpOutBuffer)\n        &&(!decompressOptionsPtr->stableDst)\n        &&((unsigned)(dctxPtr->dStage-1) < (unsigned)(dstage_getSuffix-1))\n        )\n    {\n        if (dctxPtr->dStage == dstage_flushOut)\n        {\n            size_t preserveSize = dctxPtr->tmpOut - dctxPtr->tmpOutBuffer;\n            size_t copySize = 64 KB - dctxPtr->tmpOutSize;\n            BYTE* oldDictEnd = dctxPtr->dict + dctxPtr->dictSize - dctxPtr->tmpOutStart;\n            if (dctxPtr->tmpOutSize > 64 KB) copySize = 0;\n            if (copySize > preserveSize) copySize = preserveSize;\n\n            memcpy(dctxPtr->tmpOutBuffer + preserveSize - copySize, oldDictEnd - copySize, copySize);\n\n            dctxPtr->dict = dctxPtr->tmpOutBuffer;\n            dctxPtr->dictSize = preserveSize + dctxPtr->tmpOutStart;\n        }\n        else\n        {\n            size_t newDictSize = dctxPtr->dictSize;\n            BYTE* oldDictEnd = dctxPtr->dict + dctxPtr->dictSize;\n            if ((newDictSize) > 64 KB) newDictSize = 64 KB;\n\n            memcpy(dctxPtr->tmpOutBuffer, oldDictEnd - newDictSize, newDictSize);\n\n            dctxPtr->dict = dctxPtr->tmpOutBuffer;\n            dctxPtr->dictSize = newDictSize;\n            dctxPtr->tmpOut = dctxPtr->tmpOutBuffer + newDictSize;\n        }\n    }\n\n    if (srcPtr<srcEnd)   /* function must be called again with following source data */\n        dctxPtr->srcExpect = srcPtr;\n    else\n        dctxPtr->srcExpect = NULL;\n    *srcSizePtr = (srcPtr - srcStart);\n    *dstSizePtr = (dstPtr - dstStart);\n    return nextSrcSizeHint;\n}\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/imgui_remote/lz4/lz4frame.h",
    "content": "/*\n   LZ4 auto-framing library\n   Header File\n   Copyright (C) 2011-2015, Yann Collet.\n   BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)\n\n   Redistribution and use in source and binary forms, with or without\n   modification, are permitted provided that the following conditions are\n   met:\n\n       * Redistributions of source code must retain the above copyright\n   notice, this list of conditions and the following disclaimer.\n       * Redistributions in binary form must reproduce the above\n   copyright notice, this list of conditions and the following disclaimer\n   in the documentation and/or other materials provided with the\n   distribution.\n\n   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n   \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n   You can contact the author at :\n   - LZ4 source repository : http://code.google.com/p/lz4/\n   - LZ4 source mirror : https://github.com/Cyan4973/lz4\n   - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c\n*/\n\n/* LZ4F is a stand-alone API to create LZ4-compressed frames\n * fully conformant to specification v1.4.1.\n * All related operations, including memory management, are handled by the library.\n * You don't need lz4.h when using lz4frame.h.\n * */\n\n#pragma once\n\n#if defined (__cplusplus)\nextern \"C\" {\n#endif\n\n/**************************************\n   Includes\n**************************************/\n#include <stddef.h>   /* size_t */\n\n\n/**************************************\n * Error management\n * ************************************/\ntypedef size_t LZ4F_errorCode_t;\n\nunsigned    LZ4F_isError(LZ4F_errorCode_t code);\nconst char* LZ4F_getErrorName(LZ4F_errorCode_t code);   /* return error code string; useful for debugging */\n\n\n/**************************************\n * Frame compression types\n * ************************************/\ntypedef enum { LZ4F_default=0, max64KB=4, max256KB=5, max1MB=6, max4MB=7 } blockSizeID_t;\ntypedef enum { blockLinked=0, blockIndependent} blockMode_t;\ntypedef enum { noContentChecksum=0, contentChecksumEnabled } contentChecksum_t;\n\ntypedef struct {\n  blockSizeID_t     blockSizeID;           /* max64KB, max256KB, max1MB, max4MB ; 0 == default */\n  blockMode_t       blockMode;             /* blockLinked, blockIndependent ; 0 == default */\n  contentChecksum_t contentChecksumFlag;   /* noContentChecksum, contentChecksumEnabled ; 0 == default  */\n  unsigned          reserved[5];\n} LZ4F_frameInfo_t;\n\ntypedef struct {\n  LZ4F_frameInfo_t frameInfo;\n  unsigned         compressionLevel;       /* 0 == default (fast mode); values above 16 count as 16 */\n  unsigned         autoFlush;              /* 1 == always flush : reduce need for tmp buffer */\n  unsigned         reserved[4];\n} LZ4F_preferences_t;\n\n\n/***********************************\n * Simple compression function\n * *********************************/\nsize_t LZ4F_compressFrameBound(size_t srcSize, const LZ4F_preferences_t* preferencesPtr);\n\nsize_t LZ4F_compressFrame(void* dstBuffer, size_t dstMaxSize, const void* srcBuffer, size_t srcSize, const LZ4F_preferences_t* preferencesPtr);\n/* LZ4F_compressFrame()\n * Compress an entire srcBuffer into a valid LZ4 frame, as defined by specification v1.4.1.\n * The most important rule is that dstBuffer MUST be large enough (dstMaxSize) to ensure compression completion even in worst case.\n * You can get the minimum value of dstMaxSize by using LZ4F_compressFrameBound()\n * If this condition is not respected, LZ4F_compressFrame() will fail (result is an errorCode)\n * The LZ4F_preferences_t structure is optional : you can provide NULL as argument. All preferences will be set to default.\n * The result of the function is the number of bytes written into dstBuffer.\n * The function outputs an error code if it fails (can be tested using LZ4F_isError())\n */\n\n\n\n/**********************************\n * Advanced compression functions\n * ********************************/\ntypedef void* LZ4F_compressionContext_t;\n\ntypedef struct {\n  unsigned stableSrc;    /* 1 == src content will remain available on future calls to LZ4F_compress(); avoid saving src content within tmp buffer as future dictionary */\n  unsigned reserved[3];\n} LZ4F_compressOptions_t;\n\n/* Resource Management */\n\n#define LZ4F_VERSION 100\nLZ4F_errorCode_t LZ4F_createCompressionContext(LZ4F_compressionContext_t* LZ4F_compressionContextPtr, unsigned version);\nLZ4F_errorCode_t LZ4F_freeCompressionContext(LZ4F_compressionContext_t LZ4F_compressionContext);\n/* LZ4F_createCompressionContext() :\n * The first thing to do is to create a compressionContext object, which will be used in all compression operations.\n * This is achieved using LZ4F_createCompressionContext(), which takes as argument a version and an LZ4F_preferences_t structure.\n * The version provided MUST be LZ4F_VERSION. It is intended to track potential version differences between different binaries.\n * The function will provide a pointer to a fully allocated LZ4F_compressionContext_t object.\n * If the result LZ4F_errorCode_t is not zero, there was an error during context creation.\n * Object can release its memory using LZ4F_freeCompressionContext();\n */\n\n\n/* Compression */\n\nsize_t LZ4F_compressBegin(LZ4F_compressionContext_t compressionContext, void* dstBuffer, size_t dstMaxSize, const LZ4F_preferences_t* preferencesPtr);\n/* LZ4F_compressBegin() :\n * will write the frame header into dstBuffer.\n * dstBuffer must be large enough to accommodate a header (dstMaxSize). Maximum header size is 19 bytes.\n * The LZ4F_preferences_t structure is optional : you can provide NULL as argument, all preferences will then be set to default.\n * The result of the function is the number of bytes written into dstBuffer for the header\n * or an error code (can be tested using LZ4F_isError())\n */\n\nsize_t LZ4F_compressBound(size_t srcSize, const LZ4F_preferences_t* preferencesPtr);\n/* LZ4F_compressBound() :\n * Provides the minimum size of Dst buffer given srcSize to handle worst case situations.\n * preferencesPtr is optional : you can provide NULL as argument, all preferences will then be set to default.\n * Note that different preferences will produce in different results.\n */\n\nsize_t LZ4F_compressUpdate(LZ4F_compressionContext_t compressionContext, void* dstBuffer, size_t dstMaxSize, const void* srcBuffer, size_t srcSize, const LZ4F_compressOptions_t* compressOptionsPtr);\n/* LZ4F_compressUpdate()\n * LZ4F_compressUpdate() can be called repetitively to compress as much data as necessary.\n * The most important rule is that dstBuffer MUST be large enough (dstMaxSize) to ensure compression completion even in worst case.\n * If this condition is not respected, LZ4F_compress() will fail (result is an errorCode)\n * You can get the minimum value of dstMaxSize by using LZ4F_compressBound()\n * The LZ4F_compressOptions_t structure is optional : you can provide NULL as argument.\n * The result of the function is the number of bytes written into dstBuffer : it can be zero, meaning input data was just buffered.\n * The function outputs an error code if it fails (can be tested using LZ4F_isError())\n */\n\nsize_t LZ4F_flush(LZ4F_compressionContext_t compressionContext, void* dstBuffer, size_t dstMaxSize, const LZ4F_compressOptions_t* compressOptionsPtr);\n/* LZ4F_flush()\n * Should you need to create compressed data immediately, without waiting for a block to be filled,\n * you can call LZ4_flush(), which will immediately compress any remaining data buffered within compressionContext.\n * The LZ4F_compressOptions_t structure is optional : you can provide NULL as argument.\n * The result of the function is the number of bytes written into dstBuffer\n * (it can be zero, this means there was no data left within compressionContext)\n * The function outputs an error code if it fails (can be tested using LZ4F_isError())\n */\n\nsize_t LZ4F_compressEnd(LZ4F_compressionContext_t compressionContext, void* dstBuffer, size_t dstMaxSize, const LZ4F_compressOptions_t* compressOptionsPtr);\n/* LZ4F_compressEnd()\n * When you want to properly finish the compressed frame, just call LZ4F_compressEnd().\n * It will flush whatever data remained within compressionContext (like LZ4_flush())\n * but also properly finalize the frame, with an endMark and a checksum.\n * The result of the function is the number of bytes written into dstBuffer (necessarily >= 4 (endMark size))\n * The function outputs an error code if it fails (can be tested using LZ4F_isError())\n * The LZ4F_compressOptions_t structure is optional : you can provide NULL as argument.\n * compressionContext can then be used again, starting with LZ4F_compressBegin().\n */\n\n\n/***********************************\n * Decompression functions\n * *********************************/\n\ntypedef void* LZ4F_decompressionContext_t;\n\ntypedef struct {\n  unsigned stableDst;       /* guarantee that decompressed data will still be there on next function calls (avoid storage into tmp buffers) */\n  unsigned reserved[3];\n} LZ4F_decompressOptions_t;\n\n\n/* Resource management */\n\nLZ4F_errorCode_t LZ4F_createDecompressionContext(LZ4F_decompressionContext_t* ctxPtr, unsigned version);\nLZ4F_errorCode_t LZ4F_freeDecompressionContext(LZ4F_decompressionContext_t ctx);\n/* LZ4F_createDecompressionContext() :\n * The first thing to do is to create a decompressionContext object, which will be used in all decompression operations.\n * This is achieved using LZ4F_createDecompressionContext().\n * The version provided MUST be LZ4F_VERSION. It is intended to track potential version differences between different binaries.\n * The function will provide a pointer to a fully allocated and initialized LZ4F_decompressionContext_t object.\n * If the result LZ4F_errorCode_t is not OK_NoError, there was an error during context creation.\n * Object can release its memory using LZ4F_freeDecompressionContext();\n */\n\n\n/* Decompression */\n\nsize_t LZ4F_getFrameInfo(LZ4F_decompressionContext_t ctx,\n                         LZ4F_frameInfo_t* frameInfoPtr,\n                         const void* srcBuffer, size_t* srcSizePtr);\n/* LZ4F_getFrameInfo()\n * This function decodes frame header information, such as blockSize.\n * It is optional : you could start by calling directly LZ4F_decompress() instead.\n * The objective is to extract header information without starting decompression, typically for allocation purposes.\n * LZ4F_getFrameInfo() can also be used *after* starting decompression, on a valid LZ4F_decompressionContext_t.\n * The number of bytes read from srcBuffer will be provided within *srcSizePtr (necessarily <= original value).\n * You are expected to resume decompression from where it stopped (srcBuffer + *srcSizePtr)\n * The function result is an hint of how many srcSize bytes LZ4F_decompress() expects for next call,\n * or an error code which can be tested using LZ4F_isError().\n */\n\nsize_t LZ4F_decompress(LZ4F_decompressionContext_t ctx,\n                       void* dstBuffer, size_t* dstSizePtr,\n                       const void* srcBuffer, size_t* srcSizePtr,\n                       const LZ4F_decompressOptions_t* optionsPtr);\n/* LZ4F_decompress()\n * Call this function repetitively to regenerate data compressed within srcBuffer.\n * The function will attempt to decode *srcSizePtr bytes from srcBuffer, into dstBuffer of maximum size *dstSizePtr.\n *\n * The number of bytes regenerated into dstBuffer will be provided within *dstSizePtr (necessarily <= original value).\n *\n * The number of bytes read from srcBuffer will be provided within *srcSizePtr (necessarily <= original value).\n * If number of bytes read is < number of bytes provided, then decompression operation is not completed.\n * It typically happens when dstBuffer is not large enough to contain all decoded data.\n * LZ4F_decompress() must be called again, starting from where it stopped (srcBuffer + *srcSizePtr)\n * The function will check this condition, and refuse to continue if it is not respected.\n *\n * dstBuffer is supposed to be flushed between each call to the function, since its content will be overwritten.\n * dst arguments can be changed at will with each consecutive call to the function.\n *\n * The function result is an hint of how many srcSize bytes LZ4F_decompress() expects for next call.\n * Schematically, it's the size of the current (or remaining) compressed block + header of next block.\n * Respecting the hint provides some boost to performance, since it does skip intermediate buffers.\n * This is just a hint, you can always provide any srcSize you want.\n * When a frame is fully decoded, the function result will be 0. (no more data expected)\n * If decompression failed, function result is an error code, which can be tested using LZ4F_isError().\n */\n\n\n\n#if defined (__cplusplus)\n}\n#endif\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/imgui_remote/lz4/lz4frame_static.h",
    "content": "/*\n   LZ4 auto-framing library\n   Header File for static linking only\n   Copyright (C) 2011-2015, Yann Collet.\n\n   BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)\n\n   Redistribution and use in source and binary forms, with or without\n   modification, are permitted provided that the following conditions are\n   met:\n\n       * Redistributions of source code must retain the above copyright\n   notice, this list of conditions and the following disclaimer.\n       * Redistributions in binary form must reproduce the above\n   copyright notice, this list of conditions and the following disclaimer\n   in the documentation and/or other materials provided with the\n   distribution.\n\n   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n   \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n   You can contact the author at :\n   - LZ4 source repository : http://code.google.com/p/lz4/\n   - LZ4 source mirror : https://github.com/Cyan4973/lz4\n   - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c\n*/\n\n#pragma once\n\n#if defined (__cplusplus)\nextern \"C\" {\n#endif\n\n/* lz4frame_static.h should be used solely in the context of static linking.\n * */\n\n\n/**************************************\n * Error management\n * ************************************/\n#define LZ4F_LIST_ERRORS(ITEM) \\\n        ITEM(OK_NoError) ITEM(ERROR_GENERIC) \\\n        ITEM(ERROR_maxBlockSize_invalid) ITEM(ERROR_blockMode_invalid) ITEM(ERROR_contentChecksumFlag_invalid) \\\n        ITEM(ERROR_compressionLevel_invalid) \\\n        ITEM(ERROR_allocation_failed) \\\n        ITEM(ERROR_srcSize_tooLarge) ITEM(ERROR_dstMaxSize_tooSmall) \\\n        ITEM(ERROR_decompressionFailed) \\\n        ITEM(ERROR_checksum_invalid) \\\n        ITEM(ERROR_maxCode)\n\n#define LZ4F_GENERATE_ENUM(ENUM) ENUM,\ntypedef enum { LZ4F_LIST_ERRORS(LZ4F_GENERATE_ENUM) } LZ4F_errorCodes;  /* enum is exposed, to handle specific errors; compare function result to -enum value */\n\n\n/**************************************\n   Includes\n**************************************/\n#include \"lz4frame.h\"\n\n\n#if defined (__cplusplus)\n}\n#endif\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/imgui_remote/lz4/lz4hc.c",
    "content": "/*\nLZ4 HC - High Compression Mode of LZ4\nCopyright (C) 2011-2014, Yann Collet.\nBSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n* Redistributions of source code must retain the above copyright\nnotice, this list of conditions and the following disclaimer.\n* Redistributions in binary form must reproduce the above\ncopyright notice, this list of conditions and the following disclaimer\nin the documentation and/or other materials provided with the\ndistribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(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\nYou can contact the author at :\n- LZ4 homepage : http://fastcompression.blogspot.com/p/lz4.html\n- LZ4 source repository : http://code.google.com/p/lz4/\n*/\n\n\n\n/**************************************\n   Tuning Parameter\n**************************************/\nstatic const int LZ4HC_compressionLevel_default = 8;\n\n\n/**************************************\n   Includes\n**************************************/\n#include \"lz4hc.h\"\n\n\n/**************************************\n   Local Compiler Options\n**************************************/\n#if defined(__GNUC__)\n#  pragma GCC diagnostic ignored \"-Wunused-function\"\n#endif\n\n#if defined (__clang__)\n#  pragma clang diagnostic ignored \"-Wunused-function\"\n#endif\n\n\n/**************************************\n   Common LZ4 definition\n**************************************/\n#define LZ4_COMMONDEFS_ONLY\n#include \"lz4.c\"\n\n\n/**************************************\n  Local Constants\n**************************************/\n#define DICTIONARY_LOGSIZE 16\n#define MAXD (1<<DICTIONARY_LOGSIZE)\n#define MAXD_MASK ((U32)(MAXD - 1))\n\n#define HASH_LOG (DICTIONARY_LOGSIZE-1)\n#define HASHTABLESIZE (1 << HASH_LOG)\n#define HASH_MASK (HASHTABLESIZE - 1)\n\n#define OPTIMAL_ML (int)((ML_MASK-1)+MINMATCH)\n\nstatic const int g_maxCompressionLevel = 16;\n\n\n/**************************************\n   Local Types\n**************************************/\ntypedef struct\n{\n    U32 hashTable[HASHTABLESIZE];\n    U16   chainTable[MAXD];\n    const BYTE* end;        /* next block here to continue on current prefix */\n    const BYTE* base;       /* All index relative to this position */\n    const BYTE* dictBase;   /* alternate base for extDict */\n    const BYTE* inputBuffer;/* deprecated */\n    U32   dictLimit;        /* below that point, need extDict */\n    U32   lowLimit;         /* below that point, no more dict */\n    U32   nextToUpdate;\n    U32   compressionLevel;\n} LZ4HC_Data_Structure;\n\n\n/**************************************\n   Local Macros\n**************************************/\n#define HASH_FUNCTION(i)       (((i) * 2654435761U) >> ((MINMATCH*8)-HASH_LOG))\n#define DELTANEXT(p)           chainTable[(size_t)(p) & MAXD_MASK]\n#define GETNEXT(p)             ((p) - (size_t)DELTANEXT(p))\n\nstatic U32 LZ4HC_hashPtr(const void* ptr) { return HASH_FUNCTION(LZ4_read32(ptr)); }\n\n\n\n/**************************************\n   HC Compression\n**************************************/\nstatic void LZ4HC_init (LZ4HC_Data_Structure* hc4, const BYTE* start)\n{\n    MEM_INIT((void*)hc4->hashTable, 0, sizeof(hc4->hashTable));\n    MEM_INIT(hc4->chainTable, 0xFF, sizeof(hc4->chainTable));\n    hc4->nextToUpdate = 64 KB;\n    hc4->base = start - 64 KB;\n    hc4->inputBuffer = start;\n    hc4->end = start;\n    hc4->dictBase = start - 64 KB;\n    hc4->dictLimit = 64 KB;\n    hc4->lowLimit = 64 KB;\n}\n\n\n/* Update chains up to ip (excluded) */\nFORCE_INLINE void LZ4HC_Insert (LZ4HC_Data_Structure* hc4, const BYTE* ip)\n{\n    U16* chainTable = hc4->chainTable;\n    U32* HashTable  = hc4->hashTable;\n    const BYTE* const base = hc4->base;\n    const U32 target = (U32)(ip - base);\n    U32 idx = hc4->nextToUpdate;\n\n    while(idx < target)\n    {\n        U32 h = LZ4HC_hashPtr(base+idx);\n        size_t delta = idx - HashTable[h];\n        if (delta>MAX_DISTANCE) delta = MAX_DISTANCE;\n        chainTable[idx & 0xFFFF] = (U16)delta;\n        HashTable[h] = idx;\n        idx++;\n    }\n\n    hc4->nextToUpdate = target;\n}\n\n\nFORCE_INLINE int LZ4HC_InsertAndFindBestMatch (LZ4HC_Data_Structure* hc4,   /* Index table will be updated */\n                                               const BYTE* ip, const BYTE* const iLimit,\n                                               const BYTE** matchpos,\n                                               const int maxNbAttempts)\n{\n    U16* const chainTable = hc4->chainTable;\n    U32* const HashTable = hc4->hashTable;\n    const BYTE* const base = hc4->base;\n    const BYTE* const dictBase = hc4->dictBase;\n    const U32 dictLimit = hc4->dictLimit;\n    const U32 lowLimit = (hc4->lowLimit + 64 KB > (U32)(ip-base)) ? hc4->lowLimit : (U32)(ip - base) - (64 KB - 1);\n    U32 matchIndex;\n    const BYTE* match;\n    int nbAttempts=maxNbAttempts;\n    size_t ml=0;\n\n    /* HC4 match finder */\n    LZ4HC_Insert(hc4, ip);\n    matchIndex = HashTable[LZ4HC_hashPtr(ip)];\n\n    while ((matchIndex>=lowLimit) && (nbAttempts))\n    {\n        nbAttempts--;\n        if (matchIndex >= dictLimit)\n        {\n            match = base + matchIndex;\n            if (*(match+ml) == *(ip+ml)\n                && (LZ4_read32(match) == LZ4_read32(ip)))\n            {\n                size_t mlt = LZ4_count(ip+MINMATCH, match+MINMATCH, iLimit) + MINMATCH;\n                if (mlt > ml) { ml = mlt; *matchpos = match; }\n            }\n        }\n        else\n        {\n            match = dictBase + matchIndex;\n            if (LZ4_read32(match) == LZ4_read32(ip))\n            {\n                size_t mlt;\n                const BYTE* vLimit = ip + (dictLimit - matchIndex);\n                if (vLimit > iLimit) vLimit = iLimit;\n                mlt = LZ4_count(ip+MINMATCH, match+MINMATCH, vLimit) + MINMATCH;\n                if ((ip+mlt == vLimit) && (vLimit < iLimit))\n                    mlt += LZ4_count(ip+mlt, base+dictLimit, iLimit);\n                if (mlt > ml) { ml = mlt; *matchpos = base + matchIndex; }   /* virtual matchpos */\n            }\n        }\n        matchIndex -= chainTable[matchIndex & 0xFFFF];\n    }\n\n    return (int)ml;\n}\n\n\nFORCE_INLINE int LZ4HC_InsertAndGetWiderMatch (\n    LZ4HC_Data_Structure* hc4,\n    const BYTE* ip,\n    const BYTE* iLowLimit,\n    const BYTE* iHighLimit,\n    int longest,\n    const BYTE** matchpos,\n    const BYTE** startpos,\n    const int maxNbAttempts)\n{\n    U16* const chainTable = hc4->chainTable;\n    U32* const HashTable = hc4->hashTable;\n    const BYTE* const base = hc4->base;\n    const U32 dictLimit = hc4->dictLimit;\n    const U32 lowLimit = (hc4->lowLimit + 64 KB > (U32)(ip-base)) ? hc4->lowLimit : (U32)(ip - base) - (64 KB - 1);\n    const BYTE* const dictBase = hc4->dictBase;\n    const BYTE* match;\n    U32   matchIndex;\n    int nbAttempts = maxNbAttempts;\n    int delta = (int)(ip-iLowLimit);\n\n\n    /* First Match */\n    LZ4HC_Insert(hc4, ip);\n    matchIndex = HashTable[LZ4HC_hashPtr(ip)];\n\n    while ((matchIndex>=lowLimit) && (nbAttempts))\n    {\n        nbAttempts--;\n        if (matchIndex >= dictLimit)\n        {\n            match = base + matchIndex;\n            if (*(iLowLimit + longest) == *(match - delta + longest))\n                if (LZ4_read32(match) == LZ4_read32(ip))\n                {\n                    const BYTE* startt = ip;\n                    const BYTE* tmpMatch = match;\n                    const BYTE* const matchEnd = ip + MINMATCH + LZ4_count(ip+MINMATCH, match+MINMATCH, iHighLimit);\n\n                    while ((startt>iLowLimit) && (tmpMatch > iLowLimit) && (startt[-1] == tmpMatch[-1])) {startt--; tmpMatch--;}\n\n                    if ((matchEnd-startt) > longest)\n                    {\n                        longest = (int)(matchEnd-startt);\n                        *matchpos = tmpMatch;\n                        *startpos = startt;\n                    }\n                }\n        }\n        else\n        {\n            match = dictBase + matchIndex;\n            if (LZ4_read32(match) == LZ4_read32(ip))\n            {\n                size_t mlt;\n                int back=0;\n                const BYTE* vLimit = ip + (dictLimit - matchIndex);\n                if (vLimit > iHighLimit) vLimit = iHighLimit;\n                mlt = LZ4_count(ip+MINMATCH, match+MINMATCH, vLimit) + MINMATCH;\n                if ((ip+mlt == vLimit) && (vLimit < iHighLimit))\n                    mlt += LZ4_count(ip+mlt, base+dictLimit, iHighLimit);\n                while ((ip+back > iLowLimit) && (matchIndex+back > lowLimit) && (ip[back-1] == match[back-1])) back--;\n                mlt -= back;\n                if ((int)mlt > longest) { longest = (int)mlt; *matchpos = base + matchIndex + back; *startpos = ip+back; }\n            }\n        }\n        matchIndex -= chainTable[matchIndex & 0xFFFF];\n    }\n\n    return longest;\n}\n\n\ntypedef enum { noLimit = 0, limitedOutput = 1 } limitedOutput_directive;\n\n#define LZ4HC_DEBUG 0\n#if LZ4HC_DEBUG\nstatic unsigned debug = 0;\n#endif\n\nFORCE_INLINE int LZ4HC_encodeSequence (\n    const BYTE** ip,\n    BYTE** op,\n    const BYTE** anchor,\n    int matchLength,\n    const BYTE* const match,\n    limitedOutput_directive limitedOutputBuffer,\n    BYTE* oend)\n{\n    int length;\n    BYTE* token;\n\n#if LZ4HC_DEBUG\n    if (debug) printf(\"literal : %u  --  match : %u  --  offset : %u\\n\", (U32)(*ip - *anchor), (U32)matchLength, (U32)(*ip-match));\n#endif\n\n    /* Encode Literal length */\n    length = (int)(*ip - *anchor);\n    token = (*op)++;\n    if ((limitedOutputBuffer) && ((*op + (length>>8) + length + (2 + 1 + LASTLITERALS)) > oend)) return 1;   /* Check output limit */\n    if (length>=(int)RUN_MASK) { int len; *token=(RUN_MASK<<ML_BITS); len = length-RUN_MASK; for(; len > 254 ; len-=255) *(*op)++ = 255;  *(*op)++ = (BYTE)len; }\n    else *token = (BYTE)(length<<ML_BITS);\n\n    /* Copy Literals */\n    LZ4_wildCopy(*op, *anchor, (*op) + length);\n    *op += length;\n\n    /* Encode Offset */\n    LZ4_writeLE16(*op, (U16)(*ip-match)); *op += 2;\n\n    /* Encode MatchLength */\n    length = (int)(matchLength-MINMATCH);\n    if ((limitedOutputBuffer) && (*op + (length>>8) + (1 + LASTLITERALS) > oend)) return 1;   /* Check output limit */\n    if (length>=(int)ML_MASK) { *token+=ML_MASK; length-=ML_MASK; for(; length > 509 ; length-=510) { *(*op)++ = 255; *(*op)++ = 255; } if (length > 254) { length-=255; *(*op)++ = 255; } *(*op)++ = (BYTE)length; }\n    else *token += (BYTE)(length);\n\n    /* Prepare next loop */\n    *ip += matchLength;\n    *anchor = *ip;\n\n    return 0;\n}\n\n\nstatic int LZ4HC_compress_generic (\n    void* ctxvoid,\n    const char* source,\n    char* dest,\n    int inputSize,\n    int maxOutputSize,\n    int compressionLevel,\n    limitedOutput_directive limit\n    )\n{\n    LZ4HC_Data_Structure* ctx = (LZ4HC_Data_Structure*) ctxvoid;\n    const BYTE* ip = (const BYTE*) source;\n    const BYTE* anchor = ip;\n    const BYTE* const iend = ip + inputSize;\n    const BYTE* const mflimit = iend - MFLIMIT;\n    const BYTE* const matchlimit = (iend - LASTLITERALS);\n\n    BYTE* op = (BYTE*) dest;\n    BYTE* const oend = op + maxOutputSize;\n\n    unsigned maxNbAttempts;\n    int   ml, ml2, ml3, ml0;\n    const BYTE* ref=NULL;\n    const BYTE* start2=NULL;\n    const BYTE* ref2=NULL;\n    const BYTE* start3=NULL;\n    const BYTE* ref3=NULL;\n    const BYTE* start0;\n    const BYTE* ref0;\n\n\n    /* init */\n    if (compressionLevel > g_maxCompressionLevel) compressionLevel = g_maxCompressionLevel;\n    if (compressionLevel < 1) compressionLevel = LZ4HC_compressionLevel_default;\n    maxNbAttempts = 1 << (compressionLevel-1);\n    ctx->end += inputSize;\n\n    ip++;\n\n    /* Main Loop */\n    while (ip < mflimit)\n    {\n        ml = LZ4HC_InsertAndFindBestMatch (ctx, ip, matchlimit, (&ref), maxNbAttempts);\n        if (!ml) { ip++; continue; }\n\n        /* saved, in case we would skip too much */\n        start0 = ip;\n        ref0 = ref;\n        ml0 = ml;\n\n_Search2:\n        if (ip+ml < mflimit)\n            ml2 = LZ4HC_InsertAndGetWiderMatch(ctx, ip + ml - 2, ip + 1, matchlimit, ml, &ref2, &start2, maxNbAttempts);\n        else ml2 = ml;\n\n        if (ml2 == ml)  /* No better match */\n        {\n            if (LZ4HC_encodeSequence(&ip, &op, &anchor, ml, ref, limit, oend)) return 0;\n            continue;\n        }\n\n        if (start0 < ip)\n        {\n            if (start2 < ip + ml0)   /* empirical */\n            {\n                ip = start0;\n                ref = ref0;\n                ml = ml0;\n            }\n        }\n\n        /* Here, start0==ip */\n        if ((start2 - ip) < 3)   /* First Match too small : removed */\n        {\n            ml = ml2;\n            ip = start2;\n            ref =ref2;\n            goto _Search2;\n        }\n\n_Search3:\n        /*\n        * Currently we have :\n        * ml2 > ml1, and\n        * ip1+3 <= ip2 (usually < ip1+ml1)\n        */\n        if ((start2 - ip) < OPTIMAL_ML)\n        {\n            int correction;\n            int new_ml = ml;\n            if (new_ml > OPTIMAL_ML) new_ml = OPTIMAL_ML;\n            if (ip+new_ml > start2 + ml2 - MINMATCH) new_ml = (int)(start2 - ip) + ml2 - MINMATCH;\n            correction = new_ml - (int)(start2 - ip);\n            if (correction > 0)\n            {\n                start2 += correction;\n                ref2 += correction;\n                ml2 -= correction;\n            }\n        }\n        /* Now, we have start2 = ip+new_ml, with new_ml = min(ml, OPTIMAL_ML=18) */\n\n        if (start2 + ml2 < mflimit)\n            ml3 = LZ4HC_InsertAndGetWiderMatch(ctx, start2 + ml2 - 3, start2, matchlimit, ml2, &ref3, &start3, maxNbAttempts);\n        else ml3 = ml2;\n\n        if (ml3 == ml2) /* No better match : 2 sequences to encode */\n        {\n            /* ip & ref are known; Now for ml */\n            if (start2 < ip+ml)  ml = (int)(start2 - ip);\n            /* Now, encode 2 sequences */\n            if (LZ4HC_encodeSequence(&ip, &op, &anchor, ml, ref, limit, oend)) return 0;\n            ip = start2;\n            if (LZ4HC_encodeSequence(&ip, &op, &anchor, ml2, ref2, limit, oend)) return 0;\n            continue;\n        }\n\n        if (start3 < ip+ml+3) /* Not enough space for match 2 : remove it */\n        {\n            if (start3 >= (ip+ml)) /* can write Seq1 immediately ==> Seq2 is removed, so Seq3 becomes Seq1 */\n            {\n                if (start2 < ip+ml)\n                {\n                    int correction = (int)(ip+ml - start2);\n                    start2 += correction;\n                    ref2 += correction;\n                    ml2 -= correction;\n                    if (ml2 < MINMATCH)\n                    {\n                        start2 = start3;\n                        ref2 = ref3;\n                        ml2 = ml3;\n                    }\n                }\n\n                if (LZ4HC_encodeSequence(&ip, &op, &anchor, ml, ref, limit, oend)) return 0;\n                ip  = start3;\n                ref = ref3;\n                ml  = ml3;\n\n                start0 = start2;\n                ref0 = ref2;\n                ml0 = ml2;\n                goto _Search2;\n            }\n\n            start2 = start3;\n            ref2 = ref3;\n            ml2 = ml3;\n            goto _Search3;\n        }\n\n        /*\n        * OK, now we have 3 ascending matches; let's write at least the first one\n        * ip & ref are known; Now for ml\n        */\n        if (start2 < ip+ml)\n        {\n            if ((start2 - ip) < (int)ML_MASK)\n            {\n                int correction;\n                if (ml > OPTIMAL_ML) ml = OPTIMAL_ML;\n                if (ip + ml > start2 + ml2 - MINMATCH) ml = (int)(start2 - ip) + ml2 - MINMATCH;\n                correction = ml - (int)(start2 - ip);\n                if (correction > 0)\n                {\n                    start2 += correction;\n                    ref2 += correction;\n                    ml2 -= correction;\n                }\n            }\n            else\n            {\n                ml = (int)(start2 - ip);\n            }\n        }\n        if (LZ4HC_encodeSequence(&ip, &op, &anchor, ml, ref, limit, oend)) return 0;\n\n        ip = start2;\n        ref = ref2;\n        ml = ml2;\n\n        start2 = start3;\n        ref2 = ref3;\n        ml2 = ml3;\n\n        goto _Search3;\n    }\n\n    /* Encode Last Literals */\n    {\n        int lastRun = (int)(iend - anchor);\n        if ((limit) && (((char*)op - dest) + lastRun + 1 + ((lastRun+255-RUN_MASK)/255) > (U32)maxOutputSize)) return 0;  /* Check output limit */\n        if (lastRun>=(int)RUN_MASK) { *op++=(RUN_MASK<<ML_BITS); lastRun-=RUN_MASK; for(; lastRun > 254 ; lastRun-=255) *op++ = 255; *op++ = (BYTE) lastRun; }\n        else *op++ = (BYTE)(lastRun<<ML_BITS);\n        memcpy(op, anchor, iend - anchor);\n        op += iend-anchor;\n    }\n\n    /* End */\n    return (int) (((char*)op)-dest);\n}\n\n\nint LZ4_compressHC2(const char* source, char* dest, int inputSize, int compressionLevel)\n{\n    LZ4HC_Data_Structure ctx;\n    LZ4HC_init(&ctx, (const BYTE*)source);\n    return LZ4HC_compress_generic (&ctx, source, dest, inputSize, 0, compressionLevel, noLimit);\n}\n\nint LZ4_compressHC(const char* source, char* dest, int inputSize) { return LZ4_compressHC2(source, dest, inputSize, 0); }\n\nint LZ4_compressHC2_limitedOutput(const char* source, char* dest, int inputSize, int maxOutputSize, int compressionLevel)\n{\n    LZ4HC_Data_Structure ctx;\n    LZ4HC_init(&ctx, (const BYTE*)source);\n    return LZ4HC_compress_generic (&ctx, source, dest, inputSize, maxOutputSize, compressionLevel, limitedOutput);\n}\n\nint LZ4_compressHC_limitedOutput(const char* source, char* dest, int inputSize, int maxOutputSize)\n{\n    return LZ4_compressHC2_limitedOutput(source, dest, inputSize, maxOutputSize, 0);\n}\n\n\n/*****************************\n * Using external allocation\n * ***************************/\nint LZ4_sizeofStateHC(void) { return sizeof(LZ4HC_Data_Structure); }\n\n\nint LZ4_compressHC2_withStateHC (void* state, const char* source, char* dest, int inputSize, int compressionLevel)\n{\n    if (((size_t)(state)&(sizeof(void*)-1)) != 0) return 0;   /* Error : state is not aligned for pointers (32 or 64 bits) */\n    LZ4HC_init ((LZ4HC_Data_Structure*)state, (const BYTE*)source);\n    return LZ4HC_compress_generic (state, source, dest, inputSize, 0, compressionLevel, noLimit);\n}\n\nint LZ4_compressHC_withStateHC (void* state, const char* source, char* dest, int inputSize)\n{ return LZ4_compressHC2_withStateHC (state, source, dest, inputSize, 0); }\n\n\nint LZ4_compressHC2_limitedOutput_withStateHC (void* state, const char* source, char* dest, int inputSize, int maxOutputSize, int compressionLevel)\n{\n    if (((size_t)(state)&(sizeof(void*)-1)) != 0) return 0;   /* Error : state is not aligned for pointers (32 or 64 bits) */\n    LZ4HC_init ((LZ4HC_Data_Structure*)state, (const BYTE*)source);\n    return LZ4HC_compress_generic (state, source, dest, inputSize, maxOutputSize, compressionLevel, limitedOutput);\n}\n\nint LZ4_compressHC_limitedOutput_withStateHC (void* state, const char* source, char* dest, int inputSize, int maxOutputSize)\n{ return LZ4_compressHC2_limitedOutput_withStateHC (state, source, dest, inputSize, maxOutputSize, 0); }\n\n\n\n/**************************************\n * Streaming Functions\n * ************************************/\n/* allocation */\nLZ4_streamHC_t* LZ4_createStreamHC(void) { return (LZ4_streamHC_t*)malloc(sizeof(LZ4_streamHC_t)); }\nint LZ4_freeStreamHC (LZ4_streamHC_t* LZ4_streamHCPtr) { free(LZ4_streamHCPtr); return 0; }\n\n\n/* initialization */\nvoid LZ4_resetStreamHC (LZ4_streamHC_t* LZ4_streamHCPtr, int compressionLevel)\n{\n    LZ4_STATIC_ASSERT(sizeof(LZ4HC_Data_Structure) <= LZ4_STREAMHCSIZE);   /* if compilation fails here, LZ4_STREAMHCSIZE must be increased */\n    ((LZ4HC_Data_Structure*)LZ4_streamHCPtr)->base = NULL;\n    ((LZ4HC_Data_Structure*)LZ4_streamHCPtr)->compressionLevel = (unsigned)compressionLevel;\n}\n\nint LZ4_loadDictHC (LZ4_streamHC_t* LZ4_streamHCPtr, const char* dictionary, int dictSize)\n{\n    LZ4HC_Data_Structure* ctxPtr = (LZ4HC_Data_Structure*) LZ4_streamHCPtr;\n    if (dictSize > 64 KB)\n    {\n        dictionary += dictSize - 64 KB;\n        dictSize = 64 KB;\n    }\n    LZ4HC_init (ctxPtr, (const BYTE*)dictionary);\n    if (dictSize >= 4) LZ4HC_Insert (ctxPtr, (const BYTE*)dictionary +(dictSize-3));\n    ctxPtr->end = (const BYTE*)dictionary + dictSize;\n    return dictSize;\n}\n\n\n/* compression */\n\nstatic void LZ4HC_setExternalDict(LZ4HC_Data_Structure* ctxPtr, const BYTE* newBlock)\n{\n    if (ctxPtr->end >= ctxPtr->base + 4)\n        LZ4HC_Insert (ctxPtr, ctxPtr->end-3);   /* Referencing remaining dictionary content */\n    /* Only one memory segment for extDict, so any previous extDict is lost at this stage */\n    ctxPtr->lowLimit  = ctxPtr->dictLimit;\n    ctxPtr->dictLimit = (U32)(ctxPtr->end - ctxPtr->base);\n    ctxPtr->dictBase  = ctxPtr->base;\n    ctxPtr->base = newBlock - ctxPtr->dictLimit;\n    ctxPtr->end  = newBlock;\n    ctxPtr->nextToUpdate = ctxPtr->dictLimit;   /* match referencing will resume from there */\n}\n\nstatic int LZ4_compressHC_continue_generic (LZ4HC_Data_Structure* ctxPtr,\n                                            const char* source, char* dest,\n                                            int inputSize, int maxOutputSize, limitedOutput_directive limit)\n{\n    /* auto-init if forgotten */\n    if (ctxPtr->base == NULL)\n        LZ4HC_init (ctxPtr, (const BYTE*) source);\n\n    /* Check overflow */\n    if ((size_t)(ctxPtr->end - ctxPtr->base) > 2 GB)\n    {\n        size_t dictSize = (size_t)(ctxPtr->end - ctxPtr->base) - ctxPtr->dictLimit;\n        if (dictSize > 64 KB) dictSize = 64 KB;\n\n        LZ4_loadDictHC((LZ4_streamHC_t*)ctxPtr, (const char*)(ctxPtr->end) - dictSize, (int)dictSize);\n    }\n\n    /* Check if blocks follow each other */\n    if ((const BYTE*)source != ctxPtr->end) LZ4HC_setExternalDict(ctxPtr, (const BYTE*)source);\n\n    /* Check overlapping input/dictionary space */\n    {\n        const BYTE* sourceEnd = (const BYTE*) source + inputSize;\n        const BYTE* dictBegin = ctxPtr->dictBase + ctxPtr->lowLimit;\n        const BYTE* dictEnd   = ctxPtr->dictBase + ctxPtr->dictLimit;\n        if ((sourceEnd > dictBegin) && ((BYTE*)source < dictEnd))\n        {\n            if (sourceEnd > dictEnd) sourceEnd = dictEnd;\n            ctxPtr->lowLimit = (U32)(sourceEnd - ctxPtr->dictBase);\n            if (ctxPtr->dictLimit - ctxPtr->lowLimit < 4) ctxPtr->lowLimit = ctxPtr->dictLimit;\n        }\n    }\n\n    return LZ4HC_compress_generic (ctxPtr, source, dest, inputSize, maxOutputSize, ctxPtr->compressionLevel, limit);\n}\n\nint LZ4_compressHC_continue (LZ4_streamHC_t* LZ4_streamHCPtr, const char* source, char* dest, int inputSize)\n{\n    return LZ4_compressHC_continue_generic ((LZ4HC_Data_Structure*)LZ4_streamHCPtr, source, dest, inputSize, 0, noLimit);\n}\n\nint LZ4_compressHC_limitedOutput_continue (LZ4_streamHC_t* LZ4_streamHCPtr, const char* source, char* dest, int inputSize, int maxOutputSize)\n{\n    return LZ4_compressHC_continue_generic ((LZ4HC_Data_Structure*)LZ4_streamHCPtr, source, dest, inputSize, maxOutputSize, limitedOutput);\n}\n\n\n/* dictionary saving */\n\nint LZ4_saveDictHC (LZ4_streamHC_t* LZ4_streamHCPtr, char* safeBuffer, int dictSize)\n{\n    LZ4HC_Data_Structure* streamPtr = (LZ4HC_Data_Structure*)LZ4_streamHCPtr;\n    int prefixSize = (int)(streamPtr->end - (streamPtr->base + streamPtr->dictLimit));\n    if (dictSize > 64 KB) dictSize = 64 KB;\n    if (dictSize < 4) dictSize = 0;\n    if (dictSize > prefixSize) dictSize = prefixSize;\n    memcpy(safeBuffer, streamPtr->end - dictSize, dictSize);\n    {\n        U32 endIndex = (U32)(streamPtr->end - streamPtr->base);\n        streamPtr->end = (const BYTE*)safeBuffer + dictSize;\n        streamPtr->base = streamPtr->end - endIndex;\n        streamPtr->dictLimit = endIndex - dictSize;\n        streamPtr->lowLimit = endIndex - dictSize;\n        if (streamPtr->nextToUpdate < streamPtr->dictLimit) streamPtr->nextToUpdate = streamPtr->dictLimit;\n    }\n    return dictSize;\n}\n\n\n/***********************************\n * Deprecated Functions\n ***********************************/\nint LZ4_sizeofStreamStateHC(void) { return LZ4_STREAMHCSIZE; }\n\nint LZ4_resetStreamStateHC(void* state, const char* inputBuffer)\n{\n    if ((((size_t)state) & (sizeof(void*)-1)) != 0) return 1;   /* Error : pointer is not aligned for pointer (32 or 64 bits) */\n    LZ4HC_init((LZ4HC_Data_Structure*)state, (const BYTE*)inputBuffer);\n    return 0;\n}\n\nvoid* LZ4_createHC (const char* inputBuffer)\n{\n    void* hc4 = ALLOCATOR(1, sizeof(LZ4HC_Data_Structure));\n    LZ4HC_init ((LZ4HC_Data_Structure*)hc4, (const BYTE*)inputBuffer);\n    return hc4;\n}\n\nint LZ4_freeHC (void* LZ4HC_Data)\n{\n    FREEMEM(LZ4HC_Data);\n    return (0);\n}\n\n/*\nint LZ4_compressHC_continue (void* LZ4HC_Data, const char* source, char* dest, int inputSize)\n{\nreturn LZ4HC_compress_generic (LZ4HC_Data, source, dest, inputSize, 0, 0, noLimit);\n}\nint LZ4_compressHC_limitedOutput_continue (void* LZ4HC_Data, const char* source, char* dest, int inputSize, int maxOutputSize)\n{\nreturn LZ4HC_compress_generic (LZ4HC_Data, source, dest, inputSize, maxOutputSize, 0, limitedOutput);\n}\n*/\n\nint LZ4_compressHC2_continue (void* LZ4HC_Data, const char* source, char* dest, int inputSize, int compressionLevel)\n{\n    return LZ4HC_compress_generic (LZ4HC_Data, source, dest, inputSize, 0, compressionLevel, noLimit);\n}\n\nint LZ4_compressHC2_limitedOutput_continue (void* LZ4HC_Data, const char* source, char* dest, int inputSize, int maxOutputSize, int compressionLevel)\n{\n    return LZ4HC_compress_generic (LZ4HC_Data, source, dest, inputSize, maxOutputSize, compressionLevel, limitedOutput);\n}\n\nchar* LZ4_slideInputBufferHC(void* LZ4HC_Data)\n{\n    LZ4HC_Data_Structure* hc4 = (LZ4HC_Data_Structure*)LZ4HC_Data;\n    int dictSize = LZ4_saveDictHC((LZ4_streamHC_t*)LZ4HC_Data, (char*)(hc4->inputBuffer), 64 KB);\n    return (char*)(hc4->inputBuffer + dictSize);\n}\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/imgui_remote/lz4/lz4hc.h",
    "content": "/*\n   LZ4 HC - High Compression Mode of LZ4\n   Header File\n   Copyright (C) 2011-2014, Yann Collet.\n   BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)\n\n   Redistribution and use in source and binary forms, with or without\n   modification, are permitted provided that the following conditions are\n   met:\n\n       * Redistributions of source code must retain the above copyright\n   notice, this list of conditions and the following disclaimer.\n       * Redistributions in binary form must reproduce the above\n   copyright notice, this list of conditions and the following disclaimer\n   in the documentation and/or other materials provided with the\n   distribution.\n\n   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n   \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n   You can contact the author at :\n   - LZ4 homepage : http://fastcompression.blogspot.com/p/lz4.html\n   - LZ4 source repository : http://code.google.com/p/lz4/\n*/\n#pragma once\n\n\n#if defined (__cplusplus)\nextern \"C\" {\n#endif\n\n\nint LZ4_compressHC (const char* source, char* dest, int inputSize);\n/*\nLZ4_compressHC :\n    return : the number of bytes in compressed buffer dest\n             or 0 if compression fails.\n    note : destination buffer must be already allocated.\n        To avoid any problem, size it to handle worst cases situations (input data not compressible)\n        Worst case size evaluation is provided by function LZ4_compressBound() (see \"lz4.h\")\n*/\n\nint LZ4_compressHC_limitedOutput (const char* source, char* dest, int inputSize, int maxOutputSize);\n/*\nLZ4_compress_limitedOutput() :\n    Compress 'inputSize' bytes from 'source' into an output buffer 'dest' of maximum size 'maxOutputSize'.\n    If it cannot achieve it, compression will stop, and result of the function will be zero.\n    This function never writes outside of provided output buffer.\n\n    inputSize  : Max supported value is 1 GB\n    maxOutputSize : is maximum allowed size into the destination buffer (which must be already allocated)\n    return : the number of output bytes written in buffer 'dest'\n             or 0 if compression fails.\n*/\n\n\nint LZ4_compressHC2 (const char* source, char* dest, int inputSize, int compressionLevel);\nint LZ4_compressHC2_limitedOutput (const char* source, char* dest, int inputSize, int maxOutputSize, int compressionLevel);\n/*\n    Same functions as above, but with programmable 'compressionLevel'.\n    Recommended values are between 4 and 9, although any value between 0 and 16 will work.\n    'compressionLevel'==0 means use default 'compressionLevel' value.\n    Values above 16 behave the same as 16.\n    Equivalent variants exist for all other compression functions below.\n*/\n\n/* Note :\n   Decompression functions are provided within LZ4 source code (see \"lz4.h\") (BSD license)\n*/\n\n\n/**************************************\n   Using an external allocation\n**************************************/\nint LZ4_sizeofStateHC(void);\nint LZ4_compressHC_withStateHC               (void* state, const char* source, char* dest, int inputSize);\nint LZ4_compressHC_limitedOutput_withStateHC (void* state, const char* source, char* dest, int inputSize, int maxOutputSize);\n\nint LZ4_compressHC2_withStateHC              (void* state, const char* source, char* dest, int inputSize, int compressionLevel);\nint LZ4_compressHC2_limitedOutput_withStateHC(void* state, const char* source, char* dest, int inputSize, int maxOutputSize, int compressionLevel);\n\n/*\nThese functions are provided should you prefer to allocate memory for compression tables with your own allocation methods.\nTo know how much memory must be allocated for the compression tables, use :\nint LZ4_sizeofStateHC();\n\nNote that tables must be aligned for pointer (32 or 64 bits), otherwise compression will fail (return code 0).\n\nThe allocated memory can be provided to the compression functions using 'void* state' parameter.\nLZ4_compress_withStateHC() and LZ4_compress_limitedOutput_withStateHC() are equivalent to previously described functions.\nThey just use the externally allocated memory for state instead of allocating their own (on stack, or on heap).\n*/\n\n\n\n/**************************************\n   Experimental Streaming Functions\n**************************************/\n#define LZ4_STREAMHCSIZE_U64 32774\n#define LZ4_STREAMHCSIZE     (LZ4_STREAMHCSIZE_U64 * sizeof(unsigned long long))\ntypedef struct { unsigned long long table[LZ4_STREAMHCSIZE_U64]; } LZ4_streamHC_t;\n/*\nLZ4_streamHC_t\nThis structure allows static allocation of LZ4 HC streaming state.\nState must then be initialized using LZ4_resetStreamHC() before first use.\n\nStatic allocation should only be used with statically linked library.\nIf you want to use LZ4 as a DLL, please use construction functions below, which are more future-proof.\n*/\n\n\nLZ4_streamHC_t* LZ4_createStreamHC(void);\nint             LZ4_freeStreamHC (LZ4_streamHC_t* LZ4_streamHCPtr);\n/*\nThese functions create and release memory for LZ4 HC streaming state.\nNewly created states are already initialized.\nExisting state space can be re-used anytime using LZ4_resetStreamHC().\nIf you use LZ4 as a DLL, please use these functions instead of direct struct allocation,\nto avoid size mismatch between different versions.\n*/\n\nvoid LZ4_resetStreamHC (LZ4_streamHC_t* LZ4_streamHCPtr, int compressionLevel);\nint  LZ4_loadDictHC (LZ4_streamHC_t* LZ4_streamHCPtr, const char* dictionary, int dictSize);\n\nint LZ4_compressHC_continue (LZ4_streamHC_t* LZ4_streamHCPtr, const char* source, char* dest, int inputSize);\nint LZ4_compressHC_limitedOutput_continue (LZ4_streamHC_t* LZ4_streamHCPtr, const char* source, char* dest, int inputSize, int maxOutputSize);\n\nint LZ4_saveDictHC (LZ4_streamHC_t* LZ4_streamHCPtr, char* safeBuffer, int maxDictSize);\n\n/*\nThese functions compress data in successive blocks of any size, using previous blocks as dictionary.\nOne key assumption is that each previous block will remain read-accessible while compressing next block.\n\nBefore starting compression, state must be properly initialized, using LZ4_resetStreamHC().\nA first \"fictional block\" can then be designated as initial dictionary, using LZ4_loadDictHC() (Optional).\n\nThen, use LZ4_compressHC_continue() or LZ4_compressHC_limitedOutput_continue() to compress each successive block.\nThey work like usual LZ4_compressHC() or LZ4_compressHC_limitedOutput(), but use previous memory blocks to improve compression.\nPrevious memory blocks (including initial dictionary when present) must remain accessible and unmodified during compression.\n\nIf, for any reason, previous data block can't be preserved in memory during next compression block,\nyou must save it to a safer memory space,\nusing LZ4_saveDictHC().\n*/\n\n\n\n/**************************************\n * Deprecated Streaming Functions\n * ************************************/\n/* Note : these streaming functions follows the older model, and should no longer be used */\nvoid* LZ4_createHC (const char* inputBuffer);\nchar* LZ4_slideInputBufferHC (void* LZ4HC_Data);\nint   LZ4_freeHC (void* LZ4HC_Data);\n\nint   LZ4_compressHC2_continue (void* LZ4HC_Data, const char* source, char* dest, int inputSize, int compressionLevel);\nint   LZ4_compressHC2_limitedOutput_continue (void* LZ4HC_Data, const char* source, char* dest, int inputSize, int maxOutputSize, int compressionLevel);\n\nint   LZ4_sizeofStreamStateHC(void);\nint   LZ4_resetStreamStateHC(void* state, const char* inputBuffer);\n\n\n#if defined (__cplusplus)\n}\n#endif\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/imgui_remote/lz4/xxhash.c",
    "content": "/*\nxxHash - Fast Hash algorithm\nCopyright (C) 2012-2015, Yann Collet\n\nBSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n* Redistributions of source code must retain the above copyright\nnotice, this list of conditions and the following disclaimer.\n* Redistributions in binary form must reproduce the above\ncopyright notice, this list of conditions and the following disclaimer\nin the documentation and/or other materials provided with the\ndistribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(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\nYou can contact the author at :\n- xxHash source repository : http://code.google.com/p/xxhash/\n- xxHash source mirror : https://github.com/Cyan4973/xxHash\n- public discussion board : https://groups.google.com/forum/#!forum/lz4c\n*/\n\n\n/**************************************\n*  Tuning parameters\n***************************************/\n/* Unaligned memory access is automatically enabled for \"common\" CPU, such as x86.\n * For others CPU, the compiler will be more cautious, and insert extra code to ensure aligned access is respected.\n * If you know your target CPU supports unaligned memory access, you want to force this option manually to improve performance.\n * You can also enable this parameter if you know your input data will always be aligned (boundaries of 4, for U32).\n */\n#if defined(__ARM_FEATURE_UNALIGNED) || defined(__i386) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_X64)\n#  define XXH_USE_UNALIGNED_ACCESS 1\n#endif\n\n/* XXH_ACCEPT_NULL_INPUT_POINTER :\n * If the input pointer is a null pointer, xxHash default behavior is to trigger a memory access error, since it is a bad pointer.\n * When this option is enabled, xxHash output for null input pointers will be the same as a null-length input.\n * By default, this option is disabled. To enable it, uncomment below define :\n */\n/* #define XXH_ACCEPT_NULL_INPUT_POINTER 1 */\n\n/* XXH_FORCE_NATIVE_FORMAT :\n * By default, xxHash library provides endian-independant Hash values, based on little-endian convention.\n * Results are therefore identical for little-endian and big-endian CPU.\n * This comes at a performance cost for big-endian CPU, since some swapping is required to emulate little-endian format.\n * Should endian-independance be of no importance for your application, you may set the #define below to 1.\n * It will improve speed for Big-endian CPU.\n * This option has no impact on Little_Endian CPU.\n */\n#define XXH_FORCE_NATIVE_FORMAT 0\n\n\n/**************************************\n*  Compiler Specific Options\n***************************************/\n#ifdef _MSC_VER    /* Visual Studio */\n#  pragma warning(disable : 4127)      /* disable: C4127: conditional expression is constant */\n#  define FORCE_INLINE static __forceinline\n#else\n#  if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L   /* C99 */\n#    ifdef __GNUC__\n#      define FORCE_INLINE static inline __attribute__((always_inline))\n#    else\n#      define FORCE_INLINE static inline\n#    endif\n#  else\n#    define FORCE_INLINE static\n#  endif /* __STDC_VERSION__ */\n#endif\n\n\n/**************************************\n*  Includes & Memory related functions\n***************************************/\n#include \"xxhash.h\"\n/* Modify the local functions below should you wish to use some other memory routines */\n/* for malloc(), free() */\n#include <stdlib.h>\nstatic void* XXH_malloc(size_t s) { return malloc(s); }\nstatic void  XXH_free  (void* p)  { free(p); }\n/* for memcpy() */\n#include <string.h>\nstatic void* XXH_memcpy(void* dest, const void* src, size_t size)\n{\n    return memcpy(dest,src,size);\n}\n\n\n/**************************************\n*  Basic Types\n***************************************/\n#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L   /* C99 */\n# include <stdint.h>\ntypedef uint8_t  BYTE;\ntypedef uint16_t U16;\ntypedef uint32_t U32;\ntypedef  int32_t S32;\ntypedef uint64_t U64;\n#else\ntypedef unsigned char      BYTE;\ntypedef unsigned short     U16;\ntypedef unsigned int       U32;\ntypedef   signed int       S32;\ntypedef unsigned long long U64;\n#endif\n\n#if defined(__GNUC__)  && !defined(XXH_USE_UNALIGNED_ACCESS)\n#  define _PACKED __attribute__ ((packed))\n#else\n#  define _PACKED\n#endif\n\n#if !defined(XXH_USE_UNALIGNED_ACCESS) && !defined(__GNUC__)\n#  ifdef __IBMC__\n#    pragma pack(1)\n#  else\n#    pragma pack(push, 1)\n#  endif\n#endif\n\ntypedef struct _U32_S\n{\n    U32 v;\n} _PACKED U32_S;\ntypedef struct _U64_S\n{\n    U64 v;\n} _PACKED U64_S;\n\n#if !defined(XXH_USE_UNALIGNED_ACCESS) && !defined(__GNUC__)\n#  pragma pack(pop)\n#endif\n\n#define A32(x) (((U32_S *)(x))->v)\n#define A64(x) (((U64_S *)(x))->v)\n\n\n/*****************************************\n*  Compiler-specific Functions and Macros\n******************************************/\n#define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)\n\n/* Note : although _rotl exists for minGW (GCC under windows), performance seems poor */\n#if defined(_MSC_VER)\n#  define XXH_rotl32(x,r) _rotl(x,r)\n#  define XXH_rotl64(x,r) _rotl64(x,r)\n#else\n#  define XXH_rotl32(x,r) ((x << r) | (x >> (32 - r)))\n#  define XXH_rotl64(x,r) ((x << r) | (x >> (64 - r)))\n#endif\n\n#if defined(_MSC_VER)     /* Visual Studio */\n#  define XXH_swap32 _byteswap_ulong\n#  define XXH_swap64 _byteswap_uint64\n#elif GCC_VERSION >= 403\n#  define XXH_swap32 __builtin_bswap32\n#  define XXH_swap64 __builtin_bswap64\n#else\nstatic U32 XXH_swap32 (U32 x)\n{\n    return  ((x << 24) & 0xff000000 ) |\n            ((x <<  8) & 0x00ff0000 ) |\n            ((x >>  8) & 0x0000ff00 ) |\n            ((x >> 24) & 0x000000ff );\n}\nstatic U64 XXH_swap64 (U64 x)\n{\n    return  ((x << 56) & 0xff00000000000000ULL) |\n            ((x << 40) & 0x00ff000000000000ULL) |\n            ((x << 24) & 0x0000ff0000000000ULL) |\n            ((x << 8)  & 0x000000ff00000000ULL) |\n            ((x >> 8)  & 0x00000000ff000000ULL) |\n            ((x >> 24) & 0x0000000000ff0000ULL) |\n            ((x >> 40) & 0x000000000000ff00ULL) |\n            ((x >> 56) & 0x00000000000000ffULL);\n}\n#endif\n\n\n/**************************************\n*  Constants\n***************************************/\n#define PRIME32_1   2654435761U\n#define PRIME32_2   2246822519U\n#define PRIME32_3   3266489917U\n#define PRIME32_4    668265263U\n#define PRIME32_5    374761393U\n\n#define PRIME64_1 11400714785074694791ULL\n#define PRIME64_2 14029467366897019727ULL\n#define PRIME64_3  1609587929392839161ULL\n#define PRIME64_4  9650029242287828579ULL\n#define PRIME64_5  2870177450012600261ULL\n\n\n/***************************************\n*  Architecture Macros\n****************************************/\ntypedef enum { XXH_bigEndian=0, XXH_littleEndian=1 } XXH_endianess;\n#ifndef XXH_CPU_LITTLE_ENDIAN   /* XXH_CPU_LITTLE_ENDIAN can be defined externally, for example using a compiler switch */\nstatic const int one = 1;\n#   define XXH_CPU_LITTLE_ENDIAN   (*(char*)(&one))\n#endif\n\n\n/**************************************\n*  Macros\n***************************************/\n#define XXH_STATIC_ASSERT(c)   { enum { XXH_static_assert = 1/(!!(c)) }; }    /* use only *after* variable declarations */\n\n\n/****************************\n*  Memory reads\n*****************************/\ntypedef enum { XXH_aligned, XXH_unaligned } XXH_alignment;\n\nFORCE_INLINE U32 XXH_readLE32_align(const void* ptr, XXH_endianess endian, XXH_alignment align)\n{\n    if (align==XXH_unaligned)\n        return endian==XXH_littleEndian ? A32(ptr) : XXH_swap32(A32(ptr));\n    else\n        return endian==XXH_littleEndian ? *(U32*)ptr : XXH_swap32(*(U32*)ptr);\n}\n\nFORCE_INLINE U32 XXH_readLE32(const void* ptr, XXH_endianess endian)\n{\n    return XXH_readLE32_align(ptr, endian, XXH_unaligned);\n}\n\nFORCE_INLINE U64 XXH_readLE64_align(const void* ptr, XXH_endianess endian, XXH_alignment align)\n{\n    if (align==XXH_unaligned)\n        return endian==XXH_littleEndian ? A64(ptr) : XXH_swap64(A64(ptr));\n    else\n        return endian==XXH_littleEndian ? *(U64*)ptr : XXH_swap64(*(U64*)ptr);\n}\n\nFORCE_INLINE U64 XXH_readLE64(const void* ptr, XXH_endianess endian)\n{\n    return XXH_readLE64_align(ptr, endian, XXH_unaligned);\n}\n\n\n/****************************\n*  Simple Hash Functions\n*****************************/\nFORCE_INLINE U32 XXH32_endian_align(const void* input, size_t len, U32 seed, XXH_endianess endian, XXH_alignment align)\n{\n    const BYTE* p = (const BYTE*)input;\n    const BYTE* bEnd = p + len;\n    U32 h32;\n#define XXH_get32bits(p) XXH_readLE32_align(p, endian, align)\n\n#ifdef XXH_ACCEPT_NULL_INPUT_POINTER\n    if (p==NULL)\n    {\n        len=0;\n        bEnd=p=(const BYTE*)(size_t)16;\n    }\n#endif\n\n    if (len>=16)\n    {\n        const BYTE* const limit = bEnd - 16;\n        U32 v1 = seed + PRIME32_1 + PRIME32_2;\n        U32 v2 = seed + PRIME32_2;\n        U32 v3 = seed + 0;\n        U32 v4 = seed - PRIME32_1;\n\n        do\n        {\n            v1 += XXH_get32bits(p) * PRIME32_2;\n            v1 = XXH_rotl32(v1, 13);\n            v1 *= PRIME32_1;\n            p+=4;\n            v2 += XXH_get32bits(p) * PRIME32_2;\n            v2 = XXH_rotl32(v2, 13);\n            v2 *= PRIME32_1;\n            p+=4;\n            v3 += XXH_get32bits(p) * PRIME32_2;\n            v3 = XXH_rotl32(v3, 13);\n            v3 *= PRIME32_1;\n            p+=4;\n            v4 += XXH_get32bits(p) * PRIME32_2;\n            v4 = XXH_rotl32(v4, 13);\n            v4 *= PRIME32_1;\n            p+=4;\n        }\n        while (p<=limit);\n\n        h32 = XXH_rotl32(v1, 1) + XXH_rotl32(v2, 7) + XXH_rotl32(v3, 12) + XXH_rotl32(v4, 18);\n    }\n    else\n    {\n        h32  = seed + PRIME32_5;\n    }\n\n    h32 += (U32) len;\n\n    while (p+4<=bEnd)\n    {\n        h32 += XXH_get32bits(p) * PRIME32_3;\n        h32  = XXH_rotl32(h32, 17) * PRIME32_4 ;\n        p+=4;\n    }\n\n    while (p<bEnd)\n    {\n        h32 += (*p) * PRIME32_5;\n        h32 = XXH_rotl32(h32, 11) * PRIME32_1 ;\n        p++;\n    }\n\n    h32 ^= h32 >> 15;\n    h32 *= PRIME32_2;\n    h32 ^= h32 >> 13;\n    h32 *= PRIME32_3;\n    h32 ^= h32 >> 16;\n\n    return h32;\n}\n\n\nunsigned int XXH32 (const void* input, size_t len, unsigned seed)\n{\n#if 0\n    /* Simple version, good for code maintenance, but unfortunately slow for small inputs */\n    XXH32_state_t state;\n    XXH32_reset(&state, seed);\n    XXH32_update(&state, input, len);\n    return XXH32_digest(&state);\n#else\n    XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;\n\n#  if !defined(XXH_USE_UNALIGNED_ACCESS)\n    if ((((size_t)input) & 3) == 0)   /* Input is aligned, let's leverage the speed advantage */\n    {\n        if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)\n            return XXH32_endian_align(input, len, seed, XXH_littleEndian, XXH_aligned);\n        else\n            return XXH32_endian_align(input, len, seed, XXH_bigEndian, XXH_aligned);\n    }\n#  endif\n\n    if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)\n        return XXH32_endian_align(input, len, seed, XXH_littleEndian, XXH_unaligned);\n    else\n        return XXH32_endian_align(input, len, seed, XXH_bigEndian, XXH_unaligned);\n#endif\n}\n\nFORCE_INLINE U64 XXH64_endian_align(const void* input, size_t len, U64 seed, XXH_endianess endian, XXH_alignment align)\n{\n    const BYTE* p = (const BYTE*)input;\n    const BYTE* bEnd = p + len;\n    U64 h64;\n#define XXH_get64bits(p) XXH_readLE64_align(p, endian, align)\n\n#ifdef XXH_ACCEPT_NULL_INPUT_POINTER\n    if (p==NULL)\n    {\n        len=0;\n        bEnd=p=(const BYTE*)(size_t)32;\n    }\n#endif\n\n    if (len>=32)\n    {\n        const BYTE* const limit = bEnd - 32;\n        U64 v1 = seed + PRIME64_1 + PRIME64_2;\n        U64 v2 = seed + PRIME64_2;\n        U64 v3 = seed + 0;\n        U64 v4 = seed - PRIME64_1;\n\n        do\n        {\n            v1 += XXH_get64bits(p) * PRIME64_2;\n            p+=8;\n            v1 = XXH_rotl64(v1, 31);\n            v1 *= PRIME64_1;\n            v2 += XXH_get64bits(p) * PRIME64_2;\n            p+=8;\n            v2 = XXH_rotl64(v2, 31);\n            v2 *= PRIME64_1;\n            v3 += XXH_get64bits(p) * PRIME64_2;\n            p+=8;\n            v3 = XXH_rotl64(v3, 31);\n            v3 *= PRIME64_1;\n            v4 += XXH_get64bits(p) * PRIME64_2;\n            p+=8;\n            v4 = XXH_rotl64(v4, 31);\n            v4 *= PRIME64_1;\n        }\n        while (p<=limit);\n\n        h64 = XXH_rotl64(v1, 1) + XXH_rotl64(v2, 7) + XXH_rotl64(v3, 12) + XXH_rotl64(v4, 18);\n\n        v1 *= PRIME64_2;\n        v1 = XXH_rotl64(v1, 31);\n        v1 *= PRIME64_1;\n        h64 ^= v1;\n        h64 = h64 * PRIME64_1 + PRIME64_4;\n\n        v2 *= PRIME64_2;\n        v2 = XXH_rotl64(v2, 31);\n        v2 *= PRIME64_1;\n        h64 ^= v2;\n        h64 = h64 * PRIME64_1 + PRIME64_4;\n\n        v3 *= PRIME64_2;\n        v3 = XXH_rotl64(v3, 31);\n        v3 *= PRIME64_1;\n        h64 ^= v3;\n        h64 = h64 * PRIME64_1 + PRIME64_4;\n\n        v4 *= PRIME64_2;\n        v4 = XXH_rotl64(v4, 31);\n        v4 *= PRIME64_1;\n        h64 ^= v4;\n        h64 = h64 * PRIME64_1 + PRIME64_4;\n    }\n    else\n    {\n        h64  = seed + PRIME64_5;\n    }\n\n    h64 += (U64) len;\n\n    while (p+8<=bEnd)\n    {\n        U64 k1 = XXH_get64bits(p);\n        k1 *= PRIME64_2;\n        k1 = XXH_rotl64(k1,31);\n        k1 *= PRIME64_1;\n        h64 ^= k1;\n        h64 = XXH_rotl64(h64,27) * PRIME64_1 + PRIME64_4;\n        p+=8;\n    }\n\n    if (p+4<=bEnd)\n    {\n        h64 ^= (U64)(XXH_get32bits(p)) * PRIME64_1;\n        h64 = XXH_rotl64(h64, 23) * PRIME64_2 + PRIME64_3;\n        p+=4;\n    }\n\n    while (p<bEnd)\n    {\n        h64 ^= (*p) * PRIME64_5;\n        h64 = XXH_rotl64(h64, 11) * PRIME64_1;\n        p++;\n    }\n\n    h64 ^= h64 >> 33;\n    h64 *= PRIME64_2;\n    h64 ^= h64 >> 29;\n    h64 *= PRIME64_3;\n    h64 ^= h64 >> 32;\n\n    return h64;\n}\n\n\nunsigned long long XXH64 (const void* input, size_t len, unsigned long long seed)\n{\n#if 0\n    /* Simple version, good for code maintenance, but unfortunately slow for small inputs */\n    XXH64_state_t state;\n    XXH64_reset(&state, seed);\n    XXH64_update(&state, input, len);\n    return XXH64_digest(&state);\n#else\n    XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;\n\n#  if !defined(XXH_USE_UNALIGNED_ACCESS)\n    if ((((size_t)input) & 7)==0)   /* Input is aligned, let's leverage the speed advantage */\n    {\n        if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)\n            return XXH64_endian_align(input, len, seed, XXH_littleEndian, XXH_aligned);\n        else\n            return XXH64_endian_align(input, len, seed, XXH_bigEndian, XXH_aligned);\n    }\n#  endif\n\n    if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)\n        return XXH64_endian_align(input, len, seed, XXH_littleEndian, XXH_unaligned);\n    else\n        return XXH64_endian_align(input, len, seed, XXH_bigEndian, XXH_unaligned);\n#endif\n}\n\n/****************************************************\n *  Advanced Hash Functions\n****************************************************/\n\n/*** Allocation ***/\ntypedef struct\n{\n    U64 total_len;\n    U32 seed;\n    U32 v1;\n    U32 v2;\n    U32 v3;\n    U32 v4;\n    U32 mem32[4];   /* defined as U32 for alignment */\n    U32 memsize;\n} XXH_istate32_t;\n\ntypedef struct\n{\n    U64 total_len;\n    U64 seed;\n    U64 v1;\n    U64 v2;\n    U64 v3;\n    U64 v4;\n    U64 mem64[4];   /* defined as U64 for alignment */\n    U32 memsize;\n} XXH_istate64_t;\n\n\nXXH32_state_t* XXH32_createState(void)\n{\n    XXH_STATIC_ASSERT(sizeof(XXH32_state_t) >= sizeof(XXH_istate32_t));   /* A compilation error here means XXH32_state_t is not large enough */\n    return (XXH32_state_t*)XXH_malloc(sizeof(XXH32_state_t));\n}\nXXH_errorcode XXH32_freeState(XXH32_state_t* statePtr)\n{\n    XXH_free(statePtr);\n    return XXH_OK;\n}\n\nXXH64_state_t* XXH64_createState(void)\n{\n    XXH_STATIC_ASSERT(sizeof(XXH64_state_t) >= sizeof(XXH_istate64_t));   /* A compilation error here means XXH64_state_t is not large enough */\n    return (XXH64_state_t*)XXH_malloc(sizeof(XXH64_state_t));\n}\nXXH_errorcode XXH64_freeState(XXH64_state_t* statePtr)\n{\n    XXH_free(statePtr);\n    return XXH_OK;\n}\n\n\n/*** Hash feed ***/\n\nXXH_errorcode XXH32_reset(XXH32_state_t* state_in, U32 seed)\n{\n    XXH_istate32_t* state = (XXH_istate32_t*) state_in;\n    state->seed = seed;\n    state->v1 = seed + PRIME32_1 + PRIME32_2;\n    state->v2 = seed + PRIME32_2;\n    state->v3 = seed + 0;\n    state->v4 = seed - PRIME32_1;\n    state->total_len = 0;\n    state->memsize = 0;\n    return XXH_OK;\n}\n\nXXH_errorcode XXH64_reset(XXH64_state_t* state_in, unsigned long long seed)\n{\n    XXH_istate64_t* state = (XXH_istate64_t*) state_in;\n    state->seed = seed;\n    state->v1 = seed + PRIME64_1 + PRIME64_2;\n    state->v2 = seed + PRIME64_2;\n    state->v3 = seed + 0;\n    state->v4 = seed - PRIME64_1;\n    state->total_len = 0;\n    state->memsize = 0;\n    return XXH_OK;\n}\n\n\nFORCE_INLINE XXH_errorcode XXH32_update_endian (XXH32_state_t* state_in, const void* input, size_t len, XXH_endianess endian)\n{\n    XXH_istate32_t* state = (XXH_istate32_t *) state_in;\n    const BYTE* p = (const BYTE*)input;\n    const BYTE* const bEnd = p + len;\n\n#ifdef XXH_ACCEPT_NULL_INPUT_POINTER\n    if (input==NULL) return XXH_ERROR;\n#endif\n\n    state->total_len += len;\n\n    if (state->memsize + len < 16)   /* fill in tmp buffer */\n    {\n        XXH_memcpy((BYTE*)(state->mem32) + state->memsize, input, len);\n        state->memsize += (U32)len;\n        return XXH_OK;\n    }\n\n    if (state->memsize)   /* some data left from previous update */\n    {\n        XXH_memcpy((BYTE*)(state->mem32) + state->memsize, input, 16-state->memsize);\n        {\n            const U32* p32 = state->mem32;\n            state->v1 += XXH_readLE32(p32, endian) * PRIME32_2;\n            state->v1 = XXH_rotl32(state->v1, 13);\n            state->v1 *= PRIME32_1;\n            p32++;\n            state->v2 += XXH_readLE32(p32, endian) * PRIME32_2;\n            state->v2 = XXH_rotl32(state->v2, 13);\n            state->v2 *= PRIME32_1;\n            p32++;\n            state->v3 += XXH_readLE32(p32, endian) * PRIME32_2;\n            state->v3 = XXH_rotl32(state->v3, 13);\n            state->v3 *= PRIME32_1;\n            p32++;\n            state->v4 += XXH_readLE32(p32, endian) * PRIME32_2;\n            state->v4 = XXH_rotl32(state->v4, 13);\n            state->v4 *= PRIME32_1;\n            p32++;\n        }\n        p += 16-state->memsize;\n        state->memsize = 0;\n    }\n\n    if (p <= bEnd-16)\n    {\n        const BYTE* const limit = bEnd - 16;\n        U32 v1 = state->v1;\n        U32 v2 = state->v2;\n        U32 v3 = state->v3;\n        U32 v4 = state->v4;\n\n        do\n        {\n            v1 += XXH_readLE32(p, endian) * PRIME32_2;\n            v1 = XXH_rotl32(v1, 13);\n            v1 *= PRIME32_1;\n            p+=4;\n            v2 += XXH_readLE32(p, endian) * PRIME32_2;\n            v2 = XXH_rotl32(v2, 13);\n            v2 *= PRIME32_1;\n            p+=4;\n            v3 += XXH_readLE32(p, endian) * PRIME32_2;\n            v3 = XXH_rotl32(v3, 13);\n            v3 *= PRIME32_1;\n            p+=4;\n            v4 += XXH_readLE32(p, endian) * PRIME32_2;\n            v4 = XXH_rotl32(v4, 13);\n            v4 *= PRIME32_1;\n            p+=4;\n        }\n        while (p<=limit);\n\n        state->v1 = v1;\n        state->v2 = v2;\n        state->v3 = v3;\n        state->v4 = v4;\n    }\n\n    if (p < bEnd)\n    {\n        XXH_memcpy(state->mem32, p, bEnd-p);\n        state->memsize = (int)(bEnd-p);\n    }\n\n    return XXH_OK;\n}\n\nXXH_errorcode XXH32_update (XXH32_state_t* state_in, const void* input, size_t len)\n{\n    XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;\n\n    if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)\n        return XXH32_update_endian(state_in, input, len, XXH_littleEndian);\n    else\n        return XXH32_update_endian(state_in, input, len, XXH_bigEndian);\n}\n\n\n\nFORCE_INLINE U32 XXH32_digest_endian (const XXH32_state_t* state_in, XXH_endianess endian)\n{\n    XXH_istate32_t* state = (XXH_istate32_t*) state_in;\n    const BYTE * p = (const BYTE*)state->mem32;\n    BYTE* bEnd = (BYTE*)(state->mem32) + state->memsize;\n    U32 h32;\n\n    if (state->total_len >= 16)\n    {\n        h32 = XXH_rotl32(state->v1, 1) + XXH_rotl32(state->v2, 7) + XXH_rotl32(state->v3, 12) + XXH_rotl32(state->v4, 18);\n    }\n    else\n    {\n        h32  = state->seed + PRIME32_5;\n    }\n\n    h32 += (U32) state->total_len;\n\n    while (p+4<=bEnd)\n    {\n        h32 += XXH_readLE32(p, endian) * PRIME32_3;\n        h32  = XXH_rotl32(h32, 17) * PRIME32_4;\n        p+=4;\n    }\n\n    while (p<bEnd)\n    {\n        h32 += (*p) * PRIME32_5;\n        h32 = XXH_rotl32(h32, 11) * PRIME32_1;\n        p++;\n    }\n\n    h32 ^= h32 >> 15;\n    h32 *= PRIME32_2;\n    h32 ^= h32 >> 13;\n    h32 *= PRIME32_3;\n    h32 ^= h32 >> 16;\n\n    return h32;\n}\n\n\nU32 XXH32_digest (const XXH32_state_t* state_in)\n{\n    XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;\n\n    if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)\n        return XXH32_digest_endian(state_in, XXH_littleEndian);\n    else\n        return XXH32_digest_endian(state_in, XXH_bigEndian);\n}\n\n\nFORCE_INLINE XXH_errorcode XXH64_update_endian (XXH64_state_t* state_in, const void* input, size_t len, XXH_endianess endian)\n{\n    XXH_istate64_t * state = (XXH_istate64_t *) state_in;\n    const BYTE* p = (const BYTE*)input;\n    const BYTE* const bEnd = p + len;\n\n#ifdef XXH_ACCEPT_NULL_INPUT_POINTER\n    if (input==NULL) return XXH_ERROR;\n#endif\n\n    state->total_len += len;\n\n    if (state->memsize + len < 32)   /* fill in tmp buffer */\n    {\n        XXH_memcpy(((BYTE*)state->mem64) + state->memsize, input, len);\n        state->memsize += (U32)len;\n        return XXH_OK;\n    }\n\n    if (state->memsize)   /* some data left from previous update */\n    {\n        XXH_memcpy(((BYTE*)state->mem64) + state->memsize, input, 32-state->memsize);\n        {\n            const U64* p64 = state->mem64;\n            state->v1 += XXH_readLE64(p64, endian) * PRIME64_2;\n            state->v1 = XXH_rotl64(state->v1, 31);\n            state->v1 *= PRIME64_1;\n            p64++;\n            state->v2 += XXH_readLE64(p64, endian) * PRIME64_2;\n            state->v2 = XXH_rotl64(state->v2, 31);\n            state->v2 *= PRIME64_1;\n            p64++;\n            state->v3 += XXH_readLE64(p64, endian) * PRIME64_2;\n            state->v3 = XXH_rotl64(state->v3, 31);\n            state->v3 *= PRIME64_1;\n            p64++;\n            state->v4 += XXH_readLE64(p64, endian) * PRIME64_2;\n            state->v4 = XXH_rotl64(state->v4, 31);\n            state->v4 *= PRIME64_1;\n            p64++;\n        }\n        p += 32-state->memsize;\n        state->memsize = 0;\n    }\n\n    if (p+32 <= bEnd)\n    {\n        const BYTE* const limit = bEnd - 32;\n        U64 v1 = state->v1;\n        U64 v2 = state->v2;\n        U64 v3 = state->v3;\n        U64 v4 = state->v4;\n\n        do\n        {\n            v1 += XXH_readLE64(p, endian) * PRIME64_2;\n            v1 = XXH_rotl64(v1, 31);\n            v1 *= PRIME64_1;\n            p+=8;\n            v2 += XXH_readLE64(p, endian) * PRIME64_2;\n            v2 = XXH_rotl64(v2, 31);\n            v2 *= PRIME64_1;\n            p+=8;\n            v3 += XXH_readLE64(p, endian) * PRIME64_2;\n            v3 = XXH_rotl64(v3, 31);\n            v3 *= PRIME64_1;\n            p+=8;\n            v4 += XXH_readLE64(p, endian) * PRIME64_2;\n            v4 = XXH_rotl64(v4, 31);\n            v4 *= PRIME64_1;\n            p+=8;\n        }\n        while (p<=limit);\n\n        state->v1 = v1;\n        state->v2 = v2;\n        state->v3 = v3;\n        state->v4 = v4;\n    }\n\n    if (p < bEnd)\n    {\n        XXH_memcpy(state->mem64, p, bEnd-p);\n        state->memsize = (int)(bEnd-p);\n    }\n\n    return XXH_OK;\n}\n\nXXH_errorcode XXH64_update (XXH64_state_t* state_in, const void* input, size_t len)\n{\n    XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;\n\n    if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)\n        return XXH64_update_endian(state_in, input, len, XXH_littleEndian);\n    else\n        return XXH64_update_endian(state_in, input, len, XXH_bigEndian);\n}\n\n\n\nFORCE_INLINE U64 XXH64_digest_endian (const XXH64_state_t* state_in, XXH_endianess endian)\n{\n    XXH_istate64_t * state = (XXH_istate64_t *) state_in;\n    const BYTE * p = (const BYTE*)state->mem64;\n    BYTE* bEnd = (BYTE*)state->mem64 + state->memsize;\n    U64 h64;\n\n    if (state->total_len >= 32)\n    {\n        U64 v1 = state->v1;\n        U64 v2 = state->v2;\n        U64 v3 = state->v3;\n        U64 v4 = state->v4;\n\n        h64 = XXH_rotl64(v1, 1) + XXH_rotl64(v2, 7) + XXH_rotl64(v3, 12) + XXH_rotl64(v4, 18);\n\n        v1 *= PRIME64_2;\n        v1 = XXH_rotl64(v1, 31);\n        v1 *= PRIME64_1;\n        h64 ^= v1;\n        h64 = h64*PRIME64_1 + PRIME64_4;\n\n        v2 *= PRIME64_2;\n        v2 = XXH_rotl64(v2, 31);\n        v2 *= PRIME64_1;\n        h64 ^= v2;\n        h64 = h64*PRIME64_1 + PRIME64_4;\n\n        v3 *= PRIME64_2;\n        v3 = XXH_rotl64(v3, 31);\n        v3 *= PRIME64_1;\n        h64 ^= v3;\n        h64 = h64*PRIME64_1 + PRIME64_4;\n\n        v4 *= PRIME64_2;\n        v4 = XXH_rotl64(v4, 31);\n        v4 *= PRIME64_1;\n        h64 ^= v4;\n        h64 = h64*PRIME64_1 + PRIME64_4;\n    }\n    else\n    {\n        h64  = state->seed + PRIME64_5;\n    }\n\n    h64 += (U64) state->total_len;\n\n    while (p+8<=bEnd)\n    {\n        U64 k1 = XXH_readLE64(p, endian);\n        k1 *= PRIME64_2;\n        k1 = XXH_rotl64(k1,31);\n        k1 *= PRIME64_1;\n        h64 ^= k1;\n        h64 = XXH_rotl64(h64,27) * PRIME64_1 + PRIME64_4;\n        p+=8;\n    }\n\n    if (p+4<=bEnd)\n    {\n        h64 ^= (U64)(XXH_readLE32(p, endian)) * PRIME64_1;\n        h64 = XXH_rotl64(h64, 23) * PRIME64_2 + PRIME64_3;\n        p+=4;\n    }\n\n    while (p<bEnd)\n    {\n        h64 ^= (*p) * PRIME64_5;\n        h64 = XXH_rotl64(h64, 11) * PRIME64_1;\n        p++;\n    }\n\n    h64 ^= h64 >> 33;\n    h64 *= PRIME64_2;\n    h64 ^= h64 >> 29;\n    h64 *= PRIME64_3;\n    h64 ^= h64 >> 32;\n\n    return h64;\n}\n\n\nunsigned long long XXH64_digest (const XXH64_state_t* state_in)\n{\n    XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;\n\n    if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)\n        return XXH64_digest_endian(state_in, XXH_littleEndian);\n    else\n        return XXH64_digest_endian(state_in, XXH_bigEndian);\n}\n\n\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/imgui_remote/lz4/xxhash.h",
    "content": "/*\n   xxHash - Extremely Fast Hash algorithm\n   Header File\n   Copyright (C) 2012-2014, Yann Collet.\n   BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)\n\n   Redistribution and use in source and binary forms, with or without\n   modification, are permitted provided that the following conditions are\n   met:\n\n       * Redistributions of source code must retain the above copyright\n   notice, this list of conditions and the following disclaimer.\n       * Redistributions in binary form must reproduce the above\n   copyright notice, this list of conditions and the following disclaimer\n   in the documentation and/or other materials provided with the\n   distribution.\n\n   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n   \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n   You can contact the author at :\n   - xxHash source repository : http://code.google.com/p/xxhash/\n*/\n\n/* Notice extracted from xxHash homepage :\n\nxxHash is an extremely fast Hash algorithm, running at RAM speed limits.\nIt also successfully passes all tests from the SMHasher suite.\n\nComparison (single thread, Windows Seven 32 bits, using SMHasher on a Core 2 Duo @3GHz)\n\nName            Speed       Q.Score   Author\nxxHash          5.4 GB/s     10\nCrapWow         3.2 GB/s      2       Andrew\nMumurHash 3a    2.7 GB/s     10       Austin Appleby\nSpookyHash      2.0 GB/s     10       Bob Jenkins\nSBox            1.4 GB/s      9       Bret Mulvey\nLookup3         1.2 GB/s      9       Bob Jenkins\nSuperFastHash   1.2 GB/s      1       Paul Hsieh\nCityHash64      1.05 GB/s    10       Pike & Alakuijala\nFNV             0.55 GB/s     5       Fowler, Noll, Vo\nCRC32           0.43 GB/s     9\nMD5-32          0.33 GB/s    10       Ronald L. Rivest\nSHA1-32         0.28 GB/s    10\n\nQ.Score is a measure of quality of the hash function.\nIt depends on successfully passing SMHasher test set.\n10 is a perfect score.\n*/\n\n#pragma once\n\n#if defined (__cplusplus)\nextern \"C\" {\n#endif\n\n\n/*****************************\n   Includes\n*****************************/\n#include <stddef.h>   /* size_t */\n\n\n/*****************************\n   Type\n*****************************/\ntypedef enum { XXH_OK=0, XXH_ERROR } XXH_errorcode;\n\n\n\n/*****************************\n   Simple Hash Functions\n*****************************/\n\nunsigned int       XXH32 (const void* input, size_t length, unsigned seed);\nunsigned long long XXH64 (const void* input, size_t length, unsigned long long seed);\n\n/*\nXXH32() :\n    Calculate the 32-bits hash of sequence \"length\" bytes stored at memory address \"input\".\n    The memory between input & input+length must be valid (allocated and read-accessible).\n    \"seed\" can be used to alter the result predictably.\n    This function successfully passes all SMHasher tests.\n    Speed on Core 2 Duo @ 3 GHz (single thread, SMHasher benchmark) : 5.4 GB/s\nXXH64() :\n    Calculate the 64-bits hash of sequence of length \"len\" stored at memory address \"input\".\n*/\n\n\n\n/*****************************\n   Advanced Hash Functions\n*****************************/\ntypedef struct { long long ll[ 6]; } XXH32_state_t;\ntypedef struct { long long ll[11]; } XXH64_state_t;\n\n/*\nThese structures allow static allocation of XXH states.\nStates must then be initialized using XXHnn_reset() before first use.\n\nIf you prefer dynamic allocation, please refer to functions below.\n*/\n\nXXH32_state_t* XXH32_createState(void);\nXXH_errorcode  XXH32_freeState(XXH32_state_t* statePtr);\n\nXXH64_state_t* XXH64_createState(void);\nXXH_errorcode  XXH64_freeState(XXH64_state_t* statePtr);\n\n/*\nThese functions create and release memory for XXH state.\nStates must then be initialized using XXHnn_reset() before first use.\n*/\n\n\nXXH_errorcode XXH32_reset  (XXH32_state_t* statePtr, unsigned seed);\nXXH_errorcode XXH32_update (XXH32_state_t* statePtr, const void* input, size_t length);\nunsigned int  XXH32_digest (const XXH32_state_t* statePtr);\n\nXXH_errorcode      XXH64_reset  (XXH64_state_t* statePtr, unsigned long long seed);\nXXH_errorcode      XXH64_update (XXH64_state_t* statePtr, const void* input, size_t length);\nunsigned long long XXH64_digest (const XXH64_state_t* statePtr);\n\n/*\nThese functions calculate the xxHash of an input provided in multiple smaller packets,\nas opposed to an input provided as a single block.\n\nXXH state space must first be allocated, using either static or dynamic method provided above.\n\nStart a new hash by initializing state with a seed, using XXHnn_reset().\n\nThen, feed the hash state by calling XXHnn_update() as many times as necessary.\nObviously, input must be valid, meaning allocated and read accessible.\nThe function returns an error code, with 0 meaning OK, and any other value meaning there is an error.\n\nFinally, you can produce a hash anytime, by using XXHnn_digest().\nThis function returns the final nn-bits hash.\nYou can nonetheless continue feeding the hash state with more input,\nand therefore get some new hashes, by calling again XXHnn_digest().\n\nWhen you are done, don't forget to free XXH state space, using typically XXHnn_freeState().\n*/\n\n\n#if defined (__cplusplus)\n}\n#endif\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/imgui_remote/webby/LICENSE",
    "content": "Copyright (c) 2012, Andreas Fredriksson <dep at defmacro dot se>\nAll 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\n1. Redistributions of source code must retain the above copyright notice, this\n   list of conditions and the following disclaimer. \n2. Redistributions in binary form must reproduce the above copyright notice,\n   this list of conditions and the following disclaimer in the documentation\n   and/or other materials provided with the distribution. \n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/imgui_remote/webby/README.md",
    "content": "\n# Webby - A simple web server for game debugging #\n\nWebby is a web server intended for debugging tools inside a game or other\nprogram with a continously running main loop. It's intended to be used when\nall you need is something tiny and performance isn't a key concern.\n\n## Features ##\n\n- No dynamic memory allocations -- server memory is completely fixed\n- No threading, all I/O and serving happens on the calling thread\n- Supports socket keep-alives\n- Supports the 100-Continue scheme for file uploading\n- Basic support for WebSockets is available.\n\nBecause request/response I/O is synchronous on the calling thread, performance\nwill suffer when you are serving data. For the use-cases Webby is intended for,\nthis is fine. You can still run Webby in a background thread at your\ndiscretion if this is a problem.\n\n## Usage ##\n\n- Fill in a `WebbyServerConfig` structure\n- Compute the memory requirements by calling `WebbyServerMemoryNeeded()`\n- Allocate memory (or just use a static char array..)\n- Initialize the server by calling `WebbyServerInit()`\n- Every game frame, call `WebbyServerUpdate()`\n  - Handle requests in your dispatch function\n- When it's time to shut down, call `WebbyServerShutdown()`\n\n## WebSocket Usage ##\n\n- Provide the `WEBBY_SERVER_WEBSOCKETS` flag at init time\n- In your `ws_connect` handler, decide to allow the upgrade request.\n- When the connection is established, your `ws_connected` handler is called. At this point, you can start sending WebSocket frames over the connection (and you can get incoming frames as well).\n- As frames come in, your `ws_frame` handler will be called. Webby doesn't try to merge frames together when the data is split into fragments, so you can be getting one binary/text frame followed by any number of continuation frames. It's up to your handler to make sense of the data and build a buffer as appropriate. The rationale is that otherwise Webby would need a lot more buffer space. To read the frame data, look at the payload size and then call `WebbyRead` to get at the data. Be careful to not read more than what is stated, or you will screw up the protocol.\n- To send WebSocket data, call `WebbyBeginSocketFrame`, passing in the type of frame (typically `WEBBY_WS_OP_TEXT_FRAME` or `WEBBY_WS_OP_BINARY_FRAME`). Then write an arbitrary amount of data using `WebbyWrite`. When you're done, call `WebbyEndSocketFrame`. Webby currently emits one WebSocket (continuation) frame for each `WebbyWrite` call (again, to reduce buffering overhead), so try to write big chunks if you can.\n- When a connection is closed, you will get a call to your `ws_closed` handler.\n\n## Request handling ##\n\nWhen you configure the server, you give it a function pointer to your\ndispatcher. The dispatcher is called by Webby when a request has been fully\nread into memory and is ready for processing. The socket the request came in on\nhas then been switched to blocking mode, and you're free to read any request\ndata using `WebbyRead()` (if present, check `content_length`) and then write\nyour response.\n\nThere are two ways to generate a response; explicit size or chunked.\n\n### When you know the size of the data ###\n\nWhen you know in advance how big the response is going to be, you should pass\nthat size in bytes to `WebbyBeginResponse()` (it will be sent as the\nContent-Length header). You then call `WebbyWrite()` to push that data out, and\nfinally `WebbyEndResponse()` to finalize the response and prepare the socket\nfor a new request.\n\n### When the response size is dynamic ###\n\nSometimes you want to generate an arbitrary amount of text in the response, and\nyou don't know how much that will be. Rather than buffering everything in RAM,\nyou can use chunked encoding. First call `WebbyBeginResponse()` as normal, but\npass it -1 for the content length. This triggers sending the\n`Transfer-Encoding: chunked` header. You then call `WebbyWrite()` or\n`WebbyPrintf()` as desired until the response is complete. When you're done,\ncall `WebbyEndResponse()` to finish up.\n\n## Limitations ##\n\n- There is not much error checking. \n\n## Author ##\n\nWebby was written by Andreas Fredriksson (@deplinenoise on Twitter).\n\n## License ##\n\nWebby is available under the BSD license. See the file `LICENSE`.\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/imgui_remote/webby/webby.c",
    "content": "#define _CRT_SECURE_NO_WARNINGS 1\n#define _WINSOCK_DEPRECATED_NO_WARNINGS 1\n#include \"webby.h\"\n\n/* Copyright (c) 2012, Andreas Fredriksson < dep at defmacro dot se > */\n\n#include <string.h>\n#include <assert.h>\n#include <stdlib.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <ctype.h>\n\n#if defined(__PS3__)\n#include \"webby_ps3.h\"\n#elif defined(__XBOX__)\n#include \"webby_xbox.h\"\n#elif defined(_WIN32)\n#include \"webby_win32.h\"\n#else\n#include \"webby_unix.h\"\n#endif\n\n#define WB_WEBSOCKET_VERSION \"13\"\n#define WB_ALIGN_ARB(x, a) (((x) + ((a)-1)) & ~((a)-1))\n#define WB_ARRAY_SIZE(a) (sizeof(a)/sizeof((a)[0]))\n\nstatic const char continue_header[] = \"HTTP/1.1 100 Continue\\r\\n\\r\\n\";\nstatic const size_t continue_header_len = sizeof(continue_header) - 1;\n\nstatic const char websocket_guid[] = \"258EAFA5-E914-47DA-95CA-C5AB0DC85B11\";\nstatic const size_t websocket_guid_len = sizeof(websocket_guid) - 1;\n\nstatic const unsigned char websocket_pong[] = { 0x80, WEBBY_WS_OP_PONG, 0x00 };\n\nstatic const struct WebbyHeader plain_text_headers[] =\n{\n  { \"Content-Type\", \"text/plain\" },\n};\n\n#ifdef _MSC_VER\n/* MSVC keeps complaining about constant conditionals inside the FD_SET() macro. */\n#pragma warning(disable: 4127)\n#endif\n\nstruct WebbyConnection;\nstruct WebbyRequest;\n\nenum\n{\n  WB_ALIVE                  = 1 << 0,\n  WB_FRESH_CONNECTION       = 1 << 1,\n  WB_CLOSE_AFTER_RESPONSE   = 1 << 2,\n  WB_CHUNKED_RESPONSE       = 1 << 3,\n  WB_WEBSOCKET              = 1 << 4\n};\n\nenum\n{\n  WBC_REQUEST,\n  WBC_SEND_CONTINUE,\n  WBC_SERVE,\n  WBC_WEBSOCKET\n};\n\nstruct WebbyBuffer\n{\n  int used;\n  int max;\n  unsigned char* data;\n};\n\nstruct WebbyConnectionPrv\n{\n  struct WebbyConnection    public_data;\n\n  unsigned short            flags;\n  unsigned short            state;    /* WBC_xxx */\n  webby_socket_t            socket;\n\n  struct WebbyBuffer        header_buf;\n  struct WebbyBuffer        io_buf;\n  int                       header_body_left;\n  int                       io_data_left;\n  int                       continue_data_left;\n  int                       body_bytes_read;\n  struct WebbyServer*       server;\n  struct WebbyWsFrame       ws_frame;\n  unsigned char             ws_opcode;\n  int                       blocking_count; /* number of times blocking has been requested */\n};\n\nstruct WebbyServer\n{\n  struct WebbyServerConfig  config;\n  size_t                    memory_size;\n  webby_socket_t            socket;\n  int                       connection_count;\n  struct WebbyConnectionPrv connections[1];\n};\n\nstatic void dbg(struct WebbyServer *srv, const char *fmt, ...)\n{\n  char buffer[1024];\n  va_list args;\n\n  if (srv->config.flags & WEBBY_SERVER_LOG_DEBUG)\n  {\n    va_start(args, fmt);\n    vsnprintf(buffer, sizeof buffer, fmt, args);\n    va_end(args);\n\n    buffer[(sizeof buffer)-1] = '\\0';\n    (*srv->config.log)(buffer);\n  }\n}\n\nstatic int make_connection_blocking(struct WebbyConnectionPrv *conn)\n{\n  if (0 == conn->blocking_count)\n  {\n    if (0 != wb_set_blocking(conn->socket, 1))\n    {\n      dbg(conn->server, \"failed to switch connection to blocking\");\n      conn->flags &= ~WB_ALIVE;\n      return -1;\n    }\n  }\n\n  ++conn->blocking_count;\n  return 0;\n}\n\nstatic int make_connection_nonblocking(struct WebbyConnectionPrv *conn)\n{\n  int count = conn->blocking_count;\n\n  if (1 == count)\n  {\n    if (0 != wb_set_blocking(conn->socket, 0))\n    {\n      dbg(conn->server, \"failed to switch connection to non-blocking\");\n      conn->flags &= ~WB_ALIVE;\n      return -1;\n    }\n  }\n\n  conn->blocking_count = count - 1;\n\n  return 0;\n}\n\n/* URL-decode input buffer into destination buffer.\n * 0-terminate the destination buffer. Return the length of decoded data.\n * form-url-encoded data differs from URI encoding in a way that it\n * uses '+' as character for space, see RFC 1866 section 8.2.1\n * http://ftp.ics.uci.edu/pub/ietf/html/rfc1866.txt\n *\n * This bit of code was taken from mongoose.\n */\nstatic size_t url_decode(const char *src, size_t src_len, char *dst, size_t dst_len, int is_form_url_encoded)\n{\n  size_t i, j;\n  int a, b;\n#define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')\n\n  for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {\n    if (src[i] == '%' &&\n      isxdigit(* (const unsigned char *) (src + i + 1)) &&\n      isxdigit(* (const unsigned char *) (src + i + 2))) {\n        a = tolower(* (const unsigned char *) (src + i + 1));\n        b = tolower(* (const unsigned char *) (src + i + 2));\n        dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b));\n        i += 2;\n    } else if (is_form_url_encoded && src[i] == '+') {\n      dst[j] = ' ';\n    } else {\n      dst[j] = src[i];\n    }\n  }\n\n#undef HEXTOI\n\n  dst[j] = '\\0'; /* Null-terminate the destination */\n\n  return j;\n}\n\n/* Pulled from mongoose */\nint WebbyFindQueryVar(const char *buf, const char *name, char *dst, size_t dst_len)\n{\n  const char *p, *e, *s;\n  size_t name_len;\n  int len;\n  size_t buf_len = strlen(buf);\n\n  name_len = strlen(name);\n  e = buf + buf_len;\n  len = -1;\n  dst[0] = '\\0';\n\n  // buf is \"var1=val1&var2=val2...\". Find variable first\n  for (p = buf; p != NULL && p + name_len < e; p++)\n  {\n    if ((p == buf || p[-1] == '&') && p[name_len] == '=' && 0 == strncasecmp(name, p, name_len))\n    {\n      // Point p to variable value\n      p += name_len + 1;\n\n      // Point s to the end of the value\n      s = (const char *) memchr(p, '&', (size_t)(e - p));\n      if (s == NULL) {\n        s = e;\n      }\n      assert(s >= p);\n\n      // Decode variable into destination buffer\n      if ((size_t) (s - p) < dst_len)\n      {\n        len = (int) url_decode(p, (size_t)(s - p), dst, dst_len, 1);\n      }\n      break;\n    }\n  }\n\n  return len;\n}\n\nenum\n{\n  BASE64_QUADS_BEFORE_LINEBREAK = 19\n};\n\nstatic size_t base64_bufsize(size_t input_size)\n{\n  size_t triplets = (input_size + 2) / 3;\n  size_t base_size = 4 * triplets;\n  size_t line_breaks = 2 * (triplets / BASE64_QUADS_BEFORE_LINEBREAK);\n  size_t null_termination = 1;\n  return base_size + line_breaks + null_termination;\n}\n\nstatic int base64_encode(char* output, size_t output_size, const unsigned char *input, size_t input_size)\n{\n  static const char enc[] = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\"; \n  size_t i = 0;\n  int line_out = 0;\n\n  if (output_size < base64_bufsize(input_size))\n    return 1;\n\n  while (i < input_size)\n  {\n    unsigned int idx_0, idx_1, idx_2, idx_3;\n    unsigned int i0;\n\n    i0 = (input[i]) << 16; i++;\n    i0 |= (i < input_size ? input[i] : 0) << 8; i++;\n    i0 |= (i < input_size ? input[i] : 0); i++;\n\n    idx_0 = (i0 & 0xfc0000) >> 18; i0 <<= 6;\n    idx_1 = (i0 & 0xfc0000) >> 18; i0 <<= 6;\n    idx_2 = (i0 & 0xfc0000) >> 18; i0 <<= 6;\n    idx_3 = (i0 & 0xfc0000) >> 18;\n\n    if (i - 1 > input_size)\n      idx_2 = 64;\n    if (i > input_size)\n      idx_3 = 64;\n\n    *output++ = enc[idx_0];\n    *output++ = enc[idx_1];\n    *output++ = enc[idx_2];\n    *output++ = enc[idx_3];\n\n    if (++line_out == BASE64_QUADS_BEFORE_LINEBREAK) {\n      *output++ = '\\r';\n      *output++ = '\\n';\n    }\n  }\n\n  *output = '\\0';\n  return 0;\n}\n\nstatic unsigned int sha1_rol(unsigned int value, unsigned int bits)\n{\n  return ((value) << bits) | (value >> (32 - bits));\n}\n\nstruct sha1 {\n  unsigned int state[5];\n  unsigned int msg_size[2];\n  size_t buf_used;\n  unsigned char buffer[64];\n};\n\nstatic void sha1_hash_block(unsigned int state[5], const unsigned char *block)\n{\n  int i;\n  unsigned int a, b, c, d, e;\n  unsigned int w[80];\n\n  /* Prepare message schedule */\n  for (i = 0; i < 16; ++i)\n    w[i] =\n      (((unsigned int)block[(i*4)+0]) << 24) |\n      (((unsigned int)block[(i*4)+1]) << 16) |\n      (((unsigned int)block[(i*4)+2]) <<  8) |\n      (((unsigned int)block[(i*4)+3]) <<  0);\n\n  for (i = 16; i < 80; ++i)\n    w[i] = sha1_rol(w[i-3] ^ w[i-8] ^ w[i-14] ^ w[i-16], 1);\n\n  /* Initialize working variables */\n  a = state[0]; b = state[1]; c = state[2]; d = state[3]; e = state[4];\n\n  /* This is the core loop for each 20-word span. */\n#define SHA1_LOOP(start, end, func, constant) \\\n  for (i = (start); i < (end); ++i) \\\n  { \\\n    unsigned int t = sha1_rol(a, 5) + (func) + e + (constant) + w[i]; \\\n    e = d; d = c; c = sha1_rol(b, 30); b = a; a = t; \\\n  }\n\n  SHA1_LOOP( 0, 20, ((b & c) ^ (~b & d)),           0x5a827999)\n  SHA1_LOOP(20, 40, (b ^ c ^ d),                    0x6ed9eba1)\n  SHA1_LOOP(40, 60, ((b & c) ^ (b & d) ^ (c & d)),  0x8f1bbcdc)\n  SHA1_LOOP(60, 80, (b ^ c ^ d),                    0xca62c1d6)\n\n#undef SHA1_LOOP\n\n  /* Update state */\n  state[0] += a; state[1] += b; state[2] += c; state[3] += d; state[4] += e;\n}\n\nstatic void sha1_init(struct sha1 *s)\n{\n  s->state[0] = 0x67452301;\n  s->state[1] = 0xefcdab89;\n  s->state[2] = 0x98badcfe;\n  s->state[3] = 0x10325476;\n  s->state[4] = 0xc3d2e1f0;\n  s->msg_size[0] = 0;\n  s->msg_size[1] = 0;\n  s->buf_used = 0;\n}\n\nstatic void sha1_update(struct sha1 *s, const void *data_, size_t size)\n{\n  const char *data = (const char*) data_;\n  unsigned int size_lo;\n  unsigned int size_lo_orig;\n  size_t remain = size;\n\n  while (remain > 0)\n  {\n    size_t buf_space = (sizeof s->buffer) - s->buf_used;\n    size_t copy_size = remain < buf_space ? remain : buf_space;\n    memcpy(s->buffer + s->buf_used, data, copy_size);\n    s->buf_used += copy_size;\n    data += copy_size;\n    remain -= copy_size;\n\n    if (s->buf_used == sizeof s->buffer)\n    {\n      sha1_hash_block(s->state, s->buffer);\n      s->buf_used = 0;\n    }\n  }\n\n  size_lo = size_lo_orig = s->msg_size[1];\n  size_lo += (unsigned int) (size * 8);\n  \n  if (size_lo < size_lo_orig)\n    s->msg_size[0] += 1;\n\n  s->msg_size[1] = size_lo;\n}\n\nstatic void sha1_final(unsigned char digest[20], struct sha1 *s)\n{\n  unsigned char zero = 0x00;\n  unsigned char one_bit = 0x80;\n  unsigned char count_data[8];\n  int i;\n\n  /* Generate size data in bit endian format */\n  for (i = 0; i < 8; ++i)\n  {\n    unsigned int word = s->msg_size[i >> 2];\n    count_data[i] = (unsigned char) (word >> ((3 - (i & 3)) * 8));\n  }\n\n  /* Set trailing one-bit */\n  sha1_update(s, &one_bit, 1);\n\n  /* Emit null padding to to make room for 64 bits of size info in the last 512 bit block */\n  while (s->buf_used != 56)\n    sha1_update(s, &zero, 1);\n\n  /* Write size in bits as last 64-bits */\n  sha1_update(s, count_data, 8);\n\n  /* Make sure we actually finalized our last block */\n  assert(0 == s->buf_used);\n\n  /* Generate digest */\n  for (i = 0; i < 20; ++i)\n  {\n    unsigned int word = s->state[i >> 2];\n    unsigned char byte = (unsigned char) ((word >> ((3 - (i & 3)) * 8)) & 0xff);\n    digest[i] = byte;\n  }\n}\n\nstatic int discard_incoming_data(struct WebbyConnection* conn, int count)\n{\n  while (count > 0)\n  {\n    char buffer[1024];\n    int read_size = count > (int) sizeof buffer ? (int) sizeof buffer : count;\n    if (0 != WebbyRead(conn, buffer, (size_t) read_size))\n      return -1;\n\n    count -= read_size;\n  }\n\n  return 0;\n}\n\nconst char *WebbyFindHeader(struct WebbyConnection *conn, const char *name)\n{\n  int i, count;\n  for (i = 0, count = conn->request.header_count; i < count; ++i)\n  {\n    if (0 == strcasecmp(conn->request.headers[i].name, name))\n    {\n      return conn->request.headers[i].value;\n    }\n  }\n\n  return NULL;\n}\n\n\nint\nWebbyServerMemoryNeeded(const struct WebbyServerConfig *config)\n{\n  return\n    WB_ALIGN_ARB(sizeof(struct WebbyServer), 16) +\n    WB_ALIGN_ARB((config->connection_max - 1) * sizeof(struct WebbyConnectionPrv), 16) +\n    config->connection_max * config->request_buffer_size +\n    config->connection_max * config->io_buffer_size;\n}\n\nstruct WebbyServer*\nWebbyServerInit(struct WebbyServerConfig *config, void *memory, size_t memory_size)\n{\n  int i;\n  struct WebbyServer *server = (struct WebbyServer*) memory;\n  unsigned char *buffer = (unsigned char*) memory;\n\n  memset(buffer, 0, memory_size);\n\n  server->config = *config;\n  server->memory_size = memory_size;\n  server->socket = WB_INVALID_SOCKET;\n\n  buffer +=\n    WB_ALIGN_ARB(sizeof(struct WebbyServer), 16) +\n    WB_ALIGN_ARB((config->connection_max - 1) * sizeof(struct WebbyConnectionPrv), 16);\n\n  for (i = 0; i < config->connection_max; ++i)\n  {\n    server->connections[i].server = server;\n\n    server->connections[i].header_buf.data = buffer;\n    buffer += config->request_buffer_size;\n\n    server->connections[i].io_buf.data = buffer;\n    buffer += config->io_buffer_size;\n  }\n\n  assert((size_t)(buffer - (unsigned char*) memory) <= memory_size);\n\n  server->socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);\n\n  dbg(server, \"Server socket = %d\", (int) server->socket);\n\n  if (!wb_valid_socket(server->socket))\n  {\n    dbg(server, \"failed to initialized server socket: %d\", wb_socket_error());\n    goto error;\n  }\n\n  {\n    int on = 1;\n    int off = 0;\n    setsockopt(server->socket, SOL_SOCKET, SO_REUSEADDR, (const char*) &on, sizeof(int));\n    setsockopt(server->socket, SOL_SOCKET, SO_LINGER, (const char*) &off, sizeof(int));\n  }\n\n#ifdef __APPLE__\n  /* Don't generate SIGPIPE when writing to dead socket, we check all writes. */\n  signal(SIGPIPE, SIG_IGN);\n#endif\n\n  if (0 != wb_set_blocking(server->socket, 0))\n  {\n    goto error;\n  }\n\n  {\n    struct sockaddr_in bind_addr;\n\n    dbg(server, \"binding to %s:%d\", config->bind_address, config->listening_port);\n\n    memset(&bind_addr, 0, sizeof bind_addr); // use 0.0.0.0\n    bind_addr.sin_family = AF_INET;\n    bind_addr.sin_addr.s_addr = inet_addr(config->bind_address);\n    bind_addr.sin_port = htons((unsigned short) config->listening_port);\n\n    if (0 != bind(server->socket, (struct sockaddr*) &bind_addr, sizeof bind_addr))\n    {\n      dbg(server, \"bind() failed: %d\", wb_socket_error());\n      goto error;\n    }\n  }\n\n  if (0 != listen(server->socket, SOMAXCONN))\n  {\n    dbg(server, \"listen() failed: %d\", wb_socket_error());\n    wb_close_socket(server->socket);\n    goto error;\n  }\n\n  dbg(server, \"server initialized\");\n  return server;\n\nerror:\n  if (wb_valid_socket(server->socket))\n  {\n    wb_close_socket(server->socket);\n  }\n  return NULL;\n}\n\nvoid WebbyServerShutdown(struct WebbyServer *srv)\n{\n  int i;\n  wb_close_socket(srv->socket);\n\n  for (i = 0; i < srv->connection_count; ++i)\n  {\n    wb_close_socket(srv->connections[i].socket);\n  }\n\n  memset(srv, 0, srv->memory_size);\n}\n\nstatic int wb_config_incoming_socket(webby_socket_t socket)\n{\n  int err;\n\n  if (0 != (err = wb_set_blocking(socket, 0)))\n  {\n    return err;\n  }\n\n  {\n    int off = 0;\n    setsockopt(socket, SOL_SOCKET, SO_LINGER, (const char*) &off, sizeof(int));\n  }\n\n  return 0;\n}\n\nstatic void reset_connection(struct WebbyServer *srv, struct WebbyConnectionPrv *conn)\n{\n  conn->header_buf.used       = 0;\n  conn->header_buf.max        = srv->config.request_buffer_size;\n  conn->io_buf.used           = 0;\n  conn->io_buf.max            = srv->config.io_buffer_size;\n  conn->header_body_left      = 0;\n  conn->io_data_left          = 0;\n  conn->continue_data_left    = 0;\n  conn->body_bytes_read       = 0;\n  conn->state                 = WBC_REQUEST;\n  conn->public_data.user_data = NULL;\n  conn->blocking_count        = 0;\n}\n\nstatic int wb_on_incoming(struct WebbyServer *srv)\n{\n  int connection_index;\n  char WB_ALIGN(8) client_addr[64];\n  struct WebbyConnectionPrv* connection;\n  webby_socklen_t client_addr_len = sizeof client_addr;\n  webby_socket_t fd;\n\n  /* Make sure we have space for a new connection */\n  connection_index = srv->connection_count;\n\n  if (connection_index == srv->config.connection_max)\n  {\n    dbg(srv, \"out of connection slots\");\n    return 1;\n  }\n\n  /* Accept the incoming connection. */\n  fd = accept(srv->socket, (struct sockaddr*) &client_addr[0], &client_addr_len);\n\n  if (!wb_valid_socket(fd))\n  {\n    int err = wb_socket_error();\n    if (!wb_is_blocking_error(err))\n      dbg(srv, \"accept() failed: %d\", err);\n    return 1;\n  }\n\n  connection = &srv->connections[connection_index];\n\n  reset_connection(srv, connection);\n\n  connection->flags       = WB_FRESH_CONNECTION;\n\n  srv->connection_count = connection_index + 1;\n\n  /* Configure socket */\n  if (0 != wb_config_incoming_socket(fd))\n  {\n    wb_close_socket(fd);\n    return 1;\n  }\n\n  /* OK, keep this connection */\n  dbg(srv, \"tagging connection %d as alive\", connection_index);\n  connection->flags |= WB_ALIVE;\n  connection->socket = fd;\n  return 0;\n}\n\nstatic int wb_peek_request_size(const unsigned char *buf, int len)\n{\n  int i;\n  int max = len - 3;\n\n  for (i = 0; i < max; ++i)\n  {\n    if ('\\r' != buf[i]) \n      continue;\n\n    if ('\\n' != buf[i + 1])\n      continue;\n\n    if ('\\r' != buf[i + 2])\n      continue;\n\n    if ('\\n' != buf[i + 3])\n      continue;\n\n    /* OK; we have CRLFCRLF which indicates the end of the header section */\n    return i + 4;\n  }\n\n  return -1;\n}\n\nstatic char* skipws(char *p)\n{\n  for (;;)\n  {\n    char ch = *p;\n    if (' ' == ch || '\\t' == ch)\n      ++p;\n    else\n      break;\n  }\n\n  return p;\n}\n\nenum\n{\n  WB_TOK_SKIPWS = 1 << 0\n};\n\nstatic int tok_inplace(char *buf, const char* separator, char *tokens[], int max, int flags)\n{\n  int token_count = 0;\n  char *b = buf;\n  char *e = buf;\n  int separator_len = (int) strlen(separator);\n\n  while (token_count < max)\n  {\n    if (flags & WB_TOK_SKIPWS)\n    {\n      b = skipws(b);\n    }\n\n    if (NULL != (e = strstr(b, separator)))\n    {\n      int len = (int) (e - b);\n      if (len > 0)\n      {\n        tokens[token_count++] = b;\n      }\n      *e = '\\0';\n      b = e + separator_len;\n    }\n    else\n    {\n      tokens[token_count++] = b;\n      break;\n    }\n  }\n\n  return token_count;\n}\n\nstatic void wb_close_client(struct WebbyServer *srv, struct WebbyConnectionPrv* connection)\n{\n  (void) srv;\n\n  if (connection->socket != WB_INVALID_SOCKET)\n  {\n    wb_close_socket(connection->socket);\n    connection->socket = WB_INVALID_SOCKET;\n  }\n\n  connection->flags = 0;\n}\n\nstatic int send_fully(webby_socket_t socket, const unsigned char *buffer, int size)\n{\n  while (size > 0)\n  {\n    int err = send(socket, (const char*) buffer, size, 0);\n\n    if (err <= 0)\n      return 1;\n\n    buffer += err;\n    size -= err;\n  }\n\n  return 0;\n}\n\n\nstatic int wb_setup_request(struct WebbyServer *srv, struct WebbyConnectionPrv *connection, int request_size)\n{\n  char* lines[WEBBY_MAX_HEADERS + 2];\n  int line_count;\n  char* tok[16];\n  char* query_params;\n  int tok_count;\n\n  int i;\n  int header_count;\n\n  char *buf = (char*) connection->header_buf.data;\n  struct WebbyRequest *req = &connection->public_data.request;\n\n  /* Null-terminate the request envelope by overwriting the last CRLF with 00LF */\n  buf[request_size - 2] = '\\0';\n\n  /* Split header into lines */\n  line_count = tok_inplace(buf, \"\\r\\n\", lines, WB_ARRAY_SIZE(lines), 0);\n\n  header_count = line_count - 2;\n\n  if (line_count < 1 || header_count > (int) WB_ARRAY_SIZE(req->headers))\n    return 1;\n\n  /* Parse request line */\n  tok_count = tok_inplace(lines[0], \" \", tok, WB_ARRAY_SIZE(tok), 0);\n\n  if (3 != tok_count)\n    return 1;\n\n  req->method = tok[0];\n  req->uri = tok[1];\n  req->http_version = tok[2];\n  req->content_length = 0;\n\n  /* See if there are any query parameters */\n  if (NULL != (query_params = (char*) strchr(req->uri, '?')))\n  {\n    req->query_params = query_params + 1;\n    *query_params = '\\0';\n  }\n  else\n    req->query_params = NULL;\n  \n  /* Decode the URI in place */\n  {\n    size_t uri_len = strlen(req->uri);\n    url_decode(req->uri, uri_len, (char*) req->uri, uri_len + 1, /* url encoded: */ 1);\n  }\n\n  /* Parse headers */\n  for (i = 0; i < header_count; ++i)\n  {\n    tok_count = tok_inplace(lines[i + 1], \":\", tok, 2, WB_TOK_SKIPWS);\n\n    if (tok_count != 2)\n    {\n      return 1;\n    }\n\n    req->headers[i].name = tok[0];\n    req->headers[i].value = tok[1];\n\n    if (0 == strcasecmp(\"content-length\", tok[0]))\n    {\n      req->content_length = strtoul(tok[1], NULL, 10);\n      dbg(srv, \"request has body; content length is %d\", req->content_length);\n    }\n    else if (0 == strcasecmp(\"transfer-encoding\", tok[0]))\n    {\n      dbg(srv, \"cowardly refusing to handle Transfer-Encoding: %s\", tok[1]);\n      return 1;\n    }\n  }\n\n  req->header_count = header_count;\n\n  return 0;\n}\n\nenum\n{\n  WB_FILL_OK,\n  WB_FILL_ERROR,\n  WB_FILL_FULL\n};\n\n/* Read as much as possible without blocking while there is buffer space. */\nstatic int wb_fill_buffer(struct WebbyServer *srv, struct WebbyBuffer *buf, webby_socket_t socket)\n{\n  int err;\n  int buf_left;\n\n  for (;;)\n  {\n    buf_left = buf->max - buf->used;\n\n    dbg(srv, \"buffer space left = %d\", buf_left);\n\n    if (0 == buf_left)\n    {\n      return WB_FILL_FULL;\n    }\n\n    /* Read what we can into the current buffer space. */\n    err = recv(socket, (char*) buf->data + buf->used, buf_left, 0);\n\n    if (err < 0)\n    {\n      int sock_err = wb_socket_error();\n\n      if (wb_is_blocking_error(sock_err))\n      {\n        return WB_FILL_OK;\n      }\n      else\n      {\n        /* Read error. Give up. */\n        dbg(srv, \"read error %d - connection dead\", sock_err);\n        return WB_FILL_ERROR;\n      }\n    }\n    else if (err == 0)\n    {\n      /* The peer has closed the connection. */\n      dbg(srv, \"peer has closed the connection\");\n      return WB_FILL_ERROR;\n    }\n    else\n    {\n      buf->used += err;\n    }\n  }\n}\n\nstatic int is_websocket_request(struct WebbyConnection* conn)\n{\n  const char *hdr;\n\n  if (NULL == (hdr = WebbyFindHeader(conn, \"Connection\")))\n    return 0;\n\n  //Firefox sends: \"keep-alive, Upgrade\"\n  if (0 == strstr(hdr, \"Upgrade\"))\n    return 0;\n\n  if (NULL == (hdr = WebbyFindHeader(conn, \"Upgrade\")))\n    return 0;\n\n  if (0 != strcasecmp(hdr, \"websocket\"))\n    return 0;\n\n  return 1;\n}\n\nstatic int send_websocket_upgrade(struct WebbyServer *srv, struct WebbyConnectionPrv* connection)\n{\n  const char *hdr;\n  struct sha1 sha;\n  unsigned char digest[20];\n  char output_digest[64];\n  struct WebbyHeader headers[3];\n  struct WebbyConnection *conn = &connection->public_data;\n\n  if (0 == (srv->config.flags & WEBBY_SERVER_WEBSOCKETS))\n  {\n    dbg(srv, \"websockets not enabled in server config\");\n    return 1;\n  }\n\n  if (NULL == (hdr = WebbyFindHeader(conn, \"Sec-WebSocket-Version\")))\n  {\n    dbg(srv, \"Sec-WebSocket-Version header not present\");\n    return 1;\n  }\n\n  if (0 != strcmp(hdr, WB_WEBSOCKET_VERSION))\n  {\n    dbg(srv, \"WebSocket version %s not supported (we only do %s)\", hdr, WB_WEBSOCKET_VERSION);\n    return 1;\n  }\n\n  if (NULL == (hdr = WebbyFindHeader(conn, \"Sec-WebSocket-Key\")))\n  {\n    dbg(srv, \"Sec-WebSocket-Key header not present\");\n    return 1;\n  }\n\n  /* Compute SHA1 hash of Sec-Websocket-Key + the websocket guid as required by\n   * the RFC.\n   *\n   * This handshake is bullshit. It adds zero security. Just forces me to drag\n   * in SHA1 and create a base64 encoder.\n   */\n  sha1_init(&sha);\n  sha1_update(&sha, hdr, (int) strlen(hdr));\n  sha1_update(&sha, websocket_guid, websocket_guid_len);\n  sha1_final(&digest[0], &sha);\n\n  if (0 != base64_encode(output_digest, sizeof output_digest, &digest[0], sizeof digest))\n    return 1;\n\n  headers[0].name  = \"Upgrade\";\n  headers[0].value = \"websocket\";\n  headers[1].name  = \"Connection\";\n  headers[1].value = \"Upgrade\";\n  headers[2].name  = \"Sec-WebSocket-Accept\";\n  headers[2].value = output_digest;\n\n  WebbyBeginResponse(&connection->public_data, 101, 0, headers, WB_ARRAY_SIZE(headers));\n  WebbyEndResponse(&connection->public_data);\n  return 0;\n}\n\nstatic int scan_websocket_frame(const struct WebbyBuffer *buf, struct WebbyWsFrame *frame)\n{\n  unsigned char flags = 0;\n  unsigned int len = 0;\n  unsigned int opcode = 0;\n  unsigned char* data = buf->data;\n  unsigned char* data_max = data + buf->used;\n  int i;\n  int len_bytes = 0;\n  int mask_bytes = 0;\n  unsigned char header0, header1;\n\n  if (buf->used < 2)\n    return -1;\n\n  header0 = *data++;\n  header1 = *data++;\n\n  if (header0 & 0x80)\n  {\n    flags |= WEBBY_WSF_FIN;\n  }\n\n  if (header1 & 0x80)\n  {\n    flags |= WEBBY_WSF_MASKED;\n    mask_bytes = 4;\n  }\n\n  opcode = header0 & 0xf;\n  len = header1 & 0x7f;\n\n  if (len == 126)\n    len_bytes = 2;\n  else if (len == 127)\n    len_bytes = 8;\n\n  if (data + len_bytes + mask_bytes > data_max)\n    return -1;\n\n  /* Read big endian length from length bytes (if greater than 125) */\n  len = len_bytes == 0 ? len : 0;\n  for (i = 0; i < len_bytes; ++i)\n  {\n    /* This will totally overflow for 64-bit values. I don't care.\n     * If you're transmitting more than 4 GB of data using Webby,\n     * seek help. */\n    len <<= 8;\n    len |= *data++;\n  }\n\n  /* Read mask word if present */\n  for (i = 0; i < mask_bytes; ++i)\n  {\n    frame->mask_key[i] = *data++;\n  }\n\n  frame->header_size = (unsigned char) (data - buf->data);\n  frame->flags = flags;\n  frame->opcode = (unsigned char) opcode;\n  frame->payload_length = (int) len;\n  return 0;\n}\n\nstatic void wb_update_client(struct WebbyServer *srv, struct WebbyConnectionPrv* connection)\n{\n   unsigned char* bufferBackup = connection->io_buf.data;\n  /* This is no longer a fresh connection. Only read from it when select() says\n   * so in the future. */\n  connection->flags &= ~WB_FRESH_CONNECTION;\n\n  for (;;)\n  {\n    switch (connection->state)\n    {\n      case WBC_REQUEST: {\n        const char *expect_header;\n        int result = wb_fill_buffer(srv, &connection->header_buf, connection->socket);\n        int request_size;\n\n        if (WB_FILL_ERROR == result)\n        {\n          connection->flags &= ~WB_ALIVE;\n          return;\n        }\n\n        /* Scan to see if the buffer has a complete HTTP request header package. */ \n        request_size = wb_peek_request_size(connection->header_buf.data, connection->header_buf.used);\n\n        dbg(srv, \"peek request size: %d\", request_size);\n        if (request_size < 0)\n        {\n          /* Nothing yet. */\n          if (connection->header_buf.max == connection->header_buf.used)\n          {\n            dbg(srv, \"giving up as buffer is full\");\n            /* Give up, we can't fit the request in our buffer. */\n            connection->flags &= ~WB_ALIVE;\n          }\n          return;\n        }\n\n        /* Set up request data. */\n        if (0 != wb_setup_request(srv, connection, request_size))\n        {\n          dbg(srv, \"failed to set up request\");\n          connection->flags &= ~WB_ALIVE;\n          return;\n        }\n\n        /* Remember how much of the remaining buffer is body data. */\n        connection->header_body_left = connection->header_buf.used - request_size;\n\n        /* If the client expects a 100 Continue, send one now. */\n        if (NULL != (expect_header = WebbyFindHeader(&connection->public_data, \"Expect\")))\n        {\n          if (0 == strcasecmp(expect_header, \"100-continue\"))\n          {\n            dbg(srv, \"connection expects a 100 Continue header.. making him happy\");\n            connection->continue_data_left = (int) continue_header_len;\n            connection->state = WBC_SEND_CONTINUE;\n          }\n          else\n          {\n            dbg(srv, \"unrecognized Expected header %s\", expect_header);\n            connection->state = WBC_SERVE;\n          }\n        }\n        else\n        {\n          connection->state = WBC_SERVE;\n        }\n\n        break;\n      }\n\n      case WBC_SEND_CONTINUE: {\n        int left = connection->continue_data_left;\n        int written = 0;\n\n        written = send(connection->socket, continue_header + continue_header_len - left, left, 0);\n\n        dbg(srv, \"continue write: %d bytes\", written);\n        \n        if (written < 0)\n        {\n          dbg(srv, \"failed to write 100-continue header\");\n          connection->flags &= ~WB_ALIVE;\n          return;\n        }\n\n        left -= written;\n        connection->continue_data_left = left;\n\n        if (0 == left)\n        {\n          connection->state = WBC_SERVE;\n        }\n\n        break;\n      }\n\n      case WBC_SERVE: {\n        /* Clear I/O buffer for output */\n        connection->io_buf.used = 0;\n\n        /* Switch socket to blocking mode. */\n        if (0 != make_connection_blocking(connection))\n          return;\n\n        /* Figure out if this is a request to upgrade to WebSockets */\n        if (is_websocket_request(&connection->public_data))\n        {\n          dbg(srv, \"received a websocket upgrade request\");\n\n          if (!srv->config.ws_connect || 0 != (*srv->config.ws_connect)(&connection->public_data))\n          {\n            dbg(srv, \"user callback failed connection attempt\");\n            WebbyBeginResponse(&connection->public_data, 400, -1, plain_text_headers, WB_ARRAY_SIZE(plain_text_headers));\n            WebbyPrintf(&connection->public_data, \"WebSockets not supported at %s\\r\\n\", connection->public_data.request.uri);\n            WebbyEndResponse(&connection->public_data);\n          }\n          else\n          {\n            /* OK, let's try to upgrade the connection to WebSockets */\n            if (0 != send_websocket_upgrade(srv, connection))\n            {\n              dbg(srv, \"websocket upgrade failed\");\n              WebbyBeginResponse(&connection->public_data, 400, -1, plain_text_headers, WB_ARRAY_SIZE(plain_text_headers));\n              WebbyPrintf(&connection->public_data, \"WebSockets couldn't not be enabled\\r\\n\");\n              WebbyEndResponse(&connection->public_data);\n            }\n            else\n            {\n              /* OK, we're now a websocket */\n              connection->flags |= WB_WEBSOCKET;\n              dbg(srv, \"connection %d upgraded to websocket\", (int) (connection - srv->connections));\n\n              (*srv->config.ws_connected)(&connection->public_data);\n            }\n          }\n        }\n        else if (0 != (*srv->config.dispatch)(&connection->public_data))\n        {\n          static const struct WebbyHeader headers[] =\n          {\n            { \"Content-Type\", \"text/plain\" },\n          };\n          WebbyBeginResponse(&connection->public_data, 404, -1, headers, WB_ARRAY_SIZE(headers));\n          WebbyPrintf(&connection->public_data, \"No handler for %s\\r\\n\", connection->public_data.request.uri);\n          WebbyEndResponse(&connection->public_data);\n        }\n\n        /* Back to non-blocking mode, can make the socket die. */\n        make_connection_nonblocking(connection);\n\n        /* Ready for another request, unless we should close the connection. */\n        if (connection->flags & WB_ALIVE)\n        {\n          if (connection->flags & WB_CLOSE_AFTER_RESPONSE)\n          {\n            connection->flags &= ~WB_ALIVE;\n            return;\n          }\n          else\n          {\n            /* Reset connection for next request. */\n            reset_connection(srv, connection);\n\n            if (0 == (connection->flags & WB_WEBSOCKET))\n            {\n              /* Loop back to request state */\n              connection->state = WBC_REQUEST;\n            }\n            else\n            {\n              /* Clear I/O buffer for input */\n              connection->io_buf.used = 0;\n              /* Go to the web socket serving state */\n              connection->state = WBC_WEBSOCKET;\n            }\n          }\n        }\n\n        break;\n      }\n\n      case WBC_WEBSOCKET: {\n\n        /* In this state, we're trying to read a websocket frame into the I/O\n         * buffer. Once we have enough data, we call the websocket frame\n         * callback and let the client read the data through WebbyRead.\n         */ \n\n        if (WB_FILL_ERROR == wb_fill_buffer(srv, &connection->io_buf, connection->socket))\n        {\n          /* Give up on this connection */\n          connection->flags &= ~WB_ALIVE;\n          return;\n        }\n\n        if (0 != scan_websocket_frame(&connection->io_buf, &connection->ws_frame))\n        {\n          /* Nothing yet */\n          return;\n        }\n\nparseWebsocketFrame:\n        connection->body_bytes_read = 0;\n        connection->io_data_left = connection->io_buf.used - connection->ws_frame.header_size;\n        dbg(srv, \"%d bytes of incoming websocket data buffered\", (int) connection->io_data_left);\n\n        /* Switch socket to blocking mode */\n        if (0 != make_connection_blocking(connection))\n          return;\n\n        switch (connection->ws_frame.opcode)\n        {\n          case WEBBY_WS_OP_CLOSE:\n            dbg(srv, \"received websocket close request\");\n            connection->flags &= ~WB_ALIVE;\n            return;\n\n          case WEBBY_WS_OP_PING:\n            dbg(srv, \"received websocket ping request\");\n            if (0 != send_fully(connection->socket, websocket_pong, sizeof websocket_pong))\n            {\n              connection->flags &= ~WB_ALIVE;\n              return;\n            }\n            break;\n\n          default:\n            /* Dispatch frame to user handler. */\n            if (0 != (*srv->config.ws_frame)(&connection->public_data, &connection->ws_frame))\n            {\n              connection->flags &= ~WB_ALIVE;\n              return;\n            }\n        }\n\n        /* Discard any data the client didn't read to retain the socket state. */\n        if (connection->body_bytes_read < connection->ws_frame.payload_length)\n        {\n          int size = connection->ws_frame.payload_length - connection->body_bytes_read;\n          if (0 != discard_incoming_data(&connection->public_data, size))\n          {\n            connection->flags &= ~WB_ALIVE;\n            return;\n          }\n        }\n        /* Back to non-blocking mode */\n        if (0 != make_connection_nonblocking(connection))\n          return;\n\n        if(connection->io_data_left > 0)\n        {\n            int dataToSkip  = connection->ws_frame.header_size + connection->ws_frame.payload_length;\n        \n            connection->io_buf.data += dataToSkip;\n            connection->io_buf.used -= dataToSkip;\n            connection->io_buf.max  -= dataToSkip;\n            connection->io_data_left-= dataToSkip;\n            if (0 != scan_websocket_frame(&connection->io_buf, &connection->ws_frame))\n            {\n                goto parseWebsocketFrame;\n            }\n        }\n\n        reset_connection(srv, connection);\n        connection->io_buf.data = bufferBackup;\n        connection->state = WBC_WEBSOCKET;\n\n        break;\n      }\n    }\n  }\n}\n\nvoid\nWebbyServerUpdate(struct WebbyServer *srv)\n{\n  int i, count, err;\n  webby_socket_t max_socket;\n  fd_set read_fds, write_fds, except_fds;\n  struct timeval timeout;\n\n  /* Build set of sockets to check for events */\n  FD_ZERO(&read_fds);\n  FD_ZERO(&write_fds);\n  FD_ZERO(&except_fds);\n\n  max_socket = 0;\n\n  /* Only accept incoming connections if we have space */\n  if (srv->connection_count < srv->config.connection_max)\n  {\n    FD_SET(srv->socket, &read_fds);\n    FD_SET(srv->socket, &except_fds);\n    max_socket = srv->socket;\n  }\n\n  for (i = 0, count = srv->connection_count; i < count; ++i)\n  {\n    webby_socket_t socket = srv->connections[i].socket;\n    FD_SET(socket, &read_fds);\n    FD_SET(socket, &except_fds);\n\n    if (srv->connections[i].state == WBC_SEND_CONTINUE)\n      FD_SET(socket, &write_fds);\n\n    if (socket > max_socket)\n    {\n      max_socket = socket;\n    }\n  }\n\n  timeout.tv_sec = 0;\n  timeout.tv_usec = 5;\n\n  err = select((int) (max_socket + 1), &read_fds, &write_fds, &except_fds, &timeout);\n\n  /* Handle incoming connections */\n  if (FD_ISSET(srv->socket, &read_fds))\n  {\n    do\n    {\n      dbg(srv, \"awake on incoming\");\n      err = wb_on_incoming(srv);\n    } while (0 == err);\n  }\n\n  /* Handle incoming connection data */\n  for (i = 0, count = srv->connection_count; i < count; ++i)\n  {\n    struct WebbyConnectionPrv *conn = &srv->connections[i];\n\n    if (FD_ISSET(conn->socket, &read_fds) || FD_ISSET(conn->socket, &write_fds) || conn->flags & WB_FRESH_CONNECTION)\n    {\n      dbg(srv, \"reading from connection %d\", i);\n      wb_update_client(srv, conn);\n    }\n  }\n\n  /* Close stale connections & compact connection array. */\n  for (i = 0; i < srv->connection_count; )\n  {\n    struct WebbyConnectionPrv *connection = &srv->connections[i];\n    if (0 == (connection->flags & WB_ALIVE))\n    {\n      int remain;\n      dbg(srv, \"closing connection %d (%08x)\", i, connection->flags);\n\n      if (connection->flags & WB_WEBSOCKET)\n      {\n        (*srv->config.ws_closed)(&connection->public_data);\n      }\n\n      remain = srv->connection_count - i - 1;\n      wb_close_client(srv, connection);\n      memmove(&srv->connections[i], &srv->connections[i + 1], remain*sizeof(srv->connections[i]));\n      --srv->connection_count;\n    }\n    else\n    {\n      ++i;\n    }\n  }\n}\n\nstatic int wb_flush(struct WebbyBuffer *buf, webby_socket_t socket)\n{\n  if (buf->used > 0)\n  {\n    if (0 != send_fully(socket, buf->data, buf->used))\n      return 1;\n  }\n  buf->used = 0;\n  return 0;\n}\n\nstatic int wb_push(struct WebbyServer *srv, struct WebbyConnectionPrv *conn, const void *data_, int len)\n{\n  struct WebbyBuffer *buf = &conn->io_buf;\n  const unsigned char* data = (const unsigned char*) data_;\n\n  if (conn->state != WBC_SERVE)\n  {\n    dbg(srv, \"attempt to write in non-serve state\");\n    return 1;\n  }\n\n  if (0 == len)\n  {\n    return wb_flush(buf, conn->socket);\n  }\n\n  while (len > 0)\n  {\n    int buf_space = buf->max - buf->used;\n    int copy_size = len < buf_space ? len : buf_space;\n    memcpy(buf->data + buf->used, data, copy_size);\n    buf->used += copy_size;\n\n    data += copy_size;\n    len -= copy_size;\n\n    if (buf->used == buf->max)\n    {\n      if (0 != wb_flush(buf, conn->socket))\n        return 1;\n\n      if (len >= buf->max)\n      {\n        return send_fully(conn->socket, data, len);\n      }\n    }\n  }\n\n  return 0;\n}\n\nint WebbyPrintf(struct WebbyConnection* conn, const char* fmt, ...)\n{\n  int len;\n  char buffer[1024];\n  va_list args;\n\n  va_start(args, fmt);\n  len = vsnprintf(buffer, sizeof buffer, fmt, args);\n  va_end(args);\n\n  return WebbyWrite(conn, buffer, len);\n}\n\nstatic const short status_nums[] = {\n   100, 101, 200, 201, 202, 203, 204, 205, 206, 300, 301, 302, 303, 304, 305,\n   307, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413,\n   414, 415, 416, 417, 500, 501, 502, 503, 504, 505\n};\n\nstatic const char* status_text[] = {\n  \"Continue\", \"Switching Protocols\", \"OK\", \"Created\", \"Accepted\",\n  \"Non-Authoritative Information\", \"No Content\", \"Reset Content\",\n  \"Partial Content\", \"Multiple Choices\", \"Moved Permanently\", \"Found\",\n  \"See Other\", \"Not Modified\", \"Use Proxy\", \"Temporary Redirect\", \"Bad Request\",\n  \"Unauthorized\", \"Payment Required\", \"Forbidden\", \"Not Found\", \"Method Not Allowed\",\n  \"Not Acceptable\", \"Proxy Authentication Required\", \"Request Time-out\", \"Conflict\",\n  \"Gone\", \"Length Required\", \"Precondition Failed\", \"Request Entity Too Large\",\n  \"Request-URI Too Large\", \"Unsupported Media Type\", \"Requested range not satisfiable\",\n  \"Expectation Failed\", \"Internal Server Error\", \"Not Implemented\", \"Bad Gateway\",\n  \"Service Unavailable\", \"Gateway Time-out\", \"HTTP Version not supported\"\n};\n\nstatic const char *wb_status_text(int status_code)\n{\n  int i;\n  for (i = 0; i < (int) WB_ARRAY_SIZE(status_nums); ++i)\n  {\n    if (status_nums[i] == status_code)\n      return status_text[i];\n  }\n  return \"Unknown\";\n}\n\nint WebbyBeginResponse(\n    struct WebbyConnection *conn_pub,\n    int status_code,\n    int content_length,\n    const struct WebbyHeader headers[],\n    int header_count)\n{\n  int i = 0;\n  struct WebbyConnectionPrv *conn = (struct WebbyConnectionPrv *) conn_pub;\n\n  if (conn->body_bytes_read < conn->public_data.request.content_length)\n  {\n    int body_left = conn->public_data.request.content_length - conn->body_bytes_read;\n    if (0 != discard_incoming_data(conn_pub, body_left))\n    {\n      conn->flags &= ~WB_ALIVE;\n      return -1;\n    }\n  }\n\n  WebbyPrintf(conn_pub, \"HTTP/1.1 %d %s\\r\\n\", status_code, wb_status_text(status_code));\n\n  if (content_length >= 0)\n  {\n    WebbyPrintf(conn_pub, \"Content-Length: %d\\r\\n\", content_length);\n  }\n  else\n  {\n    WebbyPrintf(conn_pub, \"Transfer-Encoding: chunked\\r\\n\");\n  }\n\n  WebbyPrintf(conn_pub, \"Server: Webby\\r\\n\");\n\n  for (i = 0; i < header_count; ++i)\n  {\n    if (0 == strcasecmp(headers[i].name, \"Connection\"))\n    {\n      if (0 == strcasecmp(headers[i].value, \"close\"))\n      {\n        conn->flags |= WB_CLOSE_AFTER_RESPONSE;\n      }\n    }\n    WebbyPrintf(conn_pub, \"%s: %s\\r\\n\", headers[i].name, headers[i].value);\n  }\n\n  if (0 == (conn->flags & WB_CLOSE_AFTER_RESPONSE))\n  {\n    /* See if the client wants us to close the connection. */\n    const char* connection_header = WebbyFindHeader(conn_pub, \"Connection\");\n    if (connection_header && 0 == strcasecmp(\"close\", connection_header))\n    {\n      conn->flags |= WB_CLOSE_AFTER_RESPONSE;\n      WebbyPrintf(conn_pub, \"Connection: close\\r\\n\");\n    }\n  }\n\n  WebbyPrintf(conn_pub, \"\\r\\n\");\n\n  if (content_length < 0)\n  {\n    conn->flags |= WB_CHUNKED_RESPONSE;\n  }\n\n  return 0;\n}\n\nstatic size_t make_websocket_header(unsigned char buffer[10], unsigned char opcode, int payload_len, int fin)\n{\n  buffer[0] = (fin ? 0x80 : 0x00) | opcode;\n\n  if (payload_len < 126)\n  {\n    buffer[1] = (unsigned char) (payload_len & 0x7f);\n    return 2;\n  }\n  else if (payload_len < 65536)\n  {\n    buffer[1] = 126;\n    buffer[2] = (unsigned char) (payload_len >> 8);\n    buffer[3] = (unsigned char) payload_len;\n    return 4;\n  }\n  else\n  {\n    buffer[1] = 127;\n    /* Ignore high 32-bits. I didn't want to require 64-bit types and typdef hell in the API. */\n    buffer[2] = buffer[3] = buffer[4] = buffer[5] = 0;\n    buffer[6] = (unsigned char) (payload_len >> 24);\n    buffer[7] = (unsigned char) (payload_len >> 16);\n    buffer[8] = (unsigned char) (payload_len >> 8);\n    buffer[9] = (unsigned char) payload_len;\n    return 10;\n  }\n}\n\nint\nWebbyBeginSocketFrame(struct WebbyConnection *conn_pub, int opcode)\n{\n  struct WebbyConnectionPrv *conn = (struct WebbyConnectionPrv *) conn_pub;\n\n  conn->ws_opcode = (unsigned char) opcode;\n\n  /* Switch socket to blocking mode */\n  return make_connection_blocking(conn);\n}\n\nint\nWebbyEndSocketFrame(struct WebbyConnection *conn_pub)\n{\n  struct WebbyConnectionPrv *conn = (struct WebbyConnectionPrv *) conn_pub;\n  unsigned char header[10];\n  size_t header_size;\n\n  header_size = make_websocket_header(header, conn->ws_opcode, 0, 1);\n\n  if (0 != send_fully(conn->socket, header, (int) header_size))\n    conn->flags &= ~WB_ALIVE;\n\n  /* Switch socket to non-blocking mode */\n  return make_connection_nonblocking(conn);\n}\n\nstatic int read_buffered_data(int *data_left, struct WebbyBuffer* buffer, char **dest_ptr, size_t *dest_len)\n{\n  int offset, read_size;\n  int left = *data_left;\n  int len;\n\n  if (left == 0)\n    return 0;\n\n  len = (int) *dest_len;\n  offset = buffer->used - left;\n  read_size = len > left ? left : len;\n\n  memcpy(*dest_ptr, buffer->data + offset, read_size);\n\n  (*dest_ptr) += read_size;\n  (*dest_len) -= (size_t) read_size;\n  (*data_left) -= read_size;\n\n  return read_size;\n}\n\nint WebbyRead(struct WebbyConnection *conn, void *ptr_, size_t len)\n{\n  struct WebbyConnectionPrv* conn_prv = (struct WebbyConnectionPrv*) conn;\n  char *ptr = (char*) ptr_;\n  int count;\n  int start_pos = conn_prv->body_bytes_read;\n\n  if (conn_prv->header_body_left > 0)\n  {\n    count = read_buffered_data(&conn_prv->header_body_left, &conn_prv->header_buf, &ptr, &len);\n    conn_prv->body_bytes_read += count;\n  }\n\n  /* Read buffered websocket data */\n  if (conn_prv->io_data_left > 0)\n  {\n    count = read_buffered_data(&conn_prv->io_data_left, &conn_prv->io_buf, &ptr, &len);\n    conn_prv->body_bytes_read += count;\n  }\n\n  while (len > 0)\n  {\n    int err = recv(conn_prv->socket, ptr, (int) len, 0);\n\n    if (err < 0)\n    {\n      conn_prv->flags &= ~WB_ALIVE;\n      return err;\n    }\n\n    len -= err;\n    ptr += err;\n    conn_prv->body_bytes_read += err;\n  }\n\n  if ((conn_prv->flags & WB_WEBSOCKET) && (conn_prv->ws_frame.flags & WEBBY_WSF_MASKED))\n  {\n    /* XOR outgoing data with websocket ofuscation key */\n    int i;\n    int end_pos = conn_prv->body_bytes_read;\n    const unsigned char *mask = conn_prv->ws_frame.mask_key;\n    ptr = (char*) ptr_; /* start over */\n    for (i = start_pos; i < end_pos; ++i)\n    {\n      unsigned char byte = *ptr;\n      *ptr++ = byte ^ mask[i & 3];\n    }\n  }\n\n  return 0;\n}\n\nint WebbyWrite(struct WebbyConnection *conn, const void *ptr, size_t len)\n{\n  struct WebbyConnectionPrv *conn_priv = (struct WebbyConnectionPrv *) conn;\n\n  if (conn_priv->flags & WB_WEBSOCKET)\n  {\n    unsigned char header[10];\n    size_t header_size;\n    header_size = make_websocket_header(header, conn_priv->ws_opcode, (int) len, 0);\n\n    /* Overwrite opcode to be continuation packages from here on out */\n    conn_priv->ws_opcode = WEBBY_WS_OP_CONTINUATION;\n\n    if (0 != send_fully(conn_priv->socket, header, (int) header_size))\n    {\n      conn_priv->flags &= ~WB_ALIVE;\n      return -1;\n    }\n    if (0 != send_fully(conn_priv->socket, (const unsigned char*) ptr, (int) len))\n    {\n      conn_priv->flags &= ~WB_ALIVE;\n      return -1;\n    }\n    return 0;\n  }\n  else if (conn_priv->flags & WB_CHUNKED_RESPONSE)\n  {\n    char chunk_header[128];\n    int header_len = snprintf(chunk_header, sizeof chunk_header, \"%x\\r\\n\", (int) len);\n    wb_push(conn_priv->server, conn_priv, chunk_header, header_len);\n    wb_push(conn_priv->server, conn_priv, ptr, (int) len);\n    return wb_push(conn_priv->server, conn_priv, \"\\r\\n\", 2);\n  }\n  else\n  {\n    return wb_push(conn_priv->server, conn_priv, ptr, (int) len);\n  }\n}\n\nvoid WebbyEndResponse(struct WebbyConnection *conn)\n{\n  struct WebbyConnectionPrv *conn_priv = (struct WebbyConnectionPrv *) conn;\n\n  if (conn_priv->flags & WB_CHUNKED_RESPONSE)\n  {\n    /* Write final chunk */\n    wb_push(conn_priv->server, conn_priv, \"0\\r\\n\\r\\n\", 5);\n\n    conn_priv->flags &= ~WB_CHUNKED_RESPONSE;\n  }\n\n  /* Flush buffers */\n  wb_push(conn_priv->server, conn_priv, \"\", 0);\n}\n\nint\nWebbySendFrame(struct WebbyConnection *conn_pub, int opcode, const void *ptr, size_t len)\n{\n  struct WebbyConnectionPrv *conn = (struct WebbyConnectionPrv *) conn_pub;\n  unsigned char header[10];\n  size_t header_size;\n\n  /* Switch socket to blocking mode */\n  make_connection_blocking(conn);\n\n  header_size = make_websocket_header(header, opcode, len, 1);\n  send_fully(conn->socket, header, (int)header_size);\n  send_fully(conn->socket, ptr, (int)len);\n\n  /* Switch socket to non-blocking mode */\n  return make_connection_nonblocking(conn);\n}\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/imgui_remote/webby/webby.h",
    "content": "#ifndef WEBBY_H\n#define WEBBY_H\n\n#include <stddef.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/*\n   Webby - A tiny little web server for game debugging.\n*/\n\n/* Server initialization flags */\nenum\n{\n  WEBBY_SERVER_LOG_DEBUG    = 1 << 0,\n  WEBBY_SERVER_WEBSOCKETS   = 1 << 1\n};\n\n/* Hard limits */\nenum\n{\n  WEBBY_MAX_HEADERS         = 64\n};\n\nstruct WebbyServer;\n\n/* A HTTP header */\nstruct WebbyHeader\n{\n  const char *name;\n  const char *value;\n};\n\n/* A HTTP request. */\nstruct WebbyRequest\n{\n  /* The method of the request, e.g. \"GET\", \"POST\" and so on */\n  const char *method;\n  /* The URI that was used. */\n  const char *uri;\n  /* The HTTP version that used. */\n  const char *http_version;\n  /* The query parameters passed in the URL, or NULL if none were passed. */\n  const char *query_params;\n  /* The number of bytes of request body that are available via WebbyRead() */\n  int content_length;\n  /* The number of headers */\n  int header_count;\n  /* Request headers */\n  struct WebbyHeader headers[WEBBY_MAX_HEADERS];\n};\n\n/* Connection state, as published to the serving callback. */\nstruct WebbyConnection\n{\n  /* The request being served. Read-only. */\n  struct WebbyRequest request;\n  \n  /* User data. Read-write. Webby doesn't care about this. */\n  void *user_data;\n};\n\nenum\n{\n  WEBBY_WS_OP_CONTINUATION    = 0,\n  WEBBY_WS_OP_TEXT_FRAME      = 1,\n  WEBBY_WS_OP_BINARY_FRAME    = 2,\n  WEBBY_WS_OP_CLOSE           = 8,\n  WEBBY_WS_OP_PING            = 9,\n  WEBBY_WS_OP_PONG            = 10\n};\n\nenum\n{\n  WEBBY_WSF_FIN               = 1 << 0,\n  WEBBY_WSF_MASKED            = 1 << 1\n};\n\nstruct WebbyWsFrame\n{\n  unsigned char flags;\n  unsigned char opcode;\n  unsigned char header_size;\n  unsigned char padding_;\n  unsigned char mask_key[4];\n  int           payload_length;\n};\n\n/* Configuration data required for starting a server. */\nstruct WebbyServerConfig\n{\n  /* The bind address. Must be a textual IP address. */\n  const char *bind_address;\n\n  /* The port to listen to. */\n  unsigned short listening_port;\n\n  /* Flags. Right now WEBBY_SERVER_LOG_DEBUG is the only valid flag. */\n  unsigned int flags;\n\n  /* Maximum number of simultaneous connections. */\n  int connection_max;\n\n  /* The size of the request buffer. This must be big enough to contain all\n   * headers and the request line sent by the client. 2-4k is a good size for\n   * this buffer. */\n  int request_buffer_size;\n\n  /* The size of the I/O buffer, used when writing the reponse. 4k is a good\n   * choice for this buffer.*/\n  int io_buffer_size;\n\n  /* Optional callback function that receives debug log text (without\n   * newlines). */\n  void (*log)(const char *msg);\n\n  /* Request dispatcher function. This function is called when the request\n   * structure is ready.\n   *\n   * If you decide to handle the request, call WebbyBeginResponse(),\n   * WebbyWrite() and WebbyEndResponse() and then return 0. Otherwise, return a\n   * non-zero value to have Webby send back a 404 response.\n   */\n  int (*dispatch)(struct WebbyConnection *connection);\n\n  /*\n   * WebSocket connection dispatcher. Called when an incoming request wants to\n   * update to a WebSocket connection.\n   *\n   * Return 0 to allow the connection.\n   * Return 1 to ignore the connection.\n   */\n  int (*ws_connect)(struct WebbyConnection *connection);\n\n  /*\n   * Called when a WebSocket connection has been established.\n   */\n  void (*ws_connected)(struct WebbyConnection *connection);\n\n  /*\n   * Called when a WebSocket connection has been closed.\n   */\n  void (*ws_closed)(struct WebbyConnection *connection);\n\n  /*\n   * Called when a WebSocket data frame is incoming.\n   *\n   * Call WebbyRead() to read the payload data.\n   *\n   * Return non-zero to close the connection.\n   */\n  int (*ws_frame)(struct WebbyConnection *connection, const struct WebbyWsFrame *frame);\n};\n\n/* Returns the amount of memory needed for the specified config. */\nint\nWebbyServerMemoryNeeded(const struct WebbyServerConfig *config);\n\n/* Initialize a server in the specified memory space. Size must be big enough,\n * as determined by WebbyServerMemoryNeeded(). The memory block must be aligned\n * to at least 8 bytes.\n */\nstruct WebbyServer*\nWebbyServerInit(struct WebbyServerConfig *config, void *memory, size_t memory_size);\n\n/* Update the server. Call frequently (at least once per frame). */\nvoid\nWebbyServerUpdate(struct WebbyServer *srv);\n\n/* Shutdown the server and close all sockets. */\nvoid\nWebbyServerShutdown(struct WebbyServer *srv);\n\n/*\n * Begin a response.\n *\n * status_code - The HTTP status code to send. Normally 200\n * content_length - size in bytes you intend to write, or -1 for chunked encoding\n * headers - Array of HTTP headers to transmit (can be NULL if header_count ==0)\n * header_count - Number of headers in the array.\n *\n * Returns zero on success, non-zero on error.\n */\nint\nWebbyBeginResponse(\n    struct WebbyConnection *conn,\n    int status_code,\n    int content_length,\n    const struct WebbyHeader headers[],\n    int header_count);\n\n/*\n * Finish a response.\n *\n * When you're done writing the response body, call this function. It makes\n * sure that chunked encoding is terminated correctly and that the connection\n * is set up for reuse.\n */\nvoid\nWebbyEndResponse(struct WebbyConnection *conn);\n\n/*\n * Read data from the request body. Only read what the client has provided (via\n * the content_length) parameter, or you will end up blocking forever.\n */\nint WebbyRead(struct WebbyConnection *conn, void *ptr, size_t len);\n\n/*\n * Write response data to the connection. If you're not using chunked encoding,\n * be careful not to send more than the specified content length. You can call\n * this function multiple times as long as the total number of bytes matches up\n * with the content length.\n */\nint WebbyWrite(struct WebbyConnection *conn, const void *ptr, size_t len);\n\n/*\n * Convenience function to do formatted printing to a response. Only useful\n * when chunked encoding is being used.\n */\nint WebbyPrintf(struct WebbyConnection *conn, const char *fmt, ...);\n\n/*\n * Convenience function to find a header in a request. Returns the value of the\n * specified header, or NULL if it was not present.\n */\nconst char *WebbyFindHeader(struct WebbyConnection *conn, const char *name);\n\n/* Helper function to look up a query parameter given a URL encoded string.\n\n   Returns the size of the returned data, or -1 if the query var wasn't found.\n */\nint WebbyFindQueryVar(const char *query_params, const char *name, char *buffer, size_t buffer_size);\n\n/* Begin an outgoing websocket frame */\nint\nWebbyBeginSocketFrame(struct WebbyConnection *conn, int websocket_opcode);\n\n/* End an outgoing websocket frame */\nint\nWebbyEndSocketFrame(struct WebbyConnection *conn);\n\nint\nWebbySendFrame(struct WebbyConnection *conn_pub, int opcode, const void *ptr, size_t len);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/imgui_remote/webby/webby_unix.h",
    "content": "\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <arpa/inet.h>\n#include <fcntl.h>\n#include <unistd.h>\n#include <errno.h>\n\ntypedef int webby_socket_t;\ntypedef socklen_t webby_socklen_t;\n\n#define WB_ALIGN(x) __attribute__((aligned(x)))\n#define WB_INVALID_SOCKET (-1)\n\nstatic int wb_socket_error(void)\n{\n  return errno;\n}\n\nstatic int wb_valid_socket(webby_socket_t socket)\n{\n  return socket > 0;\n}\n\nstatic void wb_close_socket(webby_socket_t socket)\n{\n  close(socket);\n}\n\nstatic int wb_is_blocking_error(int error)\n{\n  return EAGAIN == error;\n}\n\nstatic int wb_set_blocking(webby_socket_t socket, int blocking)\n{\n  int flags = fcntl(socket, F_GETFL);\n  if (blocking)\n    return fcntl(socket, F_SETFL, flags & ~O_NONBLOCK);\n  else\n    return fcntl(socket, F_SETFL, flags | O_NONBLOCK);\n}\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/imgui_remote/webby/webby_win32.h",
    "content": "\n#include <winsock2.h>\n\ntypedef SOCKET webby_socket_t;\n\n#if defined(__GNUC__)\n#define WB_ALIGN(x) __attribute__((aligned(x)))\n#else\n#define WB_ALIGN(x) __declspec(align(x))\n#endif\n\n#define WB_INVALID_SOCKET INVALID_SOCKET\n#define snprintf _snprintf\n\ntypedef int webby_socklen_t;\n\nstatic int wb_socket_error(void)\n{\n  return WSAGetLastError();\n}\n\n#if !defined(__GNUC__)\nstatic int strcasecmp(const char *a, const char *b)\n{\n  return _stricmp(a, b);\n}\n\nstatic int strncasecmp(const char *a, const char *b, size_t len)\n{\n  return _strnicmp(a, b, len);\n}\n#endif\n\nstatic int wb_set_blocking(webby_socket_t socket, int blocking)\n{\n  u_long val = !blocking;\n  return ioctlsocket(socket, FIONBIO, &val);\n}\n\nstatic int wb_valid_socket(webby_socket_t socket)\n{\n  return INVALID_SOCKET != socket;\n}\n\nstatic void wb_close_socket(webby_socket_t socket)\n{\n  closesocket(socket);\n}\n\nstatic int wb_is_blocking_error(int error)\n{\n  return WSAEWOULDBLOCK == error;\n}\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/implot/LICENSE",
    "content": "MIT License\n\nCopyright (c) 2020 Evan Pezent\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/implot/README.md",
    "content": "# ImPlot\nImPlot is an immediate mode, GPU accelerated plotting library for [Dear ImGui](https://github.com/ocornut/imgui). It aims to provide a first-class API that ImGui fans will love. ImPlot is well suited for visualizing program data in real-time or creating interactive plots, and requires minimal code to integrate. Just like ImGui, it does not burden the end user with GUI state management, avoids STL containers and C++ headers, and has no external dependencies except for ImGui itself.\n\n<img src=\"https://raw.githubusercontent.com/wiki/epezent/implot/screenshots3/controls.gif\" width=\"270\"> <img src=\"https://raw.githubusercontent.com/wiki/epezent/implot/screenshots3/dnd.gif\" width=\"270\"> <img src=\"https://raw.githubusercontent.com/wiki/epezent/implot/screenshots3/pie.gif\" width=\"270\">\n\n<img src=\"https://raw.githubusercontent.com/wiki/epezent/implot/screenshots3/query.gif\" width=\"270\"> <img src=\"https://raw.githubusercontent.com/wiki/epezent/implot/screenshots3/bars.gif\" width=\"270\">\n<img src=\"https://raw.githubusercontent.com/wiki/epezent/implot/screenshots3/rt.gif\" width=\"270\">\n\n<img src=\"https://raw.githubusercontent.com/wiki/epezent/implot/screenshots3/stem.gif\" width=\"270\"> <img src=\"https://raw.githubusercontent.com/wiki/epezent/implot/screenshots3/markers.gif\" width=\"270\">\n<img src=\"https://raw.githubusercontent.com/wiki/epezent/implot/screenshots3/shaded.gif\" width=\"270\">\n\n<img src=\"https://raw.githubusercontent.com/wiki/epezent/implot/screenshots3/candle.gif\" width=\"270\"> <img src=\"https://raw.githubusercontent.com/wiki/epezent/implot/screenshots3/heat.gif\" width=\"270\">\n<img src=\"https://raw.githubusercontent.com/wiki/epezent/implot/screenshots3/tables.gif\" width=\"270\">\n\n## Features\n\n- GPU accelerated rendering\n- multiple plot types:\n    - line plots\n    - shaded plots\n    - scatter plots\n    - vertical/horizontal/stacked bars graphs\n    - vertical/horizontal error bars\n    - stem plots\n    - stair plots\n    - pie charts\n    - heatmap charts\n    - 1D/2D histograms\n    - images\n    - and more likely to come\n- mix/match multiple plot items on a single plot\n- configurable axes ranges and scaling (linear/log)\n- subplots\n- time formatted x-axes (US formatted or ISO 8601)\n- reversible and lockable axes\n- multiple x-axes and y-axes\n- controls for zooming, panning, box selection, and auto-fitting data\n- controls for creating persistent query ranges (see demo)\n- several plot styling options: 10 marker types, adjustable marker sizes, line weights, outline colors, fill colors, etc.\n- 16 built-in colormaps and support for and user-added colormaps\n- optional plot titles, axis labels, and grid labels\n- optional and configurable legends with toggle buttons to quickly show/hide plot items\n- default styling based on current ImGui theme, or completely custom plot styles\n- customizable data getters and data striding (just like ImGui:PlotLine)\n- accepts data as float, double, and 8, 16, 32, and 64-bit signed/unsigned integral types\n- and more! (see Announcements [2020](https://github.com/epezent/implot/issues/48)/[2021](https://github.com/epezent/implot/issues/168))\n\n## Usage\n\nThe API is used just like any other ImGui `BeginX`/`EndX` pair. First, start a new plot with `ImPlot::BeginPlot()`. Next, plot as many items as you want with the provided `PlotX` functions (e.g. `PlotLine()`, `PlotBars()`, `PlotScatter()`, etc). Finally, wrap things up with a call to `ImPlot::EndPlot()`. That's it!\n\n```cpp\nint   bar_data[11] = ...;\nfloat x_data[1000] = ...;\nfloat y_data[1000] = ...;\n\nImGui::Begin(\"My Window\");\nif (ImPlot::BeginPlot(\"My Plot\")) {\n    ImPlot::PlotBars(\"My Bar Plot\", bar_data, 11);\n    ImPlot::PlotLine(\"My Line Plot\", x_data, y_data, 1000);\n    ...\n    ImPlot::EndPlot();\n}\nImGui::End();\n```\n\n![Usage](https://raw.githubusercontent.com/wiki/epezent/implot/screenshots3/example.PNG)\n\n\nOf course, there's much more you can do with ImPlot... \n\n## Demos\n\nA comprehensive example of ImPlot's features can be found in `implot_demo.h`. Add this file to your sources and call `ImPlot::ShowDemoWindow()` somewhere in your update loop. You are encouraged to use this file as a reference when needing to implement various plot types. The demo is always updated to show new plot types and features as they are added, so check back with each release!\n\nAn online version of the demo is hosted [here](https://traineq.org/implot_demo/src/implot_demo.html). You can view the plots and the source code that generated them. Note that this demo may not always be up to date and is not as performant as a desktop implementation, but it should give you a general taste of what's possible with ImPlot. Special thanks to [pthom](https://github.com/pthom) for creating and hosting this!\n\nMore sophisticated demos requiring lengthier code and/or third-party libraries can be found in a separate repository: [implot_demos](https://github.com/epezent/implot_demos). Here, you will find advanced signal processing and ImPlot usage in action. Please read the `Contributing` section of that repository if you have an idea for a new demo!\n\n## Integration\n\n0) Set up an [ImGui](https://github.com/ocornut/imgui) environment if you don't already have one.\n1) Add `implot.h`, `implot_internal.h`, `implot.cpp`, `implot_items.cpp` and optionally `implot_demo.cpp` to your sources. Alternatively, you can get ImPlot using [vcpkg](https://github.com/microsoft/vcpkg/tree/master/ports/implot).\n2) Create and destroy an `ImPlotContext` wherever you do so for your `ImGuiContext`:\n\n```cpp\nImGui::CreateContext();\nImPlot::CreateContext();\n...\nImPlot::DestroyContext();\nImGui::DestroyContext();\n```\n\nYou should be good to go!\n\nIf you want to test ImPlot quickly, consider trying [mahi-gui](https://github.com/mahilab/mahi-gui), which bundles ImGui, ImPlot, and several other packages for you.\n\n## Extremely Important Note\n\nDear ImGui uses **16-bit indexing by default**, so high-density ImPlot widgets like `ImPlot::PlotHeatmap()` may produce too many vertices into `ImDrawList`, which causes an assertion failure and will result in data truncation and/or visual glitches. Therefore, it is **HIGHLY** recommended that you EITHER:\n\n- **Option 1:** Enable 32-bit indices by uncommenting `#define ImDrawIdx unsigned int` in your ImGui [`imconfig.h`](https://github.com/ocornut/imgui/blob/master/imconfig.h#L89) file.\n- **Option 2:** Handle the `ImGuiBackendFlags_RendererHasVtxOffset` flag in your renderer if you must use 16-bit indices. Many of the default ImGui rendering backends already support `ImGuiBackendFlags_RendererHasVtxOffset`. Refer to [this issue](https://github.com/ocornut/imgui/issues/2591) for more information.\n\n## FAQ\n\n**Q: Why?**\n\nA: ImGui is an incredibly powerful tool for rapid prototyping and development, but provides only limited mechanisms for data visualization. Two dimensional plots are ubiquitous and useful to almost any application. Being able to visualize your data in real-time will give you insight and better understanding of your application.\n\n**Q: Is ImPlot the right plotting library for me?**\n\nA: If you're looking to generate publication quality plots and/or export plots to a file, ImPlot is NOT the library for you! ImPlot is geared toward plotting application data at realtime speeds with high levels of interactivity. ImPlot does its best to create pretty plots (indeed, there are quite a few styling options available), but it will always favor function over form.\n\n**Q: Where is the documentation?**\n\nA: The API is thoroughly commented in `implot.h`, and the demo in `implot_demo.cpp` should be more than enough to get you started. Also take a look at the [implot_demos](https://github.com/epezent/implot_demos) repository.\n\n**Q: Is ImPlot suitable for plotting large datasets?**\n\nA: Yes, within reason. You can plot tens to hundreds of thousands of points without issue, but don't expect millions to be a buttery smooth experience. That said, you can always downsample extremely large datasets by telling ImPlot to stride your data at larger intervals if needed. Also try the experimental `backends` branch which aims to provide GPU acceleration support.\n\n**Q: What data types can I plot?**\n\nA: ImPlot plotting functions accept most scalar types:\n`float`, `double`, `int8`, `uint8`, `int16`, `uint16`, `int32`, `uint32`, `int64`, `uint64`. Arrays of custom structs or classes (e.g. `Vector2f` or similar) are easily passed to ImPlot functions using the built in striding features (see `implot.h` for documentation), and many plotters provide a \"getter\" overload which accepts data generating callbacks.\n\n**Q: Can plot styles be modified?**\n\nA: Yes. Data colormaps and various styling colors and variables can be pushed/popped or modified permanently on startup. Three default styles are available, as well as an automatic style that attempts to match you ImGui style.\n\n**Q: Does ImPlot support logarithmic scaling or time formatting?**\n\nA: Yep! Both logscale and timescale are supported.\n\n**Q: Does ImPlot support multiple y-axes? x-axes?**\n\nA: Yes. Up to three x-axes and three y-axes can be enabled.\n\n**Q: Does ImPlot support [insert plot type]?**\n\nA: Maybe. Check the demo, gallery, or Announcements ([2020](https://github.com/epezent/implot/issues/48)/[2021](https://github.com/epezent/implot/issues/168))to see if your desired plot type is shown. If not, consider submitting an issue or better yet, a PR!\n\n**Q: Does ImPlot support 3D plots?**\n\nA: No, and likely never will since ImGui only deals in 2D rendering.\n\n**Q: My plot lines look like crap!**\n\nA: By default, no anti-aliasing is done on line plots for performance gains. If you use at least 4x MSAA, then you likely won't even notice. However, you can enable software AA per-plot with the `ImPlotFlags_AntiAliased` flag, or globally with `ImPlot::GetStyle().AntiAliasedLines = true;`.\n\n**Q: Does ImPlot provide analytic tools?**\n\nA: Not exactly, but it does give you the ability to query plot sub-ranges, with which you can process your data however you like.\n\n**Q: Can plots be exported/saved to image?**\n\nA: Not currently. Use your OS's screen capturing mechanisms if you need to capture a plot. ImPlot is not suitable for rendering publication quality plots; it is only intended to be used as a visualization tool. Post-process your data with MATLAB or matplotlib for these purposes.\n\n**Q: Can I compile ImPlot as a dynamic library?**\n\nA: Like ImGui, it is recommended that you compile and link ImPlot as a *static* library or directly as a part of your sources. However, if you must and are compiling ImPlot and ImGui as separate DLLs, make sure you set the current *ImGui* context with `ImPlot::SetImGuiContext(ImGuiContext* ctx)`. This ensures that global ImGui variables are correctly shared across the DLL boundary.\n\n**Q: Can ImPlot be used with other languages/bindings?**\n\nA: Yes, you can use the generated C binding, [cimplot](https://github.com/cimgui/cimplot) with most high level languages. [DearPyGui](https://github.com/hoffstadt/DearPyGui) provides a Python wrapper, among other things. [imgui-java](https://github.com/SpaiR/imgui-java) provides bindings for Java. A Rust binding, [implot-rs](https://github.com/4bb4/implot-rs), is currently in the works. An example using Emscripten can be found [here](https://github.com/pthom/implot_demo).\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/implot/TODO.md",
    "content": "The list below represents a combination of high-priority work, nice-to-have features, and random ideas. We make no guarantees that all of this work will be completed or even started. If you see something that you need or would like to have, let us know, or better yet consider submitting a PR for the feature.\n\n## API\n\n- add shortcut/legacy overloads for BeginPlot\n\n## Axes\n\n- add flag to remove weekends on Time axis\n- pixel space scale (`ImPlotTransform_Display`), normalized space scale (`ImPlotTransform_Axes`), data space scale (`ImPloTransform_Data`)\n- make ImPlotFlags_Equal not a flag -> `SetupEqual(ImPlotAxis x, ImPlotAxis y)`\n- allow inverted arguments `SetAxes` to transpose data?\n- `SetupAxisColors()`\n- `SetupAxisConstraints()`\n- `SetupAxisHome()`\n\n## Plot Items\n\n- add `ImPlotLineFlags`, `ImPlotBarsFlags`, etc. for each plot type\n- add `PlotBarGroups` wrapper that makes rendering groups of bars easier, with stacked bar support\n- add `PlotBubbles` (see MATLAB bubble chart)\n- add non-zero references for `PlotBars` etc.\n- add exploding to `PlotPieChart` (on hover-highlight?)\n\n## Styling\n\n- support gradient and/or colormap sampled fills (e.g. ImPlotFillStyle_)\n- add hover/active color for plot axes\n- API for setting different fonts for plot elements\n\n## Colormaps\n\n- gradient editing tool\n- `RemoveColormap`\n\n## Legend\n\n- `ImPlotLegendFlags_SortItems`\n- `ImPlotLegendFlags_Scroll`\n- improve legend icons (e.g. adopt markers, gradients, etc)\n- make legend frame use ButtonBehavior (maybe impossible)\n\n## Tools / Misc.\n\n- add `IsPlotChanging` to detect change in limits\n- add ability to extend plot/axis context menus\n- add LTTB downsampling for lines\n- add box selection to axes\n- first frame render delay might fix \"fit pop\" effect\n- move some code to new `implot_tools.cpp`\n\n## Optimizations\n\n- find faster way to buffer data into ImDrawList (very slow)\n- reduce number of calls to `PushClipRect`\n- explore SIMD operations for high density plot items\n\n## Completed\n- make BeginPlot take fewer args:\n- make query a tool -> `DragRect`\n- rework DragLine/Point to use ButtonBehavior\n- add support for multiple x-axes and don't limit count to 3\n- make axis side configurable (top/left, right/bottom) via new flag `ImPlotAxisFlags_Opposite`\n- add support for setting tick label strings via callback\n- give each axis an ID, remove ad-hoc DND solution\n- allow axis to be drag to opposite side (ala ImGui Table headers)\n- legend items can be hovered even if plot is not\n- fix frame delay on DragX tools\n- remove tag from drag line/point -> add `Tag` tool\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/implot/implot.cpp",
    "content": "// MIT License\n\n// Copyright (c) 2021 Evan Pezent\n\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n// ImPlot v0.13 WIP\n\n/*\n\nAPI BREAKING CHANGES\n====================\nOccasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.\nBelow is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code.\nWhen you are not sure about a old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all implot files.\nYou can read releases logs https://github.com/epezent/implot/releases for more details.\n\n- 2021/10/19 (0.13) MAJOR API OVERHAUL!\n                    - TRIVIAL RENAME:\n                      - ImPlotLimits                              -> ImPlotRect\n                      - ImPlotYAxis_                              -> ImAxis_\n                      - SetPlotYAxis                              -> SetAxis\n                      - BeginDragDropTarget                       -> BeginDragDropTargetPlot\n                      - BeginDragDropSource                       -> BeginDragDropSourcePlot\n                      - ImPlotFlags_NoMousePos                    -> ImPlotFlags_NoMouseText\n                      - SetNextPlotLimits                         -> SetNextAxesLimits\n                      - SetMouseTextLocation                      -> SetupMouseText\n                    - SIGNATURE MODIFIED:\n                      - PixelsToPlot/PlotToPixels                 -> added optional X-Axis arg\n                      - GetPlotMousePos                           -> added optional X-Axis arg\n                      - GetPlotLimits                             -> added optional X-Axis arg\n                      - GetPlotSelection                          -> added optional X-Axis arg\n                      - DragLineX/Y/DragPoint                     -> now takes int id; removed labels (render with Annotation/Tag instead)\n                    - REPLACED:\n                      - IsPlotXAxisHovered/IsPlotXYAxisHovered    -> IsAxisHovered(ImAxis)\n                      - BeginDragDropTargetX/BeginDragDropTargetY -> BeginDragDropTargetAxis(ImAxis)\n                      - BeginDragDropSourceX/BeginDragDropSourceY -> BeginDragDropSourceAxis(ImAxis)\n                      - ImPlotCol_XAxis, ImPlotCol_YAxis1, etc.   -> ImPlotCol_AxisText (push/pop this around SetupAxis to style individual axes)\n                      - ImPlotCol_XAxisGrid, ImPlotCol_Y1AxisGrid -> ImPlotCol_AxisGrid (push/pop this around SetupAxis to style individual axes)\n                      - SetNextPlotLimitsX/Y                      -> SetNextAxisLimits(ImAxis)\n                      - LinkNextPlotLimits                        -> SetNextAxisLinks(ImAxis)\n                      - FitNextPlotAxes                           -> SetNextAxisToFit(ImAxis)/SetNextAxesToFit\n                      - SetLegendLocation                         -> SetupLegend\n                      - ImPlotFlags_NoHighlight                   -> ImPlotLegendFlags_NoHighlight\n                      - ImPlotOrientation                         -> ImPlotLegendFlags_Horizontal\n                      - Annotate                                  -> Annotation\n                    - REMOVED:\n                      - GetPlotQuery, SetPlotQuery, IsPlotQueried -> use DragRect\n                      - SetNextPlotTicksX, SetNextPlotTicksY      -> use SetupAxisTicks\n                      - SetNextPlotFormatX, SetNextPlotFormatY    -> use SetupAxisFormat\n                      - AnnotateClamped                           -> use Annotation(bool clamp = true)\n                    - OBSOLETED:\n                      - BeginPlot (original signature)            -> use simplified signature + Setup API\n- 2021/07/30 (0.12) - The offset argument of `PlotXG` functions was been removed. Implement offsetting in your getter callback instead.\n- 2021/03/08 (0.9)  - SetColormap and PushColormap(ImVec4*) were removed. Use AddColormap for custom colormap support. LerpColormap was changed to SampleColormap.\n                      ShowColormapScale was changed to ColormapScale and requires additional arguments.\n- 2021/03/07 (0.9)  - The signature of ShowColormapScale was modified to accept a ImVec2 size.\n- 2021/02/28 (0.9)  - BeginLegendDragDropSource was changed to BeginDragDropSourceItem with a number of other drag and drop improvements.\n- 2021/01/18 (0.9)  - The default behavior for opening context menus was change from double right-click to single right-click. ImPlotInputMap and related functions were moved\n                      to implot_internal.h due to its immaturity.\n- 2020/10/16 (0.8)  - ImPlotStyleVar_InfoPadding was changed to ImPlotStyleVar_MousePosPadding\n- 2020/09/10 (0.8)  - The single array versions of PlotLine, PlotScatter, PlotStems, and PlotShaded were given additional arguments for x-scale and x0.\n- 2020/09/07 (0.8)  - Plotting functions which accept a custom getter function pointer have been post-fixed with a G (e.g. PlotLineG)\n- 2020/09/06 (0.7)  - Several flags under ImPlotFlags and ImPlotAxisFlags were inverted (e.g. ImPlotFlags_Legend -> ImPlotFlags_NoLegend) so that the default flagset\n                      is simply 0. This more closely matches ImGui's style and makes it easier to enable non-default but commonly used flags (e.g. ImPlotAxisFlags_Time).\n- 2020/08/28 (0.5)  - ImPlotMarker_ can no longer be combined with bitwise OR, |. This features caused unecessary slow-down, and almost no one used it.\n- 2020/08/25 (0.5)  - ImPlotAxisFlags_Scientific was removed. Logarithmic axes automatically uses scientific notation.\n- 2020/08/17 (0.5)  - PlotText was changed so that text is centered horizontally and vertically about the desired point.\n- 2020/08/16 (0.5)  - An ImPlotContext must be explicitly created and destroyed now with `CreateContext` and `DestroyContext`. Previously, the context was statically initialized in this source file.\n- 2020/06/13 (0.4)  - The flags `ImPlotAxisFlag_Adaptive` and `ImPlotFlags_Cull` were removed. Both are now done internally by default.\n- 2020/06/03 (0.3)  - The signature and behavior of PlotPieChart was changed so that data with sum less than 1 can optionally be normalized. The label format can now be specified as well.\n- 2020/06/01 (0.3)  - SetPalette was changed to `SetColormap` for consistency with other plotting libraries. `RestorePalette` was removed. Use `SetColormap(ImPlotColormap_Default)`.\n- 2020/05/31 (0.3)  - Plot functions taking custom ImVec2* getters were removed. Use the ImPlotPoint* getter versions instead.\n- 2020/05/29 (0.3)  - The signature of ImPlotLimits::Contains was changed to take two doubles instead of ImVec2\n- 2020/05/16 (0.2)  - All plotting functions were reverted to being prefixed with \"Plot\" to maintain a consistent VerbNoun style. `Plot` was split into `PlotLine`\n                      and `PlotScatter` (however, `PlotLine` can still be used to plot scatter points as `Plot` did before.). `Bar` is not `PlotBars`, to indicate\n                      that multiple bars will be plotted.\n- 2020/05/13 (0.2)  - `ImMarker` was change to `ImPlotMarker` and `ImAxisFlags` was changed to `ImPlotAxisFlags`.\n- 2020/05/11 (0.2)  - `ImPlotFlags_Selection` was changed to `ImPlotFlags_BoxSelect`\n- 2020/05/11 (0.2)  - The namespace ImGui:: was replaced with ImPlot::. As a result, the following additional changes were made:\n                      - Functions that were prefixed or decorated with the word \"Plot\" have been truncated. E.g., `ImGui::PlotBars` is now just `ImPlot::Bar`.\n                        It should be fairly obvious what was what.\n                      - Some functions have been given names that would have otherwise collided with the ImGui namespace. This has been done to maintain a consistent\n                        style with ImGui. E.g., 'ImGui::PushPlotStyleVar` is now 'ImPlot::PushStyleVar'.\n- 2020/05/10 (0.2)  - The following function/struct names were changes:\n                     - ImPlotRange       -> ImPlotLimits\n                     - GetPlotRange()    -> GetPlotLimits()\n                     - SetNextPlotRange  -> SetNextPlotLimits\n                     - SetNextPlotRangeX -> SetNextPlotLimitsX\n                     - SetNextPlotRangeY -> SetNextPlotLimitsY\n- 2020/05/10 (0.2)  - Plot queries are pixel based by default. Query rects that maintain relative plot position have been removed. This was done to support multi-y-axis.\n\n*/\n\n#include \"implot.h\"\n#include \"implot_internal.h\"\n\n#include <stdlib.h>\n\n// Support for pre-1.82 versions. Users on 1.82+ can use 0 (default) flags to mean \"all corners\" but in order to support older versions we are more explicit.\n#if (IMGUI_VERSION_NUM < 18102) && !defined(ImDrawFlags_RoundCornersAll)\n#define ImDrawFlags_RoundCornersAll ImDrawCornerFlags_All\n#endif\n\n// Visual Studio warnings\n#ifdef _MSC_VER\n#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen\n#endif\n\n// Clang/GCC warnings with -Weverything\n#if defined(__clang__)\n#pragma clang diagnostic ignored \"-Wformat-nonliteral\"  // warning: format string is not a string literal\n#elif defined(__GNUC__)\n#pragma GCC diagnostic ignored \"-Wformat-nonliteral\"    // warning: format not a string literal, format string not checked\n#endif\n\n// Global plot context\n#ifndef GImPlot\nImPlotContext* GImPlot = NULL;\n#endif\n\n//-----------------------------------------------------------------------------\n// Struct Implementations\n//-----------------------------------------------------------------------------\n\nImPlotInputMap::ImPlotInputMap() {\n    ImPlot::MapInputDefault(this);\n}\n\nImPlotStyle::ImPlotStyle() {\n\n    LineWeight         = 1;\n    Marker             = ImPlotMarker_None;\n    MarkerSize         = 4;\n    MarkerWeight       = 1;\n    FillAlpha          = 1;\n    ErrorBarSize       = 5;\n    ErrorBarWeight     = 1.5f;\n    DigitalBitHeight   = 8;\n    DigitalBitGap      = 4;\n\n    PlotBorderSize     = 1;\n    MinorAlpha         = 0.25f;\n    MajorTickLen       = ImVec2(10,10);\n    MinorTickLen       = ImVec2(5,5);\n    MajorTickSize      = ImVec2(1,1);\n    MinorTickSize      = ImVec2(1,1);\n    MajorGridSize      = ImVec2(1,1);\n    MinorGridSize      = ImVec2(1,1);\n    PlotPadding        = ImVec2(10,10);\n    LabelPadding       = ImVec2(5,5);\n    LegendPadding      = ImVec2(10,10);\n    LegendInnerPadding = ImVec2(5,5);\n    LegendSpacing      = ImVec2(5,0);\n    MousePosPadding    = ImVec2(10,10);\n    AnnotationPadding  = ImVec2(2,2);\n    FitPadding         = ImVec2(0,0);\n    PlotDefaultSize    = ImVec2(400,300);\n    PlotMinSize        = ImVec2(200,150);\n\n    ImPlot::StyleColorsAuto(this);\n\n    Colormap = ImPlotColormap_Deep;\n\n    AntiAliasedLines = false;\n    UseLocalTime     = false;\n    Use24HourClock   = false;\n    UseISO8601       = false;\n}\n\n//-----------------------------------------------------------------------------\n// Style\n//-----------------------------------------------------------------------------\n\nnamespace ImPlot {\n\nconst char* GetStyleColorName(ImPlotCol col) {\n    static const char* col_names[ImPlotCol_COUNT] = {\n        \"Line\",\n        \"Fill\",\n        \"MarkerOutline\",\n        \"MarkerFill\",\n        \"ErrorBar\",\n        \"FrameBg\",\n        \"PlotBg\",\n        \"PlotBorder\",\n        \"LegendBg\",\n        \"LegendBorder\",\n        \"LegendText\",\n        \"TitleText\",\n        \"InlayText\",\n        \"AxisText\",\n        \"AxisGrid\",\n        \"AxisTick\",\n        \"AxisBg\",\n        \"AxisBgHovered\",\n        \"AxisBgActive\",\n        \"Selection\",\n        \"Crosshairs\"\n    };\n    return col_names[col];\n}\n\nconst char* GetMarkerName(ImPlotMarker marker) {\n    switch (marker) {\n        case ImPlotMarker_None:     return \"None\";\n        case ImPlotMarker_Circle:   return \"Circle\";\n        case ImPlotMarker_Square:   return \"Square\";\n        case ImPlotMarker_Diamond:  return \"Diamond\";\n        case ImPlotMarker_Up:       return \"Up\";\n        case ImPlotMarker_Down:     return \"Down\";\n        case ImPlotMarker_Left:     return \"Left\";\n        case ImPlotMarker_Right:    return \"Right\";\n        case ImPlotMarker_Cross:    return \"Cross\";\n        case ImPlotMarker_Plus:     return \"Plus\";\n        case ImPlotMarker_Asterisk: return \"Asterisk\";\n        default:                    return \"\";\n    }\n}\n\nImVec4 GetAutoColor(ImPlotCol idx) {\n    ImVec4 col(0,0,0,1);\n    switch(idx) {\n        case ImPlotCol_Line:          return col; // these are plot dependent!\n        case ImPlotCol_Fill:          return col; // these are plot dependent!\n        case ImPlotCol_MarkerOutline: return col; // these are plot dependent!\n        case ImPlotCol_MarkerFill:    return col; // these are plot dependent!\n        case ImPlotCol_ErrorBar:      return ImGui::GetStyleColorVec4(ImGuiCol_Text);\n        case ImPlotCol_FrameBg:       return ImGui::GetStyleColorVec4(ImGuiCol_FrameBg);\n        case ImPlotCol_PlotBg:        return ImGui::GetStyleColorVec4(ImGuiCol_WindowBg);\n        case ImPlotCol_PlotBorder:    return ImGui::GetStyleColorVec4(ImGuiCol_Border);\n        case ImPlotCol_LegendBg:      return ImGui::GetStyleColorVec4(ImGuiCol_PopupBg);\n        case ImPlotCol_LegendBorder:  return GetStyleColorVec4(ImPlotCol_PlotBorder);\n        case ImPlotCol_LegendText:    return GetStyleColorVec4(ImPlotCol_InlayText);\n        case ImPlotCol_TitleText:     return ImGui::GetStyleColorVec4(ImGuiCol_Text);\n        case ImPlotCol_InlayText:     return ImGui::GetStyleColorVec4(ImGuiCol_Text);\n        case ImPlotCol_AxisText:      return ImGui::GetStyleColorVec4(ImGuiCol_Text);\n        case ImPlotCol_AxisGrid:      return GetStyleColorVec4(ImPlotCol_AxisText) * ImVec4(1,1,1,0.25f);\n        case ImPlotCol_AxisTick:      return GetStyleColorVec4(ImPlotCol_AxisGrid);\n        case ImPlotCol_AxisBg:        return ImVec4(0,0,0,0);\n        case ImPlotCol_AxisBgHovered: return ImGui::GetStyleColorVec4(ImGuiCol_ButtonHovered);\n        case ImPlotCol_AxisBgActive:  return ImGui::GetStyleColorVec4(ImGuiCol_ButtonActive);\n        case ImPlotCol_Selection:     return ImVec4(1,1,0,1);\n        case ImPlotCol_Crosshairs:    return GetStyleColorVec4(ImPlotCol_PlotBorder);\n        default: return col;\n    }\n}\n\nstruct ImPlotStyleVarInfo {\n    ImGuiDataType   Type;\n    ImU32           Count;\n    ImU32           Offset;\n    void*           GetVarPtr(ImPlotStyle* style) const { return (void*)((unsigned char*)style + Offset); }\n};\n\nstatic const ImPlotStyleVarInfo GPlotStyleVarInfo[] =\n{\n    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlotStyle, LineWeight)         }, // ImPlotStyleVar_LineWeight\n    { ImGuiDataType_S32,   1, (ImU32)IM_OFFSETOF(ImPlotStyle, Marker)             }, // ImPlotStyleVar_Marker\n    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlotStyle, MarkerSize)         }, // ImPlotStyleVar_MarkerSize\n    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlotStyle, MarkerWeight)       }, // ImPlotStyleVar_MarkerWeight\n    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlotStyle, FillAlpha)          }, // ImPlotStyleVar_FillAlpha\n    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlotStyle, ErrorBarSize)       }, // ImPlotStyleVar_ErrorBarSize\n    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlotStyle, ErrorBarWeight)     }, // ImPlotStyleVar_ErrorBarWeight\n    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlotStyle, DigitalBitHeight)   }, // ImPlotStyleVar_DigitalBitHeight\n    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlotStyle, DigitalBitGap)      }, // ImPlotStyleVar_DigitalBitGap\n\n    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlotStyle, PlotBorderSize)     }, // ImPlotStyleVar_PlotBorderSize\n    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImPlotStyle, MinorAlpha)         }, // ImPlotStyleVar_MinorAlpha\n    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, MajorTickLen)       }, // ImPlotStyleVar_MajorTickLen\n    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, MinorTickLen)       }, // ImPlotStyleVar_MinorTickLen\n    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, MajorTickSize)      }, // ImPlotStyleVar_MajorTickSize\n    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, MinorTickSize)      }, // ImPlotStyleVar_MinorTickSize\n    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, MajorGridSize)      }, // ImPlotStyleVar_MajorGridSize\n    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, MinorGridSize)      }, // ImPlotStyleVar_MinorGridSize\n    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, PlotPadding)        }, // ImPlotStyleVar_PlotPadding\n    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, LabelPadding)       }, // ImPlotStyleVar_LabelPaddine\n    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, LegendPadding)      }, // ImPlotStyleVar_LegendPadding\n    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, LegendInnerPadding) }, // ImPlotStyleVar_LegendInnerPadding\n    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, LegendSpacing)      }, // ImPlotStyleVar_LegendSpacing\n\n    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, MousePosPadding)    }, // ImPlotStyleVar_MousePosPadding\n    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, AnnotationPadding)  }, // ImPlotStyleVar_AnnotationPadding\n    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, FitPadding)         }, // ImPlotStyleVar_FitPadding\n    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, PlotDefaultSize)    }, // ImPlotStyleVar_PlotDefaultSize\n    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImPlotStyle, PlotMinSize)        }  // ImPlotStyleVar_PlotMinSize\n};\n\nstatic const ImPlotStyleVarInfo* GetPlotStyleVarInfo(ImPlotStyleVar idx) {\n    IM_ASSERT(idx >= 0 && idx < ImPlotStyleVar_COUNT);\n    IM_ASSERT(IM_ARRAYSIZE(GPlotStyleVarInfo) == ImPlotStyleVar_COUNT);\n    return &GPlotStyleVarInfo[idx];\n}\n\n//-----------------------------------------------------------------------------\n// Generic Helpers\n//-----------------------------------------------------------------------------\n\nvoid AddTextVertical(ImDrawList *DrawList, ImVec2 pos, ImU32 col, const char *text_begin, const char* text_end) {\n    // the code below is based loosely on ImFont::RenderText\n    if (!text_end)\n        text_end = text_begin + strlen(text_begin);\n    ImGuiContext& g = *GImGui;\n    ImFont* font = g.Font;\n    // Align to be pixel perfect\n    pos.x = IM_FLOOR(pos.x);\n    pos.y = IM_FLOOR(pos.y);\n    const float scale = g.FontSize / font->FontSize;\n    const char* s = text_begin;\n    int chars_exp = (int)(text_end - s);\n    int chars_rnd = 0;\n    const int vtx_count_max = chars_exp * 4;\n    const int idx_count_max = chars_exp * 6;\n    DrawList->PrimReserve(idx_count_max, vtx_count_max);\n    while (s < text_end) {\n        unsigned int c = (unsigned int)*s;\n        if (c < 0x80) {\n            s += 1;\n        }\n        else {\n            s += ImTextCharFromUtf8(&c, s, text_end);\n            if (c == 0) // Malformed UTF-8?\n                break;\n        }\n        const ImFontGlyph * glyph = font->FindGlyph((ImWchar)c);\n        if (glyph == NULL) {\n            continue;\n        }\n        DrawList->PrimQuadUV(pos + ImVec2(glyph->Y0, -glyph->X0) * scale, pos + ImVec2(glyph->Y0, -glyph->X1) * scale,\n                             pos + ImVec2(glyph->Y1, -glyph->X1) * scale, pos + ImVec2(glyph->Y1, -glyph->X0) * scale,\n                             ImVec2(glyph->U0, glyph->V0), ImVec2(glyph->U1, glyph->V0),\n                             ImVec2(glyph->U1, glyph->V1), ImVec2(glyph->U0, glyph->V1),\n                             col);\n        pos.y -= glyph->AdvanceX * scale;\n        chars_rnd++;\n    }\n    // Give back unused vertices\n    int chars_skp = chars_exp-chars_rnd;\n    DrawList->PrimUnreserve(chars_skp*6, chars_skp*4);\n}\n\nvoid AddTextCentered(ImDrawList* DrawList, ImVec2 top_center, ImU32 col, const char* text_begin, const char* text_end) {\n    float txt_ht = ImGui::GetTextLineHeight();\n    const char* title_end = ImGui::FindRenderedTextEnd(text_begin, text_end);\n    ImVec2 text_size;\n    float  y = 0;\n    while (const char* tmp = (const char*)memchr(text_begin, '\\n', title_end-text_begin)) {\n        text_size = ImGui::CalcTextSize(text_begin,tmp,true);\n        DrawList->AddText(ImVec2(top_center.x - text_size.x * 0.5f, top_center.y+y),col,text_begin,tmp);\n        text_begin = tmp + 1;\n        y += txt_ht;\n    }\n    text_size = ImGui::CalcTextSize(text_begin,title_end,true);\n    DrawList->AddText(ImVec2(top_center.x - text_size.x * 0.5f, top_center.y+y),col,text_begin,title_end);\n}\n\ndouble NiceNum(double x, bool round) {\n    double f;\n    double nf;\n    int expv = (int)floor(ImLog10(x));\n    f = x / ImPow(10.0, (double)expv);\n    if (round)\n        if (f < 1.5)\n            nf = 1;\n        else if (f < 3)\n            nf = 2;\n        else if (f < 7)\n            nf = 5;\n        else\n            nf = 10;\n    else if (f <= 1)\n        nf = 1;\n    else if (f <= 2)\n        nf = 2;\n    else if (f <= 5)\n        nf = 5;\n    else\n        nf = 10;\n    return nf * ImPow(10.0, expv);\n}\n\n//-----------------------------------------------------------------------------\n// Context Utils\n//-----------------------------------------------------------------------------\n\nvoid SetImGuiContext(ImGuiContext* ctx) {\n    ImGui::SetCurrentContext(ctx);\n}\n\nImPlotContext* CreateContext() {\n    ImPlotContext* ctx = IM_NEW(ImPlotContext)();\n    Initialize(ctx);\n    if (GImPlot == NULL)\n        SetCurrentContext(ctx);\n    return ctx;\n}\n\nvoid DestroyContext(ImPlotContext* ctx) {\n    if (ctx == NULL)\n        ctx = GImPlot;\n    if (GImPlot == ctx)\n        SetCurrentContext(NULL);\n    IM_DELETE(ctx);\n}\n\nImPlotContext* GetCurrentContext() {\n    return GImPlot;\n}\n\nvoid SetCurrentContext(ImPlotContext* ctx) {\n    GImPlot = ctx;\n}\n\n#define IMPLOT_APPEND_CMAP(name, qual) ctx->ColormapData.Append(#name, name, sizeof(name)/sizeof(ImU32), qual)\n#define IM_RGB(r,g,b) IM_COL32(r,g,b,255)\n\nvoid Initialize(ImPlotContext* ctx) {\n    ResetCtxForNextPlot(ctx);\n    ResetCtxForNextAlignedPlots(ctx);\n    ResetCtxForNextSubplot(ctx);\n\n    const ImU32 Deep[]     = {4289753676, 4283598045, 4285048917, 4283584196, 4289950337, 4284512403, 4291005402, 4287401100, 4285839820, 4291671396                        };\n    const ImU32 Dark[]     = {4280031972, 4290281015, 4283084621, 4288892568, 4278222847, 4281597951, 4280833702, 4290740727, 4288256409                                    };\n    const ImU32 Pastel[]   = {4289639675, 4293119411, 4291161036, 4293184478, 4289124862, 4291624959, 4290631909, 4293712637, 4294111986                                    };\n    const ImU32 Paired[]   = {4293119554, 4290017311, 4287291314, 4281114675, 4288256763, 4280031971, 4285513725, 4278222847, 4292260554, 4288298346, 4288282623, 4280834481};\n    const ImU32 Viridis[]  = {4283695428, 4285867080, 4287054913, 4287455029, 4287526954, 4287402273, 4286883874, 4285579076, 4283552122, 4280737725, 4280674301            };\n    const ImU32 Plasma[]   = {4287039501, 4288480321, 4289200234, 4288941455, 4287638193, 4286072780, 4284638433, 4283139314, 4281771772, 4280667900, 4280416752            };\n    const ImU32 Hot[]      = {4278190144, 4278190208, 4278190271, 4278190335, 4278206719, 4278223103, 4278239231, 4278255615, 4283826175, 4289396735, 4294967295            };\n    const ImU32 Cool[]     = {4294967040, 4294960666, 4294954035, 4294947661, 4294941030, 4294934656, 4294928025, 4294921651, 4294915020, 4294908646, 4294902015            };\n    const ImU32 Pink[]     = {4278190154, 4282532475, 4284308894, 4285690554, 4286879686, 4287870160, 4288794330, 4289651940, 4291685869, 4293392118, 4294967295            };\n    const ImU32 Jet[]      = {4289331200, 4294901760, 4294923520, 4294945280, 4294967040, 4289396565, 4283826090, 4278255615, 4278233855, 4278212095, 4278190335            };\n    const ImU32 Twilight[] = {IM_RGB(226,217,226),IM_RGB(166,191,202),IM_RGB(109,144,192),IM_RGB(95,88,176),IM_RGB(83,30,124),IM_RGB(47,20,54),IM_RGB(100,25,75),IM_RGB(159,60,80),IM_RGB(192,117,94),IM_RGB(208,179,158),IM_RGB(226,217,226)};\n    const ImU32 RdBu[]     = {IM_RGB(103,0,31),IM_RGB(178,24,43),IM_RGB(214,96,77),IM_RGB(244,165,130),IM_RGB(253,219,199),IM_RGB(247,247,247),IM_RGB(209,229,240),IM_RGB(146,197,222),IM_RGB(67,147,195),IM_RGB(33,102,172),IM_RGB(5,48,97)};\n    const ImU32 BrBG[]     = {IM_RGB(84,48,5),IM_RGB(140,81,10),IM_RGB(191,129,45),IM_RGB(223,194,125),IM_RGB(246,232,195),IM_RGB(245,245,245),IM_RGB(199,234,229),IM_RGB(128,205,193),IM_RGB(53,151,143),IM_RGB(1,102,94),IM_RGB(0,60,48)};\n    const ImU32 PiYG[]     = {IM_RGB(142,1,82),IM_RGB(197,27,125),IM_RGB(222,119,174),IM_RGB(241,182,218),IM_RGB(253,224,239),IM_RGB(247,247,247),IM_RGB(230,245,208),IM_RGB(184,225,134),IM_RGB(127,188,65),IM_RGB(77,146,33),IM_RGB(39,100,25)};\n    const ImU32 Spectral[] = {IM_RGB(158,1,66),IM_RGB(213,62,79),IM_RGB(244,109,67),IM_RGB(253,174,97),IM_RGB(254,224,139),IM_RGB(255,255,191),IM_RGB(230,245,152),IM_RGB(171,221,164),IM_RGB(102,194,165),IM_RGB(50,136,189),IM_RGB(94,79,162)};\n    const ImU32 Greys[]    = {IM_COL32_WHITE, IM_COL32_BLACK                                                                                                                };\n\n    IMPLOT_APPEND_CMAP(Deep, true);\n    IMPLOT_APPEND_CMAP(Dark, true);\n    IMPLOT_APPEND_CMAP(Pastel, true);\n    IMPLOT_APPEND_CMAP(Paired, true);\n    IMPLOT_APPEND_CMAP(Viridis, false);\n    IMPLOT_APPEND_CMAP(Plasma, false);\n    IMPLOT_APPEND_CMAP(Hot, false);\n    IMPLOT_APPEND_CMAP(Cool, false);\n    IMPLOT_APPEND_CMAP(Pink, false);\n    IMPLOT_APPEND_CMAP(Jet, false);\n    IMPLOT_APPEND_CMAP(Twilight, false);\n    IMPLOT_APPEND_CMAP(RdBu, false);\n    IMPLOT_APPEND_CMAP(BrBG, false);\n    IMPLOT_APPEND_CMAP(PiYG, false);\n    IMPLOT_APPEND_CMAP(Spectral, false);\n    IMPLOT_APPEND_CMAP(Greys, false);\n}\n\nvoid ResetCtxForNextPlot(ImPlotContext* ctx) {\n    // end child window if it was made\n    if (ctx->ChildWindowMade)\n        ImGui::EndChild();\n    ctx->ChildWindowMade = false;\n    // reset the next plot/item data\n    ctx->NextPlotData.Reset();\n    ctx->NextItemData.Reset();\n    // reset labels\n    ctx->Annotations.Reset();\n    ctx->Tags.Reset();\n    // reset extents/fit\n    ctx->OpenContextThisFrame = false;\n    // reset digital plot items count\n    ctx->DigitalPlotItemCnt = 0;\n    ctx->DigitalPlotOffset = 0;\n    // nullify plot\n    ctx->CurrentPlot  = NULL;\n    ctx->CurrentItem  = NULL;\n    ctx->PreviousItem = NULL;\n}\n\nvoid ResetCtxForNextAlignedPlots(ImPlotContext* ctx) {\n    ctx->CurrentAlignmentH = NULL;\n    ctx->CurrentAlignmentV = NULL;\n}\n\nvoid ResetCtxForNextSubplot(ImPlotContext* ctx) {\n    ctx->CurrentSubplot      = NULL;\n    ctx->CurrentAlignmentH   = NULL;\n    ctx->CurrentAlignmentV   = NULL;\n}\n\n//-----------------------------------------------------------------------------\n// Plot Utils\n//-----------------------------------------------------------------------------\n\nImPlotPlot* GetPlot(const char* title) {\n    ImGuiWindow*   Window = GImGui->CurrentWindow;\n    const ImGuiID  ID     = Window->GetID(title);\n    return GImPlot->Plots.GetByKey(ID);\n}\n\nImPlotPlot* GetCurrentPlot() {\n    return GImPlot->CurrentPlot;\n}\n\nvoid BustPlotCache() {\n    GImPlot->Plots.Clear();\n    GImPlot->Subplots.Clear();\n}\n\n//-----------------------------------------------------------------------------\n// Legend Utils\n//-----------------------------------------------------------------------------\n\nImVec2 GetLocationPos(const ImRect& outer_rect, const ImVec2& inner_size, ImPlotLocation loc, const ImVec2& pad) {\n    ImVec2 pos;\n    if (ImHasFlag(loc, ImPlotLocation_West) && !ImHasFlag(loc, ImPlotLocation_East))\n        pos.x = outer_rect.Min.x + pad.x;\n    else if (!ImHasFlag(loc, ImPlotLocation_West) && ImHasFlag(loc, ImPlotLocation_East))\n        pos.x = outer_rect.Max.x - pad.x - inner_size.x;\n    else\n        pos.x = outer_rect.GetCenter().x - inner_size.x * 0.5f;\n    // legend reference point y\n    if (ImHasFlag(loc, ImPlotLocation_North) && !ImHasFlag(loc, ImPlotLocation_South))\n        pos.y = outer_rect.Min.y + pad.y;\n    else if (!ImHasFlag(loc, ImPlotLocation_North) && ImHasFlag(loc, ImPlotLocation_South))\n        pos.y = outer_rect.Max.y - pad.y - inner_size.y;\n    else\n        pos.y = outer_rect.GetCenter().y - inner_size.y * 0.5f;\n    pos.x = IM_ROUND(pos.x);\n    pos.y = IM_ROUND(pos.y);\n    return pos;\n}\n\nImVec2 CalcLegendSize(ImPlotItemGroup& items, const ImVec2& pad, const ImVec2& spacing, bool vertical) {\n    // vars\n    const int   nItems      = items.GetLegendCount();\n    const float txt_ht      = ImGui::GetTextLineHeight();\n    const float icon_size   = txt_ht;\n    // get label max width\n    float max_label_width = 0;\n    float sum_label_width = 0;\n    for (int i = 0; i < nItems; ++i) {\n        const char* label       = items.GetLegendLabel(i);\n        const float label_width = ImGui::CalcTextSize(label, NULL, true).x;\n        max_label_width         = label_width > max_label_width ? label_width : max_label_width;\n        sum_label_width        += label_width;\n    }\n    // calc legend size\n    const ImVec2 legend_size = vertical ?\n                               ImVec2(pad.x * 2 + icon_size + max_label_width, pad.y * 2 + nItems * txt_ht + (nItems - 1) * spacing.y) :\n                               ImVec2(pad.x * 2 + icon_size * nItems + sum_label_width + (nItems - 1) * spacing.x, pad.y * 2 + txt_ht);\n    return legend_size;\n}\n\nint LegendSortingComp(void* _items, const void* _a, const void* _b) {\n    ImPlotItemGroup* items = (ImPlotItemGroup*)_items;\n    const int a = *(const int*)_a;\n    const int b = *(const int*)_b;\n    const char* label_a = items->GetLegendLabel(a);\n    const char* label_b = items->GetLegendLabel(b);\n    return strcmp(label_a,label_b);\n}\n\nbool ShowLegendEntries(ImPlotItemGroup& items, const ImRect& legend_bb, bool hovered, const ImVec2& pad, const ImVec2& spacing, bool vertical, ImDrawList& DrawList) {\n    // vars\n    const float txt_ht      = ImGui::GetTextLineHeight();\n    const float icon_size   = txt_ht;\n    const float icon_shrink = 2;\n    ImU32 col_txt           = GetStyleColorU32(ImPlotCol_LegendText);\n    ImU32  col_txt_dis      = ImAlphaU32(col_txt, 0.25f);\n    // render each legend item\n    float sum_label_width = 0;\n    bool any_item_hovered = false;\n\n    const int num_items = items.GetLegendCount();\n    if (num_items < 1)\n        return hovered;\n    // ImVector<int>& indices = GImPlot->TempInt1;\n    // indices.resize(num_items);\n    // // bool sort = true;\n    // // if (sort && num_items > 1) {\n    // //     qsort_s(indices.Data, num_items, sizeof(int), LegendSortingComp, &items);\n    // // }\n    // // else {\n    // //     for (int i = 0; i < num_items; ++i)\n    // //         indices[i] = i;\n    // // }\n    for (int i = 0; i < num_items; ++i) {\n        const int idx           = i; //indices[i];\n        ImPlotItem* item        = items.GetLegendItem(idx);\n        const char* label       = items.GetLegendLabel(idx);\n        const float label_width = ImGui::CalcTextSize(label, NULL, true).x;\n        const ImVec2 top_left   = vertical ?\n                                  legend_bb.Min + pad + ImVec2(0, i * (txt_ht + spacing.y)) :\n                                  legend_bb.Min + pad + ImVec2(i * (icon_size + spacing.x) + sum_label_width, 0);\n        sum_label_width        += label_width;\n        ImRect icon_bb;\n        icon_bb.Min = top_left + ImVec2(icon_shrink,icon_shrink);\n        icon_bb.Max = top_left + ImVec2(icon_size - icon_shrink, icon_size - icon_shrink);\n        ImRect label_bb;\n        label_bb.Min = top_left;\n        label_bb.Max = top_left + ImVec2(label_width + icon_size, icon_size);\n        ImU32 col_txt_hl;\n        ImU32 col_item = ImAlphaU32(item->Color,1);\n\n        ImRect button_bb(icon_bb.Min, label_bb.Max);\n\n\n        bool item_hov = false;\n        bool item_hld = false;\n        bool item_clk = ImHasFlag(items.Legend.Flags, ImPlotLegendFlags_NoButtons)\n                      ? false\n                      : ImGui::ButtonBehavior(button_bb, item->ID, &item_hov, &item_hld);\n\n        if (item_clk)\n            item->Show = !item->Show;\n\n\n        const bool can_hover = (item_hov)\n                             && (!ImHasFlag(items.Legend.Flags, ImPlotLegendFlags_NoHighlightItem)\n                             || !ImHasFlag(items.Legend.Flags, ImPlotLegendFlags_NoHighlightAxis));\n\n        if (can_hover) {\n            item->LegendHoverRect.Min = icon_bb.Min;\n            item->LegendHoverRect.Max = label_bb.Max;\n            item->LegendHovered = true;\n            col_txt_hl = ImMixU32(col_txt, col_item, 64);\n            any_item_hovered = true;\n        }\n        else {\n            col_txt_hl = ImGui::GetColorU32(col_txt);\n        }\n        ImU32 col_icon;\n        if (item_hld)\n            col_icon = item->Show ? ImAlphaU32(col_item,0.5f) : ImGui::GetColorU32(ImGuiCol_TextDisabled, 0.5f);\n        else if (item_hov)\n            col_icon = item->Show ? ImAlphaU32(col_item,0.75f) : ImGui::GetColorU32(ImGuiCol_TextDisabled, 0.75f);\n        else\n            col_icon = item->Show ? col_item : col_txt_dis;\n\n        DrawList.AddRectFilled(icon_bb.Min, icon_bb.Max, col_icon);\n        const char* text_display_end = ImGui::FindRenderedTextEnd(label, NULL);\n        if (label != text_display_end)\n            DrawList.AddText(top_left + ImVec2(icon_size, 0), item->Show ? col_txt_hl  : col_txt_dis, label, text_display_end);\n    }\n    return hovered && !any_item_hovered;\n}\n\n//-----------------------------------------------------------------------------\n// Tick Utils\n//-----------------------------------------------------------------------------\n\nstatic const float TICK_FILL_X = 0.8f;\nstatic const float TICK_FILL_Y = 1.0f;\n\nvoid AddTicksDefault(const ImPlotRange& range, float pix, bool vertical, ImPlotTickCollection& ticks, ImPlotFormatter formatter, void* data) {\n    const int idx0          = ticks.Size;\n    const int nMinor        = 10;\n    const int nMajor        = ImMax(2, (int)IM_ROUND(pix / (vertical ? 300.0f : 400.0f)));\n    const double nice_range = NiceNum(range.Size() * 0.99, false);\n    const double interval   = NiceNum(nice_range / (nMajor - 1), true);\n    const double graphmin   = floor(range.Min / interval) * interval;\n    const double graphmax   = ceil(range.Max / interval) * interval;\n    bool first_major_set    = false;\n    int  first_major_idx    = 0;\n    ImVec2 total_size(0,0);\n    for (double major = graphmin; major < graphmax + 0.5 * interval; major += interval) {\n        // is this zero? combat zero formatting issues\n        if (major-interval < 0 && major+interval > 0)\n            major = 0;\n        if (range.Contains(major)) {\n            if (!first_major_set) {\n                first_major_idx = ticks.Size;\n                first_major_set = true;\n            }\n            total_size += ticks.Append(major, true, true, formatter, data).LabelSize;\n        }\n        for (int i = 1; i < nMinor; ++i) {\n            double minor = major + i * interval / nMinor;\n            if (range.Contains(minor)) {\n                total_size += ticks.Append(minor, false, true, formatter, data).LabelSize;\n            }\n        }\n    }\n    // prune if necessary\n    if ((!vertical && total_size.x > pix*TICK_FILL_X) || (vertical && total_size.y > pix*TICK_FILL_Y)) {\n        for (int i = first_major_idx-1; i >= idx0; i -= 2)\n            ticks.Ticks[i].ShowLabel = false;\n        for (int i = first_major_idx+1; i < ticks.Size; i += 2)\n            ticks.Ticks[i].ShowLabel = false;\n    }\n}\n\nvoid AddTicksLogarithmic(const ImPlotRange& range, float pix, bool vertical, ImPlotTickCollection& ticks, ImPlotFormatter formatter, void* data) {\n    if (range.Min <= 0 || range.Max <= 0)\n        return;\n    const int nMajor = vertical ? ImMax(2, (int)IM_ROUND(pix * 0.02f)) : ImMax(2, (int)IM_ROUND(pix * 0.01f));\n    double log_min = ImLog10(range.Min);\n    double log_max = ImLog10(range.Max);\n    int exp_step  = ImMax(1,(int)(log_max - log_min) / nMajor);\n    int exp_min   = (int)log_min;\n    int exp_max   = (int)log_max;\n    if (exp_step != 1) {\n        while(exp_step % 3 != 0)       exp_step++; // make step size multiple of three\n        while(exp_min % exp_step != 0) exp_min--;  // decrease exp_min until exp_min + N * exp_step will be 0\n    }\n    for (int e = exp_min - exp_step; e < (exp_max + exp_step); e += exp_step) {\n        double major1 = ImPow(10, (double)(e));\n        double major2 = ImPow(10, (double)(e + 1));\n        double interval = (major2 - major1) / 9;\n        if (major1 >= (range.Min - DBL_EPSILON) && major1 <= (range.Max + DBL_EPSILON))\n            ticks.Append(major1, true, true, formatter, data);\n        for (int j = 0; j < exp_step; ++j) {\n            major1 = ImPow(10, (double)(e+j));\n            major2 = ImPow(10, (double)(e+j+1));\n            interval = (major2 - major1) / 9;\n            for (int i = 1; i < (9 + (int)(j < (exp_step - 1))); ++i) {\n                double minor = major1 + i * interval;\n                if (minor >= (range.Min - DBL_EPSILON) && minor <= (range.Max + DBL_EPSILON))\n                    ticks.Append(minor, false, false, formatter, data);\n\n            }\n        }\n    }\n}\n\nvoid AddTicksCustom(const double* values, const char* const labels[], int n, ImPlotTickCollection& ticks, ImPlotFormatter formatter, void* data) {\n    for (int i = 0; i < n; ++i) {\n        if (labels != NULL) {\n            ImPlotTick tick(values[i], false, true);\n            tick.TextOffset = ticks.TextBuffer.size();\n            ticks.TextBuffer.append(labels[i], labels[i] + strlen(labels[i]) + 1);\n            tick.LabelSize = ImGui::CalcTextSize(labels[i]);\n            ticks.Append(tick);\n        }\n        else {\n            ticks.Append(values[i], false, true, formatter, data);\n        }\n    }\n}\n\n//-----------------------------------------------------------------------------\n// Time Ticks and Utils\n//-----------------------------------------------------------------------------\n\n// this may not be thread safe?\nstatic const double TimeUnitSpans[ImPlotTimeUnit_COUNT] = {\n    0.000001,\n    0.001,\n    1,\n    60,\n    3600,\n    86400,\n    2629800,\n    31557600\n};\n\ninline ImPlotTimeUnit GetUnitForRange(double range) {\n    static double cutoffs[ImPlotTimeUnit_COUNT] = {0.001, 1, 60, 3600, 86400, 2629800, 31557600, IMPLOT_MAX_TIME};\n    for (int i = 0; i < ImPlotTimeUnit_COUNT; ++i) {\n        if (range <= cutoffs[i])\n            return (ImPlotTimeUnit)i;\n    }\n    return ImPlotTimeUnit_Yr;\n}\n\ninline int LowerBoundStep(int max_divs, const int* divs, const int* step, int size) {\n    if (max_divs < divs[0])\n        return 0;\n    for (int i = 1; i < size; ++i) {\n        if (max_divs < divs[i])\n            return step[i-1];\n    }\n    return step[size-1];\n}\n\ninline int GetTimeStep(int max_divs, ImPlotTimeUnit unit) {\n    if (unit == ImPlotTimeUnit_Ms || unit == ImPlotTimeUnit_Us) {\n        static const int step[] = {500,250,200,100,50,25,20,10,5,2,1};\n        static const int divs[] = {2,4,5,10,20,40,50,100,200,500,1000};\n        return LowerBoundStep(max_divs, divs, step, 11);\n    }\n    if (unit == ImPlotTimeUnit_S || unit == ImPlotTimeUnit_Min) {\n        static const int step[] = {30,15,10,5,1};\n        static const int divs[] = {2,4,6,12,60};\n        return LowerBoundStep(max_divs, divs, step, 5);\n    }\n    else if (unit == ImPlotTimeUnit_Hr) {\n        static const int step[] = {12,6,3,2,1};\n        static const int divs[] = {2,4,8,12,24};\n        return LowerBoundStep(max_divs, divs, step, 5);\n    }\n    else if (unit == ImPlotTimeUnit_Day) {\n        static const int step[] = {14,7,2,1};\n        static const int divs[] = {2,4,14,28};\n        return LowerBoundStep(max_divs, divs, step, 4);\n    }\n    else if (unit == ImPlotTimeUnit_Mo) {\n        static const int step[] = {6,3,2,1};\n        static const int divs[] = {2,4,6,12};\n        return LowerBoundStep(max_divs, divs, step, 4);\n    }\n    return 0;\n}\n\nImPlotTime MkGmtTime(struct tm *ptm) {\n    ImPlotTime t;\n#ifdef _WIN32\n    t.S = _mkgmtime(ptm);\n#else\n    t.S = timegm(ptm);\n#endif\n    if (t.S < 0)\n        t.S = 0;\n    return t;\n}\n\ntm* GetGmtTime(const ImPlotTime& t, tm* ptm)\n{\n#ifdef _WIN32\n  if (gmtime_s(ptm, &t.S) == 0)\n    return ptm;\n  else\n    return NULL;\n#else\n  return gmtime_r(&t.S, ptm);\n#endif\n}\n\nImPlotTime MkLocTime(struct tm *ptm) {\n    ImPlotTime t;\n    t.S = mktime(ptm);\n    if (t.S < 0)\n        t.S = 0;\n    return t;\n}\n\ntm* GetLocTime(const ImPlotTime& t, tm* ptm) {\n#ifdef _WIN32\n  if (localtime_s(ptm, &t.S) == 0)\n    return ptm;\n  else\n    return NULL;\n#else\n    return localtime_r(&t.S, ptm);\n#endif\n}\n\ninline ImPlotTime MkTime(struct tm *ptm) {\n    if (GetStyle().UseLocalTime)\n        return MkLocTime(ptm);\n    else\n        return MkGmtTime(ptm);\n}\n\ninline tm* GetTime(const ImPlotTime& t, tm* ptm) {\n    if (GetStyle().UseLocalTime)\n        return GetLocTime(t,ptm);\n    else\n        return GetGmtTime(t,ptm);\n}\n\nImPlotTime MakeTime(int year, int month, int day, int hour, int min, int sec, int us) {\n    tm& Tm = GImPlot->Tm;\n\n    int yr = year - 1900;\n    if (yr < 0)\n        yr = 0;\n\n    sec  = sec + us / 1000000;\n    us   = us % 1000000;\n\n    Tm.tm_sec  = sec;\n    Tm.tm_min  = min;\n    Tm.tm_hour = hour;\n    Tm.tm_mday = day;\n    Tm.tm_mon  = month;\n    Tm.tm_year = yr;\n\n    ImPlotTime t = MkTime(&Tm);\n\n    t.Us = us;\n    return t;\n}\n\nint GetYear(const ImPlotTime& t) {\n    tm& Tm = GImPlot->Tm;\n    GetTime(t, &Tm);\n    return Tm.tm_year + 1900;\n}\n\nImPlotTime AddTime(const ImPlotTime& t, ImPlotTimeUnit unit, int count) {\n    tm& Tm = GImPlot->Tm;\n    ImPlotTime t_out = t;\n    switch(unit) {\n        case ImPlotTimeUnit_Us:  t_out.Us += count;         break;\n        case ImPlotTimeUnit_Ms:  t_out.Us += count * 1000;  break;\n        case ImPlotTimeUnit_S:   t_out.S  += count;         break;\n        case ImPlotTimeUnit_Min: t_out.S  += count * 60;    break;\n        case ImPlotTimeUnit_Hr:  t_out.S  += count * 3600;  break;\n        case ImPlotTimeUnit_Day: t_out.S  += count * 86400; break;\n        case ImPlotTimeUnit_Mo:  for (int i = 0; i < abs(count); ++i) {\n                                     GetTime(t_out, &Tm);\n                                     if (count > 0)\n                                        t_out.S += 86400 * GetDaysInMonth(Tm.tm_year + 1900, Tm.tm_mon);\n                                     else if (count < 0)\n                                        t_out.S -= 86400 * GetDaysInMonth(Tm.tm_year + 1900 - (Tm.tm_mon == 0 ? 1 : 0), Tm.tm_mon == 0 ? 11 : Tm.tm_mon - 1); // NOT WORKING\n                                 }\n                                 break;\n        case ImPlotTimeUnit_Yr:  for (int i = 0; i < abs(count); ++i) {\n                                    if (count > 0)\n                                        t_out.S += 86400 * (365 + (int)IsLeapYear(GetYear(t_out)));\n                                    else if (count < 0)\n                                        t_out.S -= 86400 * (365 + (int)IsLeapYear(GetYear(t_out) - 1));\n                                    // this is incorrect if leap year and we are past Feb 28\n                                 }\n                                 break;\n        default:                 break;\n    }\n    t_out.RollOver();\n    return t_out;\n}\n\nImPlotTime FloorTime(const ImPlotTime& t, ImPlotTimeUnit unit) {\n    GetTime(t, &GImPlot->Tm);\n    switch (unit) {\n        case ImPlotTimeUnit_S:   return ImPlotTime(t.S, 0);\n        case ImPlotTimeUnit_Ms:  return ImPlotTime(t.S, (t.Us / 1000) * 1000);\n        case ImPlotTimeUnit_Us:  return t;\n        case ImPlotTimeUnit_Yr:  GImPlot->Tm.tm_mon  = 0; // fall-through\n        case ImPlotTimeUnit_Mo:  GImPlot->Tm.tm_mday = 1; // fall-through\n        case ImPlotTimeUnit_Day: GImPlot->Tm.tm_hour = 0; // fall-through\n        case ImPlotTimeUnit_Hr:  GImPlot->Tm.tm_min  = 0; // fall-through\n        case ImPlotTimeUnit_Min: GImPlot->Tm.tm_sec  = 0; break;\n        default:                 return t;\n    }\n    return MkTime(&GImPlot->Tm);\n}\n\nImPlotTime CeilTime(const ImPlotTime& t, ImPlotTimeUnit unit) {\n    return AddTime(FloorTime(t, unit), unit, 1);\n}\n\nImPlotTime RoundTime(const ImPlotTime& t, ImPlotTimeUnit unit) {\n    ImPlotTime t1 = FloorTime(t, unit);\n    ImPlotTime t2 = AddTime(t1,unit,1);\n    if (t1.S == t2.S)\n        return t.Us - t1.Us < t2.Us - t.Us ? t1 : t2;\n    return t.S - t1.S < t2.S - t.S ? t1 : t2;\n}\n\nImPlotTime CombineDateTime(const ImPlotTime& date_part, const ImPlotTime& tod_part) {\n    tm& Tm = GImPlot->Tm;\n    GetTime(date_part, &GImPlot->Tm);\n    int y = Tm.tm_year;\n    int m = Tm.tm_mon;\n    int d = Tm.tm_mday;\n    GetTime(tod_part, &GImPlot->Tm);\n    Tm.tm_year = y;\n    Tm.tm_mon  = m;\n    Tm.tm_mday = d;\n    ImPlotTime t = MkTime(&Tm);\n    t.Us = tod_part.Us;\n    return t;\n}\n\n// TODO: allow users to define these\nstatic const char* MONTH_NAMES[]  = {\"January\",\"February\",\"March\",\"April\",\"May\",\"June\",\"July\",\"August\",\"September\",\"October\",\"November\",\"December\"};\nstatic const char* WD_ABRVS[]     = {\"Su\",\"Mo\",\"Tu\",\"We\",\"Th\",\"Fr\",\"Sa\"};\nstatic const char* MONTH_ABRVS[]  = {\"Jan\",\"Feb\",\"Mar\",\"Apr\",\"May\",\"Jun\",\"Jul\",\"Aug\",\"Sep\",\"Oct\",\"Nov\",\"Dec\"};\n\nint FormatTime(const ImPlotTime& t, char* buffer, int size, ImPlotTimeFmt fmt, bool use_24_hr_clk) {\n    tm& Tm = GImPlot->Tm;\n    GetTime(t, &Tm);\n    const int us   = t.Us % 1000;\n    const int ms   = t.Us / 1000;\n    const int sec  = Tm.tm_sec;\n    const int min  = Tm.tm_min;\n    if (use_24_hr_clk) {\n        const int hr   = Tm.tm_hour;\n        switch(fmt) {\n            case ImPlotTimeFmt_Us:        return ImFormatString(buffer, size, \".%03d %03d\", ms, us);\n            case ImPlotTimeFmt_SUs:       return ImFormatString(buffer, size, \":%02d.%03d %03d\", sec, ms, us);\n            case ImPlotTimeFmt_SMs:       return ImFormatString(buffer, size, \":%02d.%03d\", sec, ms);\n            case ImPlotTimeFmt_S:         return ImFormatString(buffer, size, \":%02d\", sec);\n            case ImPlotTimeFmt_HrMinSMs:  return ImFormatString(buffer, size, \"%02d:%02d:%02d.%03d\", hr, min, sec, ms);\n            case ImPlotTimeFmt_HrMinS:    return ImFormatString(buffer, size, \"%02d:%02d:%02d\", hr, min, sec);\n            case ImPlotTimeFmt_HrMin:     return ImFormatString(buffer, size, \"%02d:%02d\", hr, min);\n            case ImPlotTimeFmt_Hr:        return ImFormatString(buffer, size, \"%02d:00\", hr);\n            default:                      return 0;\n        }\n    }\n    else {\n        const char* ap = Tm.tm_hour < 12 ? \"am\" : \"pm\";\n        const int hr   = (Tm.tm_hour == 0 || Tm.tm_hour == 12) ? 12 : Tm.tm_hour % 12;\n        switch(fmt) {\n            case ImPlotTimeFmt_Us:        return ImFormatString(buffer, size, \".%03d %03d\", ms, us);\n            case ImPlotTimeFmt_SUs:       return ImFormatString(buffer, size, \":%02d.%03d %03d\", sec, ms, us);\n            case ImPlotTimeFmt_SMs:       return ImFormatString(buffer, size, \":%02d.%03d\", sec, ms);\n            case ImPlotTimeFmt_S:         return ImFormatString(buffer, size, \":%02d\", sec);\n            case ImPlotTimeFmt_HrMinSMs:  return ImFormatString(buffer, size, \"%d:%02d:%02d.%03d%s\", hr, min, sec, ms, ap);\n            case ImPlotTimeFmt_HrMinS:    return ImFormatString(buffer, size, \"%d:%02d:%02d%s\", hr, min, sec, ap);\n            case ImPlotTimeFmt_HrMin:     return ImFormatString(buffer, size, \"%d:%02d%s\", hr, min, ap);\n            case ImPlotTimeFmt_Hr:        return ImFormatString(buffer, size, \"%d%s\", hr, ap);\n            default:                      return 0;\n        }\n    }\n}\n\nint FormatDate(const ImPlotTime& t, char* buffer, int size, ImPlotDateFmt fmt, bool use_iso_8601) {\n    tm& Tm = GImPlot->Tm;\n    GetTime(t, &Tm);\n    const int day  = Tm.tm_mday;\n    const int mon  = Tm.tm_mon + 1;\n    const int year = Tm.tm_year + 1900;\n    const int yr   = year % 100;\n    if (use_iso_8601) {\n        switch (fmt) {\n            case ImPlotDateFmt_DayMo:   return ImFormatString(buffer, size, \"--%02d-%02d\", mon, day);\n            case ImPlotDateFmt_DayMoYr: return ImFormatString(buffer, size, \"%d-%02d-%02d\", year, mon, day);\n            case ImPlotDateFmt_MoYr:    return ImFormatString(buffer, size, \"%d-%02d\", year, mon);\n            case ImPlotDateFmt_Mo:      return ImFormatString(buffer, size, \"--%02d\", mon);\n            case ImPlotDateFmt_Yr:      return ImFormatString(buffer, size, \"%d\", year);\n            default:                    return 0;\n        }\n    }\n    else {\n        switch (fmt) {\n            case ImPlotDateFmt_DayMo:   return ImFormatString(buffer, size, \"%d/%d\", mon, day);\n            case ImPlotDateFmt_DayMoYr: return ImFormatString(buffer, size, \"%d/%d/%02d\", mon, day, yr);\n            case ImPlotDateFmt_MoYr:    return ImFormatString(buffer, size, \"%s %d\", MONTH_ABRVS[Tm.tm_mon], year);\n            case ImPlotDateFmt_Mo:      return ImFormatString(buffer, size, \"%s\", MONTH_ABRVS[Tm.tm_mon]);\n            case ImPlotDateFmt_Yr:      return ImFormatString(buffer, size, \"%d\", year);\n            default:                    return 0;\n        }\n    }\n }\n\nint FormatDateTime(const ImPlotTime& t, char* buffer, int size, ImPlotDateTimeFmt fmt) {\n    int written = 0;\n    if (fmt.Date != ImPlotDateFmt_None)\n        written += FormatDate(t, buffer, size, fmt.Date, fmt.UseISO8601);\n    if (fmt.Time != ImPlotTimeFmt_None) {\n        if (fmt.Date != ImPlotDateFmt_None)\n            buffer[written++] = ' ';\n        written += FormatTime(t, &buffer[written], size - written, fmt.Time, fmt.Use24HourClock);\n    }\n    return written;\n}\n\ninline float GetDateTimeWidth(ImPlotDateTimeFmt fmt) {\n    static const ImPlotTime t_max_width = MakeTime(2888, 12, 22, 12, 58, 58, 888888); // best guess at time that maximizes pixel width\n    char buffer[32];\n    FormatDateTime(t_max_width, buffer, 32, fmt);\n    return ImGui::CalcTextSize(buffer).x;\n}\n\nvoid LabelTickTime(ImPlotTick& tick, ImGuiTextBuffer& buffer, const ImPlotTime& t, ImPlotDateTimeFmt fmt) {\n    char temp[32];\n    if (tick.ShowLabel) {\n        tick.TextOffset = buffer.size();\n        FormatDateTime(t, temp, 32, fmt);\n        buffer.append(temp, temp + strlen(temp) + 1);\n        tick.LabelSize = ImGui::CalcTextSize(buffer.Buf.Data + tick.TextOffset);\n    }\n}\n\ninline bool TimeLabelSame(const char* l1, const char* l2) {\n    size_t len1 = strlen(l1);\n    size_t len2 = strlen(l2);\n    size_t n  = len1 < len2 ? len1 : len2;\n    return strcmp(l1 + len1 - n, l2 + len2 - n) == 0;\n}\n\nstatic const ImPlotDateTimeFmt TimeFormatLevel0[ImPlotTimeUnit_COUNT] = {\n    ImPlotDateTimeFmt(ImPlotDateFmt_None,  ImPlotTimeFmt_Us),\n    ImPlotDateTimeFmt(ImPlotDateFmt_None,  ImPlotTimeFmt_SMs),\n    ImPlotDateTimeFmt(ImPlotDateFmt_None,  ImPlotTimeFmt_S),\n    ImPlotDateTimeFmt(ImPlotDateFmt_None,  ImPlotTimeFmt_HrMin),\n    ImPlotDateTimeFmt(ImPlotDateFmt_None,  ImPlotTimeFmt_Hr),\n    ImPlotDateTimeFmt(ImPlotDateFmt_DayMo, ImPlotTimeFmt_None),\n    ImPlotDateTimeFmt(ImPlotDateFmt_Mo,    ImPlotTimeFmt_None),\n    ImPlotDateTimeFmt(ImPlotDateFmt_Yr,    ImPlotTimeFmt_None)\n};\n\nstatic const ImPlotDateTimeFmt TimeFormatLevel1[ImPlotTimeUnit_COUNT] = {\n    ImPlotDateTimeFmt(ImPlotDateFmt_None,    ImPlotTimeFmt_HrMin),\n    ImPlotDateTimeFmt(ImPlotDateFmt_None,    ImPlotTimeFmt_HrMinS),\n    ImPlotDateTimeFmt(ImPlotDateFmt_None,    ImPlotTimeFmt_HrMin),\n    ImPlotDateTimeFmt(ImPlotDateFmt_None,    ImPlotTimeFmt_HrMin),\n    ImPlotDateTimeFmt(ImPlotDateFmt_DayMoYr, ImPlotTimeFmt_None),\n    ImPlotDateTimeFmt(ImPlotDateFmt_DayMoYr, ImPlotTimeFmt_None),\n    ImPlotDateTimeFmt(ImPlotDateFmt_Yr,      ImPlotTimeFmt_None),\n    ImPlotDateTimeFmt(ImPlotDateFmt_Yr,      ImPlotTimeFmt_None)\n};\n\nstatic const ImPlotDateTimeFmt TimeFormatLevel1First[ImPlotTimeUnit_COUNT] = {\n    ImPlotDateTimeFmt(ImPlotDateFmt_DayMoYr, ImPlotTimeFmt_HrMinS),\n    ImPlotDateTimeFmt(ImPlotDateFmt_DayMoYr, ImPlotTimeFmt_HrMinS),\n    ImPlotDateTimeFmt(ImPlotDateFmt_DayMoYr, ImPlotTimeFmt_HrMin),\n    ImPlotDateTimeFmt(ImPlotDateFmt_DayMoYr, ImPlotTimeFmt_HrMin),\n    ImPlotDateTimeFmt(ImPlotDateFmt_DayMoYr, ImPlotTimeFmt_None),\n    ImPlotDateTimeFmt(ImPlotDateFmt_DayMoYr, ImPlotTimeFmt_None),\n    ImPlotDateTimeFmt(ImPlotDateFmt_Yr,      ImPlotTimeFmt_None),\n    ImPlotDateTimeFmt(ImPlotDateFmt_Yr,      ImPlotTimeFmt_None)\n};\n\nstatic const ImPlotDateTimeFmt TimeFormatMouseCursor[ImPlotTimeUnit_COUNT] = {\n    ImPlotDateTimeFmt(ImPlotDateFmt_None,     ImPlotTimeFmt_Us),\n    ImPlotDateTimeFmt(ImPlotDateFmt_None,     ImPlotTimeFmt_SUs),\n    ImPlotDateTimeFmt(ImPlotDateFmt_None,     ImPlotTimeFmt_SMs),\n    ImPlotDateTimeFmt(ImPlotDateFmt_None,     ImPlotTimeFmt_HrMinS),\n    ImPlotDateTimeFmt(ImPlotDateFmt_None,     ImPlotTimeFmt_HrMin),\n    ImPlotDateTimeFmt(ImPlotDateFmt_DayMo,    ImPlotTimeFmt_Hr),\n    ImPlotDateTimeFmt(ImPlotDateFmt_DayMoYr,  ImPlotTimeFmt_None),\n    ImPlotDateTimeFmt(ImPlotDateFmt_MoYr,     ImPlotTimeFmt_None)\n};\n\ninline ImPlotDateTimeFmt GetDateTimeFmt(const ImPlotDateTimeFmt* ctx, ImPlotTimeUnit idx) {\n    ImPlotStyle& style     = GetStyle();\n    ImPlotDateTimeFmt fmt  = ctx[idx];\n    fmt.UseISO8601         = style.UseISO8601;\n    fmt.Use24HourClock     = style.Use24HourClock;\n    return fmt;\n}\n\nvoid AddTicksTime(const ImPlotRange& range, float plot_width, ImPlotTickCollection& ticks) {\n    // get units for level 0 and level 1 labels\n    const ImPlotTimeUnit unit0 = GetUnitForRange(range.Size() / (plot_width / 100)); // level = 0 (top)\n    const ImPlotTimeUnit unit1 = unit0 + 1;                                          // level = 1 (bottom)\n    // get time format specs\n    const ImPlotDateTimeFmt fmt0 = GetDateTimeFmt(TimeFormatLevel0, unit0);\n    const ImPlotDateTimeFmt fmt1 = GetDateTimeFmt(TimeFormatLevel1, unit1);\n    const ImPlotDateTimeFmt fmtf = GetDateTimeFmt(TimeFormatLevel1First, unit1);\n    // min max times\n    const ImPlotTime t_min = ImPlotTime::FromDouble(range.Min);\n    const ImPlotTime t_max = ImPlotTime::FromDouble(range.Max);\n    // maximum allowable density of labels\n    const float max_density = 0.5f;\n    // book keeping\n    const char* last_major  = NULL;\n    if (unit0 != ImPlotTimeUnit_Yr) {\n        // pixels per major (level 1) division\n        const float pix_per_major_div = plot_width / (float)(range.Size() / TimeUnitSpans[unit1]);\n        // nominal pixels taken up by labels\n        const float fmt0_width = GetDateTimeWidth(fmt0);\n        const float fmt1_width = GetDateTimeWidth(fmt1);\n        const float fmtf_width = GetDateTimeWidth(fmtf);\n        // the maximum number of minor (level 0) labels that can fit between major (level 1) divisions\n        const int   minor_per_major   = (int)(max_density * pix_per_major_div / fmt0_width);\n        // the minor step size (level 0)\n        const int step = GetTimeStep(minor_per_major, unit0);\n        // generate ticks\n        ImPlotTime t1 = FloorTime(ImPlotTime::FromDouble(range.Min), unit1);\n        while (t1 < t_max) {\n            // get next major\n            const ImPlotTime t2 = AddTime(t1, unit1, 1);\n            // add major tick\n            if (t1 >= t_min && t1 <= t_max) {\n                // minor level 0 tick\n                ImPlotTick tick_min(t1.ToDouble(),true,true);\n                tick_min.Level = 0;\n                LabelTickTime(tick_min,ticks.TextBuffer,t1,fmt0);\n                ticks.Append(tick_min);\n                // major level 1 tick\n                ImPlotTick tick_maj(t1.ToDouble(),true,true);\n                tick_maj.Level = 1;\n                LabelTickTime(tick_maj,ticks.TextBuffer,t1, last_major == NULL ? fmtf : fmt1);\n                const char* this_major = ticks.TextBuffer.Buf.Data + tick_maj.TextOffset;\n                if (last_major && TimeLabelSame(last_major,this_major))\n                    tick_maj.ShowLabel = false;\n                last_major = this_major;\n                ticks.Append(tick_maj);\n            }\n            // add minor ticks up until next major\n            if (minor_per_major > 1 && (t_min <= t2 && t1 <= t_max)) {\n                ImPlotTime t12 = AddTime(t1, unit0, step);\n                while (t12 < t2) {\n                    float px_to_t2 = (float)((t2 - t12).ToDouble()/range.Size()) * plot_width;\n                    if (t12 >= t_min && t12 <= t_max) {\n                        ImPlotTick tick(t12.ToDouble(),false,px_to_t2 >= fmt0_width);\n                        tick.Level =  0;\n                        LabelTickTime(tick,ticks.TextBuffer,t12,fmt0);\n                        ticks.Append(tick);\n                        if (last_major == NULL && px_to_t2 >= fmt0_width && px_to_t2 >= (fmt1_width + fmtf_width) / 2) {\n                            ImPlotTick tick_maj(t12.ToDouble(),true,true);\n                            tick_maj.Level = 1;\n                            LabelTickTime(tick_maj,ticks.TextBuffer,t12,fmtf);\n                            last_major = ticks.TextBuffer.Buf.Data + tick_maj.TextOffset;\n                            ticks.Append(tick_maj);\n                        }\n                    }\n                    t12 = AddTime(t12, unit0, step);\n                }\n            }\n            t1 = t2;\n        }\n    }\n    else {\n        const ImPlotDateTimeFmt fmty = GetDateTimeFmt(TimeFormatLevel0, ImPlotTimeUnit_Yr);\n        const float label_width = GetDateTimeWidth(fmty);\n        const int   max_labels  = (int)(max_density * plot_width / label_width);\n        const int year_min      = GetYear(t_min);\n        const int year_max      = GetYear(CeilTime(t_max, ImPlotTimeUnit_Yr));\n        const double nice_range = NiceNum((year_max - year_min)*0.99,false);\n        const double interval   = NiceNum(nice_range / (max_labels - 1), true);\n        const int graphmin      = (int)(floor(year_min / interval) * interval);\n        const int graphmax      = (int)(ceil(year_max  / interval) * interval);\n        const int step          = (int)interval <= 0 ? 1 : (int)interval;\n\n        for (int y = graphmin; y < graphmax; y += step) {\n            ImPlotTime t = MakeTime(y);\n            if (t >= t_min && t <= t_max) {\n                ImPlotTick tick(t.ToDouble(), true, true);\n                tick.Level = 0;\n                LabelTickTime(tick, ticks.TextBuffer, t, fmty);\n                ticks.Append(tick);\n            }\n        }\n    }\n}\n\n//-----------------------------------------------------------------------------\n// Context Menu\n//-----------------------------------------------------------------------------\n\ntemplate <typename F>\nbool DragFloat(const char*, F*, float, F, F) {\n    return false;\n}\n\ntemplate <>\nbool DragFloat<double>(const char* label, double* v, float v_speed, double v_min, double v_max) {\n    return ImGui::DragScalar(label, ImGuiDataType_Double, v, v_speed, &v_min, &v_max, \"%.3f\", 1);\n}\n\ntemplate <>\nbool DragFloat<float>(const char* label, float* v, float v_speed, float v_min, float v_max) {\n    return ImGui::DragScalar(label, ImGuiDataType_Float, v, v_speed, &v_min, &v_max, \"%.3f\", 1);\n}\n\ninline void BeginDisabledControls(bool cond) {\n    if (cond) {\n        ImGui::PushItemFlag(ImGuiItemFlags_Disabled, true);\n        ImGui::PushStyleVar(ImGuiStyleVar_Alpha, ImGui::GetStyle().Alpha * 0.25f);\n    }\n}\n\ninline void EndDisabledControls(bool cond) {\n    if (cond) {\n        ImGui::PopItemFlag();\n        ImGui::PopStyleVar();\n    }\n}\n\nvoid ShowAxisContextMenu(ImPlotAxis& axis, ImPlotAxis* equal_axis, bool time_allowed) {\n\n    ImGui::PushItemWidth(75);\n    bool always_locked   = axis.IsRangeLocked() || axis.IsAutoFitting();\n    bool label           = axis.HasLabel();\n    bool grid            = axis.HasGridLines();\n    bool ticks           = axis.HasTickMarks();\n    bool labels          = axis.HasTickLabels();\n    double drag_speed    = (axis.Range.Size() <= DBL_EPSILON) ? DBL_EPSILON * 1.0e+13 : 0.01 * axis.Range.Size(); // recover from almost equal axis limits.\n\n    if (axis.IsTime()) {\n        ImPlotTime tmin = ImPlotTime::FromDouble(axis.Range.Min);\n        ImPlotTime tmax = ImPlotTime::FromDouble(axis.Range.Max);\n\n        BeginDisabledControls(always_locked);\n        ImGui::CheckboxFlags(\"##LockMin\", (unsigned int*)&axis.Flags, ImPlotAxisFlags_LockMin);\n        EndDisabledControls(always_locked);\n        ImGui::SameLine();\n        BeginDisabledControls(axis.IsLockedMin() || always_locked);\n        if (ImGui::BeginMenu(\"Min Time\")) {\n            if (ShowTimePicker(\"mintime\", &tmin)) {\n                if (tmin >= tmax)\n                    tmax = AddTime(tmin, ImPlotTimeUnit_S, 1);\n                axis.SetRange(tmin.ToDouble(),tmax.ToDouble());\n            }\n            ImGui::Separator();\n            if (ShowDatePicker(\"mindate\",&axis.PickerLevel,&axis.PickerTimeMin,&tmin,&tmax)) {\n                tmin = CombineDateTime(axis.PickerTimeMin, tmin);\n                if (tmin >= tmax)\n                    tmax = AddTime(tmin, ImPlotTimeUnit_S, 1);\n                axis.SetRange(tmin.ToDouble(), tmax.ToDouble());\n            }\n            ImGui::EndMenu();\n        }\n        EndDisabledControls(axis.IsLockedMin() || always_locked);\n\n        BeginDisabledControls(always_locked);\n        ImGui::CheckboxFlags(\"##LockMax\", (unsigned int*)&axis.Flags, ImPlotAxisFlags_LockMax);\n        EndDisabledControls(always_locked);\n        ImGui::SameLine();\n        BeginDisabledControls(axis.IsLockedMax() || always_locked);\n        if (ImGui::BeginMenu(\"Max Time\")) {\n            if (ShowTimePicker(\"maxtime\", &tmax)) {\n                if (tmax <= tmin)\n                    tmin = AddTime(tmax, ImPlotTimeUnit_S, -1);\n                axis.SetRange(tmin.ToDouble(),tmax.ToDouble());\n            }\n            ImGui::Separator();\n            if (ShowDatePicker(\"maxdate\",&axis.PickerLevel,&axis.PickerTimeMax,&tmin,&tmax)) {\n                tmax = CombineDateTime(axis.PickerTimeMax, tmax);\n                if (tmax <= tmin)\n                    tmin = AddTime(tmax, ImPlotTimeUnit_S, -1);\n                axis.SetRange(tmin.ToDouble(), tmax.ToDouble());\n            }\n            ImGui::EndMenu();\n        }\n        EndDisabledControls(axis.IsLockedMax() || always_locked);\n    }\n    else {\n        BeginDisabledControls(always_locked);\n        ImGui::CheckboxFlags(\"##LockMin\", (unsigned int*)&axis.Flags, ImPlotAxisFlags_LockMin);\n        EndDisabledControls(always_locked);\n        ImGui::SameLine();\n        BeginDisabledControls(axis.IsLockedMin() || always_locked);\n        double temp_min = axis.Range.Min;\n        if (DragFloat(\"Min\", &temp_min, (float)drag_speed, -HUGE_VAL, axis.Range.Max - DBL_EPSILON)) {\n            axis.SetMin(temp_min,true);\n            if (equal_axis != NULL)\n                equal_axis->SetAspect(axis.GetAspect());\n        }\n        EndDisabledControls(axis.IsLockedMin() || always_locked);\n\n        BeginDisabledControls(always_locked);\n        ImGui::CheckboxFlags(\"##LockMax\", (unsigned int*)&axis.Flags, ImPlotAxisFlags_LockMax);\n        EndDisabledControls(always_locked);\n        ImGui::SameLine();\n        BeginDisabledControls(axis.IsLockedMax() || always_locked);\n        double temp_max = axis.Range.Max;\n        if (DragFloat(\"Max\", &temp_max, (float)drag_speed, axis.Range.Min + DBL_EPSILON, HUGE_VAL)) {\n            axis.SetMax(temp_max,true);\n            if (equal_axis != NULL)\n                equal_axis->SetAspect(axis.GetAspect());\n        }\n        EndDisabledControls(axis.IsLockedMax() || always_locked);\n    }\n\n    ImGui::Separator();\n\n    ImGui::CheckboxFlags(\"Auto-Fit\",(unsigned int*)&axis.Flags, ImPlotAxisFlags_AutoFit);\n    BeginDisabledControls(axis.IsTime() && time_allowed);\n    ImGui::CheckboxFlags(\"Log Scale\",(unsigned int*)&axis.Flags, ImPlotAxisFlags_LogScale);\n    EndDisabledControls(axis.IsTime() && time_allowed);\n    if (time_allowed) {\n        BeginDisabledControls(axis.IsLog());\n        ImGui::CheckboxFlags(\"Time\",(unsigned int*)&axis.Flags, ImPlotAxisFlags_Time);\n        EndDisabledControls(axis.IsLog());\n    }\n    ImGui::Separator();\n    ImGui::CheckboxFlags(\"Invert\",(unsigned int*)&axis.Flags, ImPlotAxisFlags_Invert);\n    ImGui::CheckboxFlags(\"Opposite\",(unsigned int*)&axis.Flags, ImPlotAxisFlags_Opposite);\n    ImGui::Separator();\n    BeginDisabledControls(axis.LabelOffset == -1);\n    if (ImGui::Checkbox(\"Label\", &label))\n        ImFlipFlag(axis.Flags, ImPlotAxisFlags_NoLabel);\n    EndDisabledControls(axis.LabelOffset == -1);\n    if (ImGui::Checkbox(\"Grid Lines\", &grid))\n        ImFlipFlag(axis.Flags, ImPlotAxisFlags_NoGridLines);\n    if (ImGui::Checkbox(\"Tick Marks\", &ticks))\n        ImFlipFlag(axis.Flags, ImPlotAxisFlags_NoTickMarks);\n    if (ImGui::Checkbox(\"Tick Labels\", &labels))\n        ImFlipFlag(axis.Flags, ImPlotAxisFlags_NoTickLabels);\n\n}\n\nbool ShowLegendContextMenu(ImPlotLegend& legend, bool visible) {\n    const float s = ImGui::GetFrameHeight();\n    bool ret = false;\n    if (ImGui::Checkbox(\"Show\",&visible))\n        ret = true;\n    if (legend.CanGoInside)\n        ImGui::CheckboxFlags(\"Outside\",(unsigned int*)&legend.Flags, ImPlotLegendFlags_Outside);\n    if (ImGui::RadioButton(\"H\", ImHasFlag(legend.Flags, ImPlotLegendFlags_Horizontal)))\n        legend.Flags |= ImPlotLegendFlags_Horizontal;\n    ImGui::SameLine();\n    if (ImGui::RadioButton(\"V\", !ImHasFlag(legend.Flags, ImPlotLegendFlags_Horizontal)))\n        legend.Flags &= ~ImPlotLegendFlags_Horizontal;\n    ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(2,2));\n    if (ImGui::Button(\"NW\",ImVec2(1.5f*s,s))) { legend.Location = ImPlotLocation_NorthWest; } ImGui::SameLine();\n    if (ImGui::Button(\"N\", ImVec2(1.5f*s,s))) { legend.Location = ImPlotLocation_North;     } ImGui::SameLine();\n    if (ImGui::Button(\"NE\",ImVec2(1.5f*s,s))) { legend.Location = ImPlotLocation_NorthEast; }\n    if (ImGui::Button(\"W\", ImVec2(1.5f*s,s))) { legend.Location = ImPlotLocation_West;      } ImGui::SameLine();\n    if (ImGui::InvisibleButton(\"C\", ImVec2(1.5f*s,s))) {     } ImGui::SameLine();\n    if (ImGui::Button(\"E\", ImVec2(1.5f*s,s))) { legend.Location = ImPlotLocation_East;      }\n    if (ImGui::Button(\"SW\",ImVec2(1.5f*s,s))) { legend.Location = ImPlotLocation_SouthWest; } ImGui::SameLine();\n    if (ImGui::Button(\"S\", ImVec2(1.5f*s,s))) { legend.Location = ImPlotLocation_South;     } ImGui::SameLine();\n    if (ImGui::Button(\"SE\",ImVec2(1.5f*s,s))) { legend.Location = ImPlotLocation_SouthEast; }\n    ImGui::PopStyleVar();\n    return ret;\n}\n\nvoid ShowSubplotsContextMenu(ImPlotSubplot& subplot) {\n    if ((ImGui::BeginMenu(\"Linking\"))) {\n        if (ImGui::MenuItem(\"Link Rows\",NULL,ImHasFlag(subplot.Flags, ImPlotSubplotFlags_LinkRows)))\n            ImFlipFlag(subplot.Flags, ImPlotSubplotFlags_LinkRows);\n        if (ImGui::MenuItem(\"Link Cols\",NULL,ImHasFlag(subplot.Flags, ImPlotSubplotFlags_LinkCols)))\n            ImFlipFlag(subplot.Flags, ImPlotSubplotFlags_LinkCols);\n        if (ImGui::MenuItem(\"Link All X\",NULL,ImHasFlag(subplot.Flags, ImPlotSubplotFlags_LinkAllX)))\n            ImFlipFlag(subplot.Flags, ImPlotSubplotFlags_LinkAllX);\n        if (ImGui::MenuItem(\"Link All Y\",NULL,ImHasFlag(subplot.Flags, ImPlotSubplotFlags_LinkAllY)))\n            ImFlipFlag(subplot.Flags, ImPlotSubplotFlags_LinkAllY);\n        ImGui::EndMenu();\n    }\n    if ((ImGui::BeginMenu(\"Settings\"))) {\n        BeginDisabledControls(!subplot.HasTitle);\n        if (ImGui::MenuItem(\"Title\",NULL,subplot.HasTitle && !ImHasFlag(subplot.Flags, ImPlotSubplotFlags_NoTitle)))\n            ImFlipFlag(subplot.Flags, ImPlotSubplotFlags_NoTitle);\n        EndDisabledControls(!subplot.HasTitle);\n        if (ImGui::MenuItem(\"Resizable\",NULL,!ImHasFlag(subplot.Flags, ImPlotSubplotFlags_NoResize)))\n            ImFlipFlag(subplot.Flags, ImPlotSubplotFlags_NoResize);\n        if (ImGui::MenuItem(\"Align\",NULL,!ImHasFlag(subplot.Flags, ImPlotSubplotFlags_NoAlign)))\n            ImFlipFlag(subplot.Flags, ImPlotSubplotFlags_NoAlign);\n        if (ImGui::MenuItem(\"Share Items\",NULL,ImHasFlag(subplot.Flags, ImPlotSubplotFlags_ShareItems)))\n            ImFlipFlag(subplot.Flags, ImPlotSubplotFlags_ShareItems);\n        ImGui::EndMenu();\n    }\n}\n\nvoid ShowPlotContextMenu(ImPlotPlot& plot) {\n    const bool owns_legend = GImPlot->CurrentItems == &plot.Items;\n    const bool equal = ImHasFlag(plot.Flags, ImPlotFlags_Equal);\n\n    char buf[16] = {};\n\n    for (int i = 0; i < IMPLOT_NUM_X_AXES; i++) {\n        ImPlotAxis& x_axis = plot.XAxis(i);\n        if (!x_axis.Enabled || !x_axis.HasMenus())\n            continue;\n        ImGui::PushID(i);\n        ImFormatString(buf, sizeof(buf) - 1, i == 0 ? \"X-Axis\" : \"X-Axis %d\", i + 1);\n        if (ImGui::BeginMenu(x_axis.HasLabel() ? plot.GetAxisLabel(x_axis) : buf)) {\n            ShowAxisContextMenu(x_axis, equal ? x_axis.OrthoAxis : NULL, false);\n            ImGui::EndMenu();\n        }\n        ImGui::PopID();\n    }\n\n    for (int i = 0; i < IMPLOT_NUM_Y_AXES; i++) {\n        ImPlotAxis& y_axis = plot.YAxis(i);\n        if (!y_axis.Enabled || !y_axis.HasMenus())\n            continue;\n        ImGui::PushID(i);\n        ImFormatString(buf, sizeof(buf) - 1, i == 0 ? \"Y-Axis\" : \"Y-Axis %d\", i + 1);\n        if (ImGui::BeginMenu(y_axis.HasLabel() ? plot.GetAxisLabel(y_axis) : buf)) {\n            ShowAxisContextMenu(y_axis, equal ? y_axis.OrthoAxis : NULL, false);\n            ImGui::EndMenu();\n        }\n        ImGui::PopID();\n    }\n\n    ImGui::Separator();\n    if (!ImHasFlag(GImPlot->CurrentItems->Legend.Flags, ImPlotLegendFlags_NoMenus)) {\n        if ((ImGui::BeginMenu(\"Legend\"))) {\n            if (owns_legend) {\n                if (ShowLegendContextMenu(plot.Items.Legend, !ImHasFlag(plot.Flags, ImPlotFlags_NoLegend)))\n                    ImFlipFlag(plot.Flags, ImPlotFlags_NoLegend);\n            }\n            else if (GImPlot->CurrentSubplot != NULL) {\n                if (ShowLegendContextMenu(GImPlot->CurrentSubplot->Items.Legend, !ImHasFlag(GImPlot->CurrentSubplot->Flags, ImPlotSubplotFlags_NoLegend)))\n                    ImFlipFlag(GImPlot->CurrentSubplot->Flags, ImPlotSubplotFlags_NoLegend);\n            }\n            ImGui::EndMenu();\n        }\n    }\n    if ((ImGui::BeginMenu(\"Settings\"))) {\n        if (ImGui::MenuItem(\"Anti-Aliased Lines\",NULL,ImHasFlag(plot.Flags, ImPlotFlags_AntiAliased)))\n            ImFlipFlag(plot.Flags, ImPlotFlags_AntiAliased);\n        if (ImGui::MenuItem(\"Equal\", NULL, ImHasFlag(plot.Flags, ImPlotFlags_Equal)))\n            ImFlipFlag(plot.Flags, ImPlotFlags_Equal);\n        if (ImGui::MenuItem(\"Box Select\",NULL,!ImHasFlag(plot.Flags, ImPlotFlags_NoBoxSelect)))\n            ImFlipFlag(plot.Flags, ImPlotFlags_NoBoxSelect);\n        BeginDisabledControls(plot.TitleOffset == -1);\n        if (ImGui::MenuItem(\"Title\",NULL,plot.HasTitle()))\n            ImFlipFlag(plot.Flags, ImPlotFlags_NoTitle);\n        EndDisabledControls(plot.TitleOffset == -1);\n        if (ImGui::MenuItem(\"Mouse Position\",NULL,!ImHasFlag(plot.Flags, ImPlotFlags_NoMouseText)))\n            ImFlipFlag(plot.Flags, ImPlotFlags_NoMouseText);\n        if (ImGui::MenuItem(\"Crosshairs\",NULL,ImHasFlag(plot.Flags, ImPlotFlags_Crosshairs)))\n            ImFlipFlag(plot.Flags, ImPlotFlags_Crosshairs);\n        ImGui::EndMenu();\n    }\n    if (GImPlot->CurrentSubplot != NULL && !ImHasFlag(GImPlot->CurrentPlot->Flags, ImPlotSubplotFlags_NoMenus)) {\n        ImGui::Separator();\n        if ((ImGui::BeginMenu(\"Subplots\"))) {\n            ShowSubplotsContextMenu(*GImPlot->CurrentSubplot);\n            ImGui::EndMenu();\n        }\n    }\n}\n\n//-----------------------------------------------------------------------------\n// Axis Utils\n//-----------------------------------------------------------------------------\n\nstatic inline void DefaultFormatter(double value, char* buff, int size, void* data) {\n    char* fmt = (char*)data;\n    ImFormatString(buff, size, fmt, value);\n}\n\nstatic inline int AxisPrecision(const ImPlotAxis& axis) {\n    const double range = axis.Ticks.Size > 1 ? (axis.Ticks.Ticks[1].PlotPos - axis.Ticks.Ticks[0].PlotPos) : axis.Range.Size();\n    return Precision(range);\n}\n\nstatic inline double RoundAxisValue(const ImPlotAxis& axis, double value) {\n    return RoundTo(value, AxisPrecision(axis));\n}\n\nvoid LabelAxisValue(const ImPlotAxis& axis, double value, char* buff, int size, bool round) {\n    ImPlotContext& gp = *GImPlot;\n    if (axis.IsTime()) {\n        ImPlotTimeUnit unit = axis.Vertical\n                            ? GetUnitForRange(axis.Range.Size() / (gp.CurrentPlot->PlotRect.GetHeight() / 100)) // TODO: magic value!\n                            : GetUnitForRange(axis.Range.Size() / (gp.CurrentPlot->PlotRect.GetWidth() / 100)); // TODO: magic value!\n        FormatDateTime(ImPlotTime::FromDouble(value), buff, size, GetDateTimeFmt(TimeFormatMouseCursor, unit));\n    }\n    else {\n        if (round)\n            value = RoundAxisValue(axis, value);\n        ImPlotFormatter formatter = axis.Formatter ? axis.Formatter : DefaultFormatter;\n        void* data = (axis.Formatter && axis.FormatterData) ? axis.FormatterData : axis.HasFormatSpec ? (void*)axis.FormatSpec : (void*)IMPLOT_LABEL_FORMAT;\n        formatter(value, buff, size, data);\n    }\n}\n\nvoid UpdateAxisColors(ImPlotAxis& axis) {\n    const ImVec4 col_grid = GetStyleColorVec4(ImPlotCol_AxisGrid);\n    axis.ColorMaj         = ImGui::GetColorU32(col_grid);\n    axis.ColorMin         = ImGui::GetColorU32(col_grid*ImVec4(1,1,1,GImPlot->Style.MinorAlpha));\n    axis.ColorTick        = GetStyleColorU32(ImPlotCol_AxisTick);\n    axis.ColorTxt         = GetStyleColorU32(ImPlotCol_AxisText);\n    axis.ColorBg          = GetStyleColorU32(ImPlotCol_AxisBg);\n    axis.ColorHov         = GetStyleColorU32(ImPlotCol_AxisBgHovered);\n    axis.ColorAct         = GetStyleColorU32(ImPlotCol_AxisBgActive);\n    // axis.ColorHiLi     = IM_COL32_BLACK_TRANS;\n}\n\nvoid PadAndDatumAxesX(ImPlotPlot& plot, float& pad_T, float& pad_B, ImPlotAlignmentData* align) {\n\n    ImPlotContext& gp = *GImPlot;\n\n    const float T = ImGui::GetTextLineHeight();\n    const float P = gp.Style.LabelPadding.y;\n    const float K = gp.Style.MinorTickLen.x;\n\n    int   count_T = 0;\n    int   count_B = 0;\n    float last_T  = plot.AxesRect.Min.y;\n    float last_B  = plot.AxesRect.Max.y;\n\n    for (int i = IMPLOT_NUM_X_AXES; i-- > 0;) { // FYI: can iterate forward\n        ImPlotAxis& axis = plot.XAxis(i);\n        if (!axis.Enabled)\n            continue;\n        const bool label = axis.HasLabel();\n        const bool ticks = axis.HasTickLabels();\n        const bool opp   = axis.IsOpposite();\n        const bool time  = axis.IsTime();\n        if (opp) {\n            if (count_T++ > 0)\n                pad_T += K + P;\n            if (label)\n                pad_T += T + P;\n            if (ticks)\n                pad_T += ImMax(T, axis.Ticks.MaxSize.y) + P + (time ? T + P : 0);\n            axis.Datum1 = plot.CanvasRect.Min.y + pad_T;\n            axis.Datum2 = last_T;\n            last_T = axis.Datum1;\n        }\n        else {\n            if (count_B++ > 0)\n                pad_B += K + P;\n            if (label)\n                pad_B += T + P;\n            if (ticks)\n                pad_B += ImMax(T, axis.Ticks.MaxSize.y) + P + (time ? T + P : 0);\n            axis.Datum1 = plot.CanvasRect.Max.y - pad_B;\n            axis.Datum2 = last_B;\n            last_B = axis.Datum1;\n        }\n    }\n\n    if (align) {\n        count_T = count_B = 0;\n        float delta_T, delta_B;\n        align->Update(pad_T,pad_B,delta_T,delta_B);\n        for (int i = IMPLOT_NUM_X_AXES; i-- > 0;) {\n            ImPlotAxis& axis = plot.XAxis(i);\n            if (!axis.Enabled)\n                continue;\n            if (axis.IsOpposite()) {\n                axis.Datum1 += delta_T;\n                axis.Datum2 += count_T++ > 1 ? delta_T : 0;\n            }\n            else {\n                axis.Datum1 -= delta_B;\n                axis.Datum2 -= count_B++ > 1 ? delta_B : 0;\n            }\n        }\n    }\n}\n\nvoid PadAndDatumAxesY(ImPlotPlot& plot, float& pad_L, float& pad_R, ImPlotAlignmentData* align) {\n\n    //   [   pad_L   ]                 [   pad_R   ]\n    //   .................CanvasRect................\n    //   :TPWPK.PTPWP _____PlotRect____ PWPTP.KPWPT:\n    //   :A # |- A # |-               -| # A -| # A:\n    //   :X   |  X   |                 |   X  |   x:\n    //   :I # |- I # |-               -| # I -| # I:\n    //   :S   |  S   |                 |   S  |   S:\n    //   :3 # |- 0 # |-_______________-| # 1 -| # 2:\n    //   :.........................................:\n    //\n    //   T = text height\n    //   P = label padding\n    //   K = minor tick length\n    //   W = label width\n\n    ImPlotContext& gp = *GImPlot;\n\n    const float T = ImGui::GetTextLineHeight();\n    const float P = gp.Style.LabelPadding.x;\n    const float K = gp.Style.MinorTickLen.y;\n\n    int   count_L = 0;\n    int   count_R = 0;\n    float last_L  = plot.AxesRect.Min.x;\n    float last_R  = plot.AxesRect.Max.x;\n\n    for (int i = IMPLOT_NUM_Y_AXES; i-- > 0;) { // FYI: can iterate forward\n        ImPlotAxis& axis = plot.YAxis(i);\n        if (!axis.Enabled)\n            continue;\n        const bool label = axis.HasLabel();\n        const bool ticks = axis.HasTickLabels();\n        const bool opp   = axis.IsOpposite();\n        if (opp) {\n            if (count_R++ > 0)\n                pad_R += K + P;\n            if (label)\n                pad_R += T + P;\n            if (ticks)\n                pad_R += axis.Ticks.MaxSize.x + P;\n            axis.Datum1 = plot.CanvasRect.Max.x - pad_R;\n            axis.Datum2 = last_R;\n            last_R = axis.Datum1;\n        }\n        else {\n            if (count_L++ > 0)\n                pad_L += K + P;\n            if (label)\n                pad_L += T + P;\n            if (ticks)\n                pad_L += axis.Ticks.MaxSize.x + P;\n            axis.Datum1 = plot.CanvasRect.Min.x + pad_L;\n            axis.Datum2 = last_L;\n            last_L = axis.Datum1;\n        }\n    }\n\n    plot.PlotRect.Min.x = plot.CanvasRect.Min.x + pad_L;\n    plot.PlotRect.Max.x = plot.CanvasRect.Max.x - pad_R;\n\n    if (align) {\n        count_L = count_R = 0;\n        float delta_L, delta_R;\n        align->Update(pad_L,pad_R,delta_L,delta_R);\n        for (int i = IMPLOT_NUM_Y_AXES; i-- > 0;) {\n            ImPlotAxis& axis = plot.YAxis(i);\n            if (!axis.Enabled)\n                continue;\n            if (axis.IsOpposite()) {\n                axis.Datum1 -= delta_R;\n                axis.Datum2 -= count_R++ > 1 ? delta_R : 0;\n            }\n            else {\n                axis.Datum1 += delta_L;\n                axis.Datum2 += count_L++ > 1 ? delta_L : 0;\n            }\n        }\n    }\n}\n\n//-----------------------------------------------------------------------------\n// RENDERING\n//-----------------------------------------------------------------------------\n\nstatic inline void RenderGridLinesX(ImDrawList& DrawList, const ImPlotTickCollection& ticks, const ImRect& rect, ImU32 col_maj, ImU32 col_min, float size_maj, float size_min) {\n    const float density   = ticks.Size / rect.GetWidth();\n    ImVec4 col_min4  = ImGui::ColorConvertU32ToFloat4(col_min);\n    col_min4.w      *= ImClamp(ImRemap(density, 0.1f, 0.2f, 1.0f, 0.0f), 0.0f, 1.0f);\n    col_min = ImGui::ColorConvertFloat4ToU32(col_min4);\n    for (int t = 0; t < ticks.Size; t++) {\n        const ImPlotTick& xt = ticks.Ticks[t];\n        if (xt.PixelPos < rect.Min.x || xt.PixelPos > rect.Max.x)\n            continue;\n        if (xt.Level == 0) {\n            if (xt.Major)\n                DrawList.AddLine(ImVec2(xt.PixelPos, rect.Min.y), ImVec2(xt.PixelPos, rect.Max.y), col_maj, size_maj);\n            else if (density < 0.2f)\n                DrawList.AddLine(ImVec2(xt.PixelPos, rect.Min.y), ImVec2(xt.PixelPos, rect.Max.y), col_min, size_min);\n        }\n    }\n}\n\nstatic inline void RenderGridLinesY(ImDrawList& DrawList, const ImPlotTickCollection& ticks, const ImRect& rect, ImU32 col_maj, ImU32 col_min, float size_maj, float size_min) {\n    const float density   = ticks.Size / rect.GetHeight();\n    ImVec4 col_min4  = ImGui::ColorConvertU32ToFloat4(col_min);\n    col_min4.w      *= ImClamp(ImRemap(density, 0.1f, 0.2f, 1.0f, 0.0f), 0.0f, 1.0f);\n    col_min = ImGui::ColorConvertFloat4ToU32(col_min4);\n    for (int t = 0; t < ticks.Size; t++) {\n        const ImPlotTick& yt = ticks.Ticks[t];\n        if (yt.PixelPos < rect.Min.y || yt.PixelPos > rect.Max.y)\n            continue;\n        if (yt.Major)\n            DrawList.AddLine(ImVec2(rect.Min.x, yt.PixelPos), ImVec2(rect.Max.x, yt.PixelPos), col_maj, size_maj);\n        else if (density < 0.2f)\n            DrawList.AddLine(ImVec2(rect.Min.x, yt.PixelPos), ImVec2(rect.Max.x, yt.PixelPos), col_min, size_min);\n    }\n}\n\nstatic inline void RenderSelectionRect(ImDrawList& DrawList, const ImVec2& p_min, const ImVec2& p_max, const ImVec4& col) {\n    const ImU32 col_bg = ImGui::GetColorU32(col * ImVec4(1,1,1,0.25f));\n    const ImU32 col_bd = ImGui::GetColorU32(col);\n    DrawList.AddRectFilled(p_min, p_max, col_bg);\n    DrawList.AddRect(p_min, p_max, col_bd);\n}\n\n//-----------------------------------------------------------------------------\n// Input Handling\n//-----------------------------------------------------------------------------\n\nstatic const float MOUSE_CURSOR_DRAG_THRESHOLD = 5.0f;\nstatic const float BOX_SELECT_DRAG_THRESHOLD   = 4.0f;\n\nbool UpdateInput(ImPlotPlot& plot) {\n\n    bool changed = false;\n\n    ImPlotContext& gp = *GImPlot;\n    ImGuiIO& IO = ImGui::GetIO();\n\n    // BUTTON STATE -----------------------------------------------------------\n\n    const ImGuiButtonFlags plot_button_flags = ImGuiButtonFlags_AllowItemOverlap\n                                             | ImGuiButtonFlags_PressedOnClick\n                                             | ImGuiButtonFlags_PressedOnDoubleClick\n                                             | ImGuiButtonFlags_MouseButtonLeft\n                                             | ImGuiButtonFlags_MouseButtonRight\n                                             | ImGuiButtonFlags_MouseButtonMiddle;\n    const ImGuiButtonFlags axis_button_flags = ImGuiButtonFlags_FlattenChildren\n                                             | plot_button_flags;\n\n    const bool plot_clicked = ImGui::ButtonBehavior(plot.PlotRect,plot.ID,&plot.Hovered,&plot.Held,plot_button_flags);\n    ImGui::SetItemAllowOverlap();\n\n    if (plot_clicked) {\n        if (!ImHasFlag(plot.Flags, ImPlotFlags_NoBoxSelect) && IO.MouseClicked[gp.InputMap.Select] && ImHasFlag(IO.KeyMods, gp.InputMap.SelectMod)) {\n            plot.Selecting   = true;\n            plot.SelectStart = IO.MousePos;\n            plot.SelectRect  = ImRect(0,0,0,0);\n        }\n        if (IO.MouseDoubleClicked[gp.InputMap.Fit]) {\n            plot.FitThisFrame = true;\n            for (int i = 0; i < ImAxis_COUNT; ++i)\n                plot.Axes[i].FitThisFrame = true;\n        }\n    }\n\n    const bool can_pan = IO.MouseDown[gp.InputMap.Pan] && ImHasFlag(IO.KeyMods, gp.InputMap.PanMod);\n\n    plot.Held = plot.Held && can_pan;\n\n    bool x_click[IMPLOT_NUM_X_AXES] = {false};\n    bool x_held[IMPLOT_NUM_X_AXES]  = {false};\n    bool x_hov[IMPLOT_NUM_X_AXES]   = {false};\n\n    bool y_click[IMPLOT_NUM_Y_AXES] = {false};\n    bool y_held[IMPLOT_NUM_Y_AXES]  = {false};\n    bool y_hov[IMPLOT_NUM_Y_AXES]   = {false};\n\n    for (int i = 0; i < IMPLOT_NUM_X_AXES; ++i) {\n        ImPlotAxis& xax = plot.XAxis(i);\n        if (xax.Enabled) {\n            ImGui::KeepAliveID(xax.ID);\n            x_click[i]  = ImGui::ButtonBehavior(xax.HoverRect,xax.ID,&xax.Hovered,&xax.Held,axis_button_flags);\n            if (x_click[i] && IO.MouseDoubleClicked[gp.InputMap.Fit])\n                plot.FitThisFrame = xax.FitThisFrame = true;\n            xax.Held  = xax.Held && can_pan;\n            x_hov[i]  = xax.Hovered || plot.Hovered;\n            x_held[i] = xax.Held    || plot.Held;\n        }\n    }\n\n    for (int i = 0; i < IMPLOT_NUM_Y_AXES; ++i) {\n        ImPlotAxis& yax = plot.YAxis(i);\n        if (yax.Enabled) {\n            ImGui::KeepAliveID(yax.ID);\n            y_click[i]  = ImGui::ButtonBehavior(yax.HoverRect,yax.ID,&yax.Hovered,&yax.Held,axis_button_flags);\n            if (y_click[i] && IO.MouseDoubleClicked[gp.InputMap.Fit])\n                plot.FitThisFrame = yax.FitThisFrame = true;\n            yax.Held  = yax.Held && can_pan;\n            y_hov[i]  = yax.Hovered || plot.Hovered;\n            y_held[i] = yax.Held    || plot.Held;\n        }\n    }\n\n    // cancel due to DND activity\n    if (GImGui->DragDropActive || (IO.KeyMods == gp.InputMap.OverrideMod && gp.InputMap.OverrideMod != 0))\n        return false;\n\n    // STATE -------------------------------------------------------------------\n\n    const bool axis_equal      = ImHasFlag(plot.Flags, ImPlotFlags_Equal);\n\n    const bool any_x_hov       = plot.Hovered || AnyAxesHovered(&plot.Axes[ImAxis_X1], IMPLOT_NUM_X_AXES);\n    const bool any_x_held      = plot.Held    || AnyAxesHeld(&plot.Axes[ImAxis_X1], IMPLOT_NUM_X_AXES);\n    const bool any_y_hov       = plot.Hovered || AnyAxesHovered(&plot.Axes[ImAxis_Y1], IMPLOT_NUM_Y_AXES);\n    const bool any_y_held      = plot.Held    || AnyAxesHeld(&plot.Axes[ImAxis_Y1], IMPLOT_NUM_Y_AXES);\n    const bool any_hov         = any_x_hov    || any_y_hov;\n    const bool any_held        = any_x_held   || any_y_held;\n\n    const ImVec2 select_drag   = ImGui::GetMouseDragDelta(gp.InputMap.Select);\n    const ImVec2 pan_drag      = ImGui::GetMouseDragDelta(gp.InputMap.Pan);\n    const float select_drag_sq = ImLengthSqr(select_drag);\n    const float pan_drag_sq    = ImLengthSqr(pan_drag);\n    const bool selecting       = plot.Selecting && select_drag_sq > MOUSE_CURSOR_DRAG_THRESHOLD;\n    const bool panning         = any_held       && pan_drag_sq    > MOUSE_CURSOR_DRAG_THRESHOLD;\n\n    // CONTEXT MENU -----------------------------------------------------------\n\n    if (IO.MouseReleased[gp.InputMap.Menu] && !plot.ContextLocked)\n        gp.OpenContextThisFrame = true;\n\n    if (selecting || panning)\n        plot.ContextLocked = true;\n    else if (!(IO.MouseDown[gp.InputMap.Menu] || IO.MouseReleased[gp.InputMap.Menu]))\n        plot.ContextLocked = false;\n\n    // DRAG INPUT -------------------------------------------------------------\n\n    if (any_held && !plot.Selecting) {\n        int drag_direction = 0;\n        for (int i = 0; i < IMPLOT_NUM_X_AXES; i++) {\n            ImPlotAxis& x_axis = plot.XAxis(i);\n            if (x_held[i] && !x_axis.IsInputLocked()) {\n                drag_direction |= (1 << 1);\n                const double plot_l = x_axis.PixelsToPlot(plot.PlotRect.Min.x - IO.MouseDelta.x);\n                const double plot_r = x_axis.PixelsToPlot(plot.PlotRect.Max.x - IO.MouseDelta.x);\n                x_axis.SetMin(x_axis.IsInverted() ? plot_r : plot_l);\n                x_axis.SetMax(x_axis.IsInverted() ? plot_l : plot_r);\n                if (axis_equal && x_axis.OrthoAxis != NULL)\n                    x_axis.OrthoAxis->SetAspect(x_axis.GetAspect());\n                changed = true;\n            }\n        }\n        for (int i = 0; i < IMPLOT_NUM_Y_AXES; i++) {\n            ImPlotAxis& y_axis = plot.YAxis(i);\n            if (y_held[i] && !y_axis.IsInputLocked()) {\n                drag_direction |= (1 << 2);\n                const double plot_t = y_axis.PixelsToPlot(plot.PlotRect.Min.y - IO.MouseDelta.y);\n                const double plot_b = y_axis.PixelsToPlot(plot.PlotRect.Max.y - IO.MouseDelta.y);\n                y_axis.SetMin(y_axis.IsInverted() ? plot_t : plot_b);\n                y_axis.SetMax(y_axis.IsInverted() ? plot_b : plot_t);\n                if (axis_equal && y_axis.OrthoAxis != NULL)\n                    y_axis.OrthoAxis->SetAspect(y_axis.GetAspect());\n                changed = true;\n            }\n        }\n        if (IO.MouseDragMaxDistanceSqr[gp.InputMap.Pan] > MOUSE_CURSOR_DRAG_THRESHOLD) {\n            switch (drag_direction) {\n                case 0        : ImGui::SetMouseCursor(ImGuiMouseCursor_NotAllowed); break;\n                case (1 << 1) : ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeEW);   break;\n                case (1 << 2) : ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeNS);   break;\n                default       : ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeAll);  break;\n            }\n        }\n    }\n\n    // SCROLL INPUT -----------------------------------------------------------\n\n    if (any_hov && IO.MouseWheel != 0 && ImHasFlag(IO.KeyMods, gp.InputMap.ZoomMod)) {\n\n        float zoom_rate = gp.InputMap.ZoomRate;\n        if (IO.MouseWheel > 0)\n            zoom_rate = (-zoom_rate) / (1.0f + (2.0f * zoom_rate));\n        ImVec2 rect_size = plot.PlotRect.GetSize();\n        float tx = ImRemap(IO.MousePos.x, plot.PlotRect.Min.x, plot.PlotRect.Max.x, 0.0f, 1.0f);\n        float ty = ImRemap(IO.MousePos.y, plot.PlotRect.Min.y, plot.PlotRect.Max.y, 0.0f, 1.0f);\n\n        for (int i = 0; i < IMPLOT_NUM_X_AXES; i++) {\n            ImPlotAxis& x_axis = plot.XAxis(i);\n            const bool equal_zoom   = axis_equal && x_axis.OrthoAxis != NULL;\n            const bool equal_locked = (equal_zoom != false) && x_axis.OrthoAxis->IsInputLocked();\n            if (x_hov[i] && !x_axis.IsInputLocked() && !equal_locked) {\n                float correction = (plot.Hovered && equal_zoom) ? 0.5f : 1.0f;\n                const double plot_l = x_axis.PixelsToPlot(plot.PlotRect.Min.x - rect_size.x * tx * zoom_rate * correction);\n                const double plot_r = x_axis.PixelsToPlot(plot.PlotRect.Max.x + rect_size.x * (1 - tx) * zoom_rate * correction);\n                x_axis.SetMin(x_axis.IsInverted() ? plot_r : plot_l);\n                x_axis.SetMax(x_axis.IsInverted() ? plot_l : plot_r);\n                if (axis_equal && x_axis.OrthoAxis != NULL)\n                    x_axis.OrthoAxis->SetAspect(x_axis.GetAspect());\n                changed = true;\n            }\n        }\n        for (int i = 0; i < IMPLOT_NUM_Y_AXES; i++) {\n            ImPlotAxis& y_axis = plot.YAxis(i);\n            const bool equal_zoom   = axis_equal && y_axis.OrthoAxis != NULL;\n            const bool equal_locked = equal_zoom && y_axis.OrthoAxis->IsInputLocked();\n            if (y_hov[i] && !y_axis.IsInputLocked() && !equal_locked) {\n                float correction = (plot.Hovered && equal_zoom) ? 0.5f : 1.0f;\n                const double plot_t = y_axis.PixelsToPlot(plot.PlotRect.Min.y - rect_size.y * ty * zoom_rate * correction);\n                const double plot_b = y_axis.PixelsToPlot(plot.PlotRect.Max.y + rect_size.y * (1 - ty) * zoom_rate * correction);\n                y_axis.SetMin(y_axis.IsInverted() ? plot_t : plot_b);\n                y_axis.SetMax(y_axis.IsInverted() ? plot_b : plot_t);\n                if (axis_equal && y_axis.OrthoAxis != NULL)\n                    y_axis.OrthoAxis->SetAspect(y_axis.GetAspect());\n                changed = true;\n            }\n        }\n    }\n\n    // BOX-SELECTION ----------------------------------------------------------\n\n    if (plot.Selecting) {\n        const ImVec2 d = plot.SelectStart - IO.MousePos;\n        const bool x_can_change = !ImHasFlag(IO.KeyMods,gp.InputMap.SelectHorzMod) && ImFabs(d.x) > 2;\n        const bool y_can_change = !ImHasFlag(IO.KeyMods,gp.InputMap.SelectVertMod) && ImFabs(d.y) > 2;\n        // confirm\n        if (IO.MouseReleased[gp.InputMap.Select]) {\n            for (int i = 0; i < IMPLOT_NUM_X_AXES; i++) {\n                ImPlotAxis& x_axis = plot.XAxis(i);\n                if (!x_axis.IsInputLocked() && x_can_change) {\n                    const double p1 = x_axis.PixelsToPlot(plot.SelectStart.x);\n                    const double p2 = x_axis.PixelsToPlot(IO.MousePos.x);\n                    x_axis.SetMin(ImMin(p1, p2));\n                    x_axis.SetMax(ImMax(p1, p2));\n                    changed = true;\n                }\n            }\n            for (int i = 0; i < IMPLOT_NUM_Y_AXES; i++) {\n                ImPlotAxis& y_axis = plot.YAxis(i);\n                if (!y_axis.IsInputLocked() && y_can_change) {\n                    const double p1 = y_axis.PixelsToPlot(plot.SelectStart.y);\n                    const double p2 = y_axis.PixelsToPlot(IO.MousePos.y);\n                    y_axis.SetMin(ImMin(p1, p2));\n                    y_axis.SetMax(ImMax(p1, p2));\n                    changed = true;\n                }\n            }\n            if (x_can_change || y_can_change || (ImHasFlag(IO.KeyMods,gp.InputMap.SelectHorzMod) && ImHasFlag(IO.KeyMods,gp.InputMap.SelectVertMod)))\n                gp.OpenContextThisFrame = false;\n            plot.Selected = plot.Selecting = false;\n        }\n        // cancel\n        else if (IO.MouseReleased[gp.InputMap.SelectCancel]) {\n            plot.Selected = plot.Selecting = false;\n            gp.OpenContextThisFrame = false;\n        }\n        else if (ImLengthSqr(d) > BOX_SELECT_DRAG_THRESHOLD) {\n            // bad selection\n            if (plot.IsInputLocked()) {\n                ImGui::SetMouseCursor(ImGuiMouseCursor_NotAllowed);\n                gp.OpenContextThisFrame = false;\n                plot.Selected      = false;\n            }\n            else {\n                // TODO: Handle only min or max locked cases\n                const bool full_width  = ImHasFlag(IO.KeyMods, gp.InputMap.SelectHorzMod) || AllAxesInputLocked(&plot.Axes[ImAxis_X1], IMPLOT_NUM_X_AXES);\n                const bool full_height = ImHasFlag(IO.KeyMods, gp.InputMap.SelectVertMod) || AllAxesInputLocked(&plot.Axes[ImAxis_Y1], IMPLOT_NUM_Y_AXES);\n                plot.SelectRect.Min.x = full_width  ? plot.PlotRect.Min.x : ImMin(plot.SelectStart.x, IO.MousePos.x);\n                plot.SelectRect.Max.x = full_width  ? plot.PlotRect.Max.x : ImMax(plot.SelectStart.x, IO.MousePos.x);\n                plot.SelectRect.Min.y = full_height ? plot.PlotRect.Min.y : ImMin(plot.SelectStart.y, IO.MousePos.y);\n                plot.SelectRect.Max.y = full_height ? plot.PlotRect.Max.y : ImMax(plot.SelectStart.y, IO.MousePos.y);\n                plot.SelectRect.Min  -= plot.PlotRect.Min;\n                plot.SelectRect.Max  -= plot.PlotRect.Min;\n                plot.Selected = true;\n            }\n        }\n        else {\n            plot.Selected = false;\n        }\n    }\n    return changed;\n}\n\n//-----------------------------------------------------------------------------\n// Next Plot Data (Legacy)\n//-----------------------------------------------------------------------------\n\nvoid ApplyNextPlotData(ImAxis idx) {\n    ImPlotContext& gp = *GImPlot;\n    ImPlotPlot& plot  = *GImPlot->CurrentPlot;\n    ImPlotAxis& axis  = plot.Axes[idx];\n    if (!axis.Enabled)\n        return;\n    double*     npd_lmin = gp.NextPlotData.LinkedMin[idx];\n    double*     npd_lmax = gp.NextPlotData.LinkedMax[idx];\n    bool        npd_rngh = gp.NextPlotData.HasRange[idx];\n    ImPlotCond  npd_rngc = gp.NextPlotData.RangeCond[idx];\n    ImPlotRange     npd_rngv = gp.NextPlotData.Range[idx];\n    axis.LinkedMin = npd_lmin;\n    axis.LinkedMax = npd_lmax;\n    axis.PullLinks();\n    if (npd_rngh) {\n        if (!plot.Initialized || npd_rngc == ImPlotCond_Always)\n            axis.SetRange(npd_rngv);\n    }\n    axis.HasRange         = npd_rngh;\n    axis.RangeCond        = npd_rngc;\n}\n\n//-----------------------------------------------------------------------------\n// Setup\n//-----------------------------------------------------------------------------\n\nvoid SetupAxis(ImAxis idx, const char* label, ImPlotAxisFlags flags) {\n    IM_ASSERT_USER_ERROR(GImPlot->CurrentPlot != NULL && !GImPlot->CurrentPlot->SetupLocked,\n                         \"Setup needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!\");\n    IM_ASSERT_USER_ERROR(!(ImHasFlag(flags, ImPlotAxisFlags_Time) && ImHasFlag(flags, ImPlotAxisFlags_LogScale)),\n                         \"ImPlotAxisFlags_Time and ImPlotAxisFlags_LogScale cannot be enabled at the same time!\");\n    IM_ASSERT_USER_ERROR(!(ImHasFlag(flags, ImPlotAxisFlags_Time) && idx >= ImAxis_Y1),\n                         \"Y axes cannot display time formatted labels!\");\n    // get plot and axis\n    ImPlotPlot& plot = *GImPlot->CurrentPlot;\n    ImPlotAxis& axis = plot.Axes[idx];\n    // set ID\n    axis.ID = plot.ID + idx + 1;\n    // check and set flags\n    if (plot.JustCreated || flags != axis.PreviousFlags)\n        axis.Flags = flags;\n    axis.PreviousFlags = flags;\n    // enable axis\n    axis.Enabled = true;\n    // set label\n    plot.SetAxisLabel(axis,label);\n    // cache colors\n    UpdateAxisColors(axis);\n}\n\nvoid SetupAxisLimits(ImAxis idx, double min_lim, double max_lim, ImPlotCond cond) {\n    IM_ASSERT_USER_ERROR(GImPlot->CurrentPlot != NULL && !GImPlot->CurrentPlot->SetupLocked,\n                         \"Setup needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!\");    // get plot and axis\n    ImPlotPlot& plot = *GImPlot->CurrentPlot;\n    ImPlotAxis& axis = plot.Axes[idx];\n    IM_ASSERT_USER_ERROR(axis.Enabled, \"Axis is not enabled! Did you forget to call SetupAxis()?\");\n    if (!plot.Initialized || cond == ImPlotCond_Always)\n        axis.SetRange(min_lim, max_lim);\n    axis.HasRange  = true;\n    axis.RangeCond = cond;\n}\n\nvoid SetupAxisFormat(ImAxis idx, const char* fmt) {\n    IM_ASSERT_USER_ERROR(GImPlot->CurrentPlot != NULL && !GImPlot->CurrentPlot->SetupLocked,\n                         \"Setup needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!\");\n    ImPlotPlot& plot = *GImPlot->CurrentPlot;\n    ImPlotAxis& axis = plot.Axes[idx];\n    IM_ASSERT_USER_ERROR(axis.Enabled, \"Axis is not enabled! Did you forget to call SetupAxis()?\");\n    axis.HasFormatSpec = fmt != NULL;\n    if (fmt != NULL)\n        ImStrncpy(axis.FormatSpec,fmt,sizeof(axis.FormatSpec));\n}\n\nvoid SetupAxisLinks(ImAxis idx, double* min_lnk, double* max_lnk) {\n    IM_ASSERT_USER_ERROR(GImPlot->CurrentPlot != NULL && !GImPlot->CurrentPlot->SetupLocked,\n                         \"Setup needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!\");\n    ImPlotPlot& plot = *GImPlot->CurrentPlot;\n    ImPlotAxis& axis = plot.Axes[idx];\n    IM_ASSERT_USER_ERROR(axis.Enabled, \"Axis is not enabled! Did you forget to call SetupAxis()?\");\n    axis.LinkedMin = min_lnk;\n    axis.LinkedMax = max_lnk;\n    axis.PullLinks();\n}\n\nvoid SetupAxisFormat(ImAxis idx, ImPlotFormatter formatter, void* data) {\n    IM_ASSERT_USER_ERROR(GImPlot->CurrentPlot != NULL && !GImPlot->CurrentPlot->SetupLocked,\n                         \"Setup needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!\");\n    ImPlotPlot& plot = *GImPlot->CurrentPlot;\n    ImPlotAxis& axis = plot.Axes[idx];\n    IM_ASSERT_USER_ERROR(axis.Enabled, \"Axis is not enabled! Did you forget to call SetupAxis()?\");\n    axis.Formatter = formatter;\n    axis.FormatterData = data;\n}\n\nvoid SetupAxisTicks(ImAxis idx, const double* values, int n_ticks, const char* const labels[], bool show_default) {\n    IM_ASSERT_USER_ERROR(GImPlot->CurrentPlot != NULL && !GImPlot->CurrentPlot->SetupLocked,\n                        \"Setup needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!\");\n    ImPlotPlot& plot = *GImPlot->CurrentPlot;\n    ImPlotAxis& axis = plot.Axes[idx];\n    IM_ASSERT_USER_ERROR(axis.Enabled, \"Axis is not enabled! Did you forget to call SetupAxis()?\");\n    axis.ShowDefaultTicks = show_default;\n    AddTicksCustom(values,\n                  labels,\n                  n_ticks,\n                  axis.Ticks,\n                  axis.Formatter ? axis.Formatter : DefaultFormatter,\n                  (axis.Formatter && axis.FormatterData) ? axis.FormatterData : axis.HasFormatSpec ? axis.FormatSpec : (void*)IMPLOT_LABEL_FORMAT);\n}\n\nvoid SetupAxisTicks(ImAxis idx, double v_min, double v_max, int n_ticks, const char* const labels[], bool show_default) {\n    IM_ASSERT_USER_ERROR(GImPlot->CurrentPlot != NULL && !GImPlot->CurrentPlot->SetupLocked,\n                         \"Setup needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!\");\n    IM_ASSERT_USER_ERROR(n_ticks > 1, \"The number of ticks must be greater than 1\");\n    FillRange(GImPlot->TempDouble1, n_ticks, v_min, v_max);\n    SetupAxisTicks(idx, GImPlot->TempDouble1.Data, n_ticks, labels, show_default);\n}\n\nvoid SetupAxes(const char* x_label, const char* y_label, ImPlotAxisFlags x_flags, ImPlotAxisFlags y_flags) {\n    SetupAxis(ImAxis_X1, x_label, x_flags);\n    SetupAxis(ImAxis_Y1, y_label, y_flags);\n}\n\nvoid SetupAxesLimits(double x_min, double x_max, double y_min, double y_max, ImPlotCond cond) {\n    SetupAxisLimits(ImAxis_X1, x_min, x_max, cond);\n    SetupAxisLimits(ImAxis_Y1, y_min, y_max, cond);\n}\n\nvoid SetupLegend(ImPlotLocation location, ImPlotLegendFlags flags) {\n    IM_ASSERT_USER_ERROR(GImPlot->CurrentPlot != NULL && !GImPlot->CurrentPlot->SetupLocked,\n                         \"Setup needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!\");\n    IM_ASSERT_USER_ERROR(GImPlot->CurrentItems != NULL,\n                         \"SetupLegend() needs to be called within an itemized context!\");\n    ImPlotLegend& legend = GImPlot->CurrentItems->Legend;\n    // check and set location\n    if (location != legend.PreviousLocation)\n        legend.Location = location;\n    legend.PreviousLocation = location;\n    // check and set flags\n    if (flags != legend.PreviousFlags)\n        legend.Flags = flags;\n    legend.PreviousFlags = flags;\n}\n\nvoid SetupMouseText(ImPlotLocation location, ImPlotMouseTextFlags flags) {\n    IM_ASSERT_USER_ERROR(GImPlot->CurrentPlot != NULL && !GImPlot->CurrentPlot->SetupLocked,\n                         \"Setup needs to be called after BeginPlot and before any setup locking functions (e.g. PlotX)!\");\n    GImPlot->CurrentPlot->MouseTextLocation = location;\n    GImPlot->CurrentPlot->MouseTextFlags = flags;\n}\n\n//-----------------------------------------------------------------------------\n// SetNext\n//-----------------------------------------------------------------------------\n\nvoid SetNextAxisLimits(ImAxis axis, double v_min, double v_max, ImPlotCond cond) {\n    ImPlotContext& gp = *GImPlot;\n    IM_ASSERT_USER_ERROR(gp.CurrentPlot == NULL, \"SetNextAxisLimits() needs to be called before BeginPlot()!\");\n    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.\n    gp.NextPlotData.HasRange[axis]  = true;\n    gp.NextPlotData.RangeCond[axis] = cond;\n    gp.NextPlotData.Range[axis].Min = v_min;\n    gp.NextPlotData.Range[axis].Max = v_max;\n}\n\nvoid SetNextAxisLinks(ImAxis axis, double* link_min, double* link_max) {\n    ImPlotContext& gp = *GImPlot;\n    IM_ASSERT_USER_ERROR(gp.CurrentPlot == NULL, \"SetNextAxisLinks() needs to be called before BeginPlot()!\");\n    gp.NextPlotData.LinkedMin[axis] = link_min;\n    gp.NextPlotData.LinkedMax[axis] = link_max;\n}\n\nvoid SetNextAxisToFit(ImAxis axis) {\n    ImPlotContext& gp = *GImPlot;\n    IM_ASSERT_USER_ERROR(gp.CurrentPlot == NULL, \"SetNextAxisToFit() needs to be called before BeginPlot()!\");\n    gp.NextPlotData.Fit[axis] = true;\n}\n\nvoid SetNextAxesLimits(double x_min, double x_max, double y_min, double y_max, ImPlotCond cond) {\n    SetNextAxisLimits(ImAxis_X1, x_min, x_max, cond);\n    SetNextAxisLimits(ImAxis_Y1, y_min, y_max, cond);\n}\n\nvoid SetNextAxesToFit() {\n    for (int i = 0; i < ImAxis_COUNT; ++i)\n        SetNextAxisToFit(i);\n}\n\n//-----------------------------------------------------------------------------\n// BeginPlot\n//-----------------------------------------------------------------------------\n\nbool BeginPlot(const char* title_id, const ImVec2& size, ImPlotFlags flags) {\n    IM_ASSERT_USER_ERROR(GImPlot != NULL, \"No current context. Did you call ImPlot::CreateContext() or ImPlot::SetCurrentContext()?\");\n    IM_ASSERT_USER_ERROR(GImPlot->CurrentPlot == NULL, \"Mismatched BeginPlot()/EndPlot()!\");\n\n    // FRONT MATTER -----------------------------------------------------------\n\n    if (GImPlot->CurrentSubplot != NULL)\n        ImGui::PushID(GImPlot->CurrentSubplot->CurrentIdx);\n\n    // get globals\n    ImPlotContext& gp        = *GImPlot;\n    ImGuiContext &G          = *GImGui;\n    ImGuiWindow* Window      = G.CurrentWindow;\n\n    // skip if needed\n    if (Window->SkipItems && !gp.CurrentSubplot) {\n        ResetCtxForNextPlot(GImPlot);\n        return false;\n    }\n\n    // ID and age (TODO: keep track of plot age in frames)\n    const ImGuiID ID         = Window->GetID(title_id);\n    const bool just_created  = gp.Plots.GetByKey(ID) == NULL;\n    gp.CurrentPlot           = gp.Plots.GetOrAddByKey(ID);\n\n    ImPlotPlot &plot         = *gp.CurrentPlot;\n    plot.ID                  = ID;\n    plot.Items.ID            = ID - 1;\n    plot.JustCreated         = just_created;\n    plot.SetupLocked         = false;\n\n    // check flags\n    if (plot.JustCreated)\n        plot.Flags = flags;\n    else if (flags != plot.PreviousFlags)\n        plot.Flags = flags;\n    plot.PreviousFlags = flags;\n\n    // setup default axes\n    if (plot.JustCreated) {\n        SetupAxis(ImAxis_X1);\n        SetupAxis(ImAxis_Y1);\n    }\n\n    // reset axes\n    for (int i = 0; i < ImAxis_COUNT; ++i) {\n        plot.Axes[i].Reset();\n        UpdateAxisColors(plot.Axes[i]);\n    }\n    // ensure first axes enabled\n    plot.Axes[ImAxis_X1].Enabled = true;\n    plot.Axes[ImAxis_Y1].Enabled = true;\n    // set initial axes\n    plot.CurrentX = ImAxis_X1;\n    plot.CurrentY = ImAxis_Y1;\n\n    // process next plot data (legacy)\n    for (int i = 0; i < ImAxis_COUNT; ++i)\n        ApplyNextPlotData(i);\n\n    // capture scroll with a child region\n    if (!ImHasFlag(plot.Flags, ImPlotFlags_NoChild)) {\n        ImVec2 child_size;\n        if (gp.CurrentSubplot != NULL)\n            child_size = gp.CurrentSubplot->CellSize;\n        else\n            child_size = ImVec2(size.x == 0 ? gp.Style.PlotDefaultSize.x : size.x, size.y == 0 ? gp.Style.PlotDefaultSize.y : size.y);\n        ImGui::BeginChild(title_id, child_size, false, ImGuiWindowFlags_NoScrollbar);\n        Window = ImGui::GetCurrentWindow();\n        Window->ScrollMax.y = 1.0f;\n        gp.ChildWindowMade = true;\n    }\n    else {\n        gp.ChildWindowMade = false;\n    }\n\n    // clear text buffers\n    plot.ClearTextBuffer();\n    plot.SetTitle(title_id);\n\n    // set frame size\n    ImVec2 frame_size;\n    if (gp.CurrentSubplot != NULL)\n        frame_size = gp.CurrentSubplot->CellSize;\n    else\n        frame_size = ImGui::CalcItemSize(size, gp.Style.PlotDefaultSize.x, gp.Style.PlotDefaultSize.y);\n\n    if (frame_size.x < gp.Style.PlotMinSize.x && (size.x < 0.0f || gp.CurrentSubplot != NULL))\n        frame_size.x = gp.Style.PlotMinSize.x;\n    if (frame_size.y < gp.Style.PlotMinSize.y && (size.y < 0.0f || gp.CurrentSubplot != NULL))\n        frame_size.y = gp.Style.PlotMinSize.y;\n\n    plot.FrameRect = ImRect(Window->DC.CursorPos, Window->DC.CursorPos + frame_size);\n    ImGui::ItemSize(plot.FrameRect);\n    if (!ImGui::ItemAdd(plot.FrameRect, plot.ID, &plot.FrameRect) && !gp.CurrentSubplot) {\n        ResetCtxForNextPlot(GImPlot);\n        return false;\n    }\n\n    // setup items (or dont)\n    if (gp.CurrentItems == NULL)\n        gp.CurrentItems = &plot.Items;\n\n    return true;\n}\n\nvoid SetupFinish() {\n    IM_ASSERT_USER_ERROR(GImPlot != NULL, \"No current context. Did you call ImPlot::CreateContext() or ImPlot::SetCurrentContext()?\");\n    IM_ASSERT_USER_ERROR(GImPlot->CurrentPlot != NULL, \"SetupFinish needs to be called after BeginPlot!\");\n\n    ImPlotContext& gp       = *GImPlot;\n    ImGuiContext& G         = *GImGui;\n    ImDrawList& DrawList    = *G.CurrentWindow->DrawList;\n    const ImGuiStyle& Style = G.Style;\n\n    ImPlotPlot &plot  = *gp.CurrentPlot;\n\n    // lock setup\n    plot.SetupLocked = true;\n\n    // finalize axes\n    for (int i = 0; i < ImAxis_COUNT; ++i) {\n        if (plot.Axes[i].Enabled) {\n            plot.Axes[i].Constrain();\n            if (!plot.Initialized && plot.Axes[i].CanInitFit())\n                plot.FitThisFrame = plot.Axes[i].FitThisFrame = true;\n        }\n    }\n\n    // setup NULL orthogonal axes\n    const bool axis_equal = ImHasFlag(plot.Flags, ImPlotFlags_Equal);\n    for (int ix = ImAxis_X1, iy = ImAxis_Y1; ix < ImAxis_Y1 || iy < ImAxis_COUNT; ++ix, ++iy) {\n        ImPlotAxis& x_axis = plot.Axes[ix];\n        ImPlotAxis& y_axis = plot.Axes[iy];\n        if (x_axis.Enabled && y_axis.Enabled) {\n            if (x_axis.OrthoAxis == NULL)\n                x_axis.OrthoAxis = &y_axis;\n            if (y_axis.OrthoAxis == NULL)\n                y_axis.OrthoAxis = &x_axis;\n        }\n        else if (x_axis.Enabled)\n        {\n            if (x_axis.OrthoAxis == NULL && !axis_equal)\n                x_axis.OrthoAxis = &plot.Axes[ImAxis_Y1];\n        }\n        else if (y_axis.Enabled) {\n            if (y_axis.OrthoAxis == NULL && !axis_equal)\n                y_axis.OrthoAxis = &plot.Axes[ImAxis_X1];\n        }\n    }\n\n    // canvas/axes bb\n    plot.CanvasRect = ImRect(plot.FrameRect.Min + gp.Style.PlotPadding, plot.FrameRect.Max - gp.Style.PlotPadding);\n    plot.AxesRect   = plot.FrameRect;\n\n    // outside legend adjustments\n    if (!ImHasFlag(plot.Flags, ImPlotFlags_NoLegend) && plot.Items.GetLegendCount() > 0 && ImHasFlag(plot.Items.Legend.Flags, ImPlotLegendFlags_Outside)) {\n        ImPlotLegend& legend = plot.Items.Legend;\n        const bool horz = ImHasFlag(legend.Flags, ImPlotLegendFlags_Horizontal);\n        const ImVec2 legend_size = CalcLegendSize(plot.Items, gp.Style.LegendInnerPadding, gp.Style.LegendSpacing, !horz);\n        const bool west = ImHasFlag(legend.Location, ImPlotLocation_West) && !ImHasFlag(legend.Location, ImPlotLocation_East);\n        const bool east = ImHasFlag(legend.Location, ImPlotLocation_East) && !ImHasFlag(legend.Location, ImPlotLocation_West);\n        const bool north = ImHasFlag(legend.Location, ImPlotLocation_North) && !ImHasFlag(legend.Location, ImPlotLocation_South);\n        const bool south = ImHasFlag(legend.Location, ImPlotLocation_South) && !ImHasFlag(legend.Location, ImPlotLocation_North);\n        if ((west && !horz) || (west && horz && !north && !south)) {\n            plot.CanvasRect.Min.x += (legend_size.x + gp.Style.LegendPadding.x);\n            plot.AxesRect.Min.x   += (legend_size.x + gp.Style.PlotPadding.x);\n        }\n        if ((east && !horz) || (east && horz && !north && !south)) {\n            plot.CanvasRect.Max.x -= (legend_size.x + gp.Style.LegendPadding.x);\n            plot.AxesRect.Max.x   -= (legend_size.x + gp.Style.PlotPadding.x);\n        }\n        if ((north && horz) || (north && !horz && !west && !east)) {\n            plot.CanvasRect.Min.y += (legend_size.y + gp.Style.LegendPadding.y);\n            plot.AxesRect.Min.y   += (legend_size.y + gp.Style.PlotPadding.y);\n        }\n        if ((south && horz) || (south && !horz && !west && !east)) {\n            plot.CanvasRect.Max.y -= (legend_size.y + gp.Style.LegendPadding.y);\n            plot.AxesRect.Max.y   -= (legend_size.y + gp.Style.PlotPadding.y);\n        }\n    }\n\n    // plot bb\n    float pad_top = 0, pad_bot = 0, pad_left = 0, pad_right = 0;\n\n    // (0) calc top padding form title\n    ImVec2 title_size(0.0f, 0.0f);\n    if (plot.HasTitle())\n         title_size = ImGui::CalcTextSize(plot.GetTitle(), NULL, true);\n    if (title_size.x > 0) {\n        pad_top += title_size.y + gp.Style.LabelPadding.y;\n        plot.AxesRect.Min.y += gp.Style.PlotPadding.y + pad_top;\n    }\n\n    // (1) calc addition top padding and bot padding\n    PadAndDatumAxesX(plot,pad_top,pad_bot,gp.CurrentAlignmentH);\n\n\n\n    const float plot_height = plot.CanvasRect.GetHeight() - pad_top - pad_bot;\n\n    // (2) get y tick labels (needed for left/right pad)\n    for (int i = 0; i < IMPLOT_NUM_Y_AXES; i++) {\n        ImPlotAxis& axis = plot.YAxis(i);\n        if (axis.WillRender() && axis.ShowDefaultTicks) {\n            if (axis.IsLog())\n                AddTicksLogarithmic(axis.Range,\n                                    plot_height,\n                                    true,\n                                    axis.Ticks,\n                                    axis.Formatter     ? axis.Formatter  : DefaultFormatter,\n                                    (axis.Formatter && axis.FormatterData) ? axis.FormatterData : axis.HasFormatSpec ? axis.FormatSpec : (void*)IMPLOT_LABEL_FORMAT);\n            else\n                AddTicksDefault(axis.Range,\n                                plot_height,\n                                true,\n                                axis.Ticks,\n                                axis.Formatter     ? axis.Formatter  : DefaultFormatter,\n                                (axis.Formatter && axis.FormatterData) ? axis.FormatterData : axis.HasFormatSpec ? axis.FormatSpec : (void*)IMPLOT_LABEL_FORMAT);\n        }\n    }\n\n    // (3) calc left/right pad\n    PadAndDatumAxesY(plot,pad_left,pad_right,gp.CurrentAlignmentV);\n\n    const float plot_width = plot.CanvasRect.GetWidth() - pad_left - pad_right;\n\n    // (4) get x ticks\n    for (int i = 0; i < IMPLOT_NUM_X_AXES; i++) {\n        ImPlotAxis& axis = plot.XAxis(i);\n        if (axis.WillRender() && axis.ShowDefaultTicks) {\n            if (axis.IsTime())\n                AddTicksTime(axis.Range, plot_width, axis.Ticks);\n            else if (axis.IsLog())\n                AddTicksLogarithmic(axis.Range,\n                                    plot_width,\n                                    false,\n                                    axis.Ticks,\n                                    axis.Formatter     ? axis.Formatter  : DefaultFormatter,\n                                    (axis.Formatter && axis.FormatterData) ? axis.FormatterData : axis.HasFormatSpec ? axis.FormatSpec : (void*)IMPLOT_LABEL_FORMAT);\n            else\n                AddTicksDefault(axis.Range,\n                                plot_width,\n                                false,\n                                axis.Ticks,\n                                axis.Formatter     ? axis.Formatter  : DefaultFormatter,\n                                (axis.Formatter && axis.FormatterData) ? axis.FormatterData : axis.HasFormatSpec ? axis.FormatSpec : (void*)IMPLOT_LABEL_FORMAT);\n        }\n    }\n\n    // (5) calc plot bb\n    plot.PlotRect = ImRect(plot.CanvasRect.Min + ImVec2(pad_left, pad_top), plot.CanvasRect.Max - ImVec2(pad_right, pad_bot));\n\n    // HOVER------------------------------------------------------------\n\n    // axes hover rect, pixel ranges\n    for (int i = 0; i < IMPLOT_NUM_X_AXES; ++i) {\n        ImPlotAxis& xax = plot.XAxis(i);\n        xax.HoverRect   = ImRect(ImVec2(plot.PlotRect.Min.x, ImMin(xax.Datum1,xax.Datum2)),\n                                 ImVec2(plot.PlotRect.Max.x, ImMax(xax.Datum1,xax.Datum2)));\n        xax.PixelMin    = xax.IsInverted() ? plot.PlotRect.Max.x : plot.PlotRect.Min.x;\n        xax.PixelMax    = xax.IsInverted() ? plot.PlotRect.Min.x : plot.PlotRect.Max.x;\n        xax.UpdateTransformCache();\n    }\n\n    for (int i = 0; i < IMPLOT_NUM_Y_AXES; ++i) {\n        ImPlotAxis& yax = plot.YAxis(i);\n        yax.HoverRect   = ImRect(ImVec2(ImMin(yax.Datum1,yax.Datum2),plot.PlotRect.Min.y),\n                                 ImVec2(ImMax(yax.Datum1,yax.Datum2),plot.PlotRect.Max.y));\n        yax.PixelMin    = yax.IsInverted() ? plot.PlotRect.Min.y : plot.PlotRect.Max.y;\n        yax.PixelMax    = yax.IsInverted() ? plot.PlotRect.Max.y : plot.PlotRect.Min.y;\n        yax.UpdateTransformCache();\n    }\n    // Equal axis constraint. Must happen after we set Pixels\n    // constrain equal axes for primary x and y if not approximately equal\n    // constrains x to y since x pixel size depends on y labels width, and causes feedback loops in opposite case\n    if (axis_equal) {\n        for (int i = 0; i < IMPLOT_NUM_X_AXES; ++i) {\n            ImPlotAxis& x_axis = plot.XAxis(i);\n            if (x_axis.OrthoAxis == NULL)\n                continue;\n            double xar = x_axis.GetAspect();\n            double yar = x_axis.OrthoAxis->GetAspect();\n            // edge case: user has set x range this frame, so fit y to x so that we honor their request for x range\n            // NB: because of feedback across several frames, the user's x request may not be perfectly honored\n            if (x_axis.HasRange)\n                x_axis.OrthoAxis->SetAspect(xar);\n            else if (!ImAlmostEqual(xar,yar) && !x_axis.OrthoAxis->IsInputLocked())\n                 x_axis.SetAspect(yar);\n        }\n    }\n\n    // INPUT ------------------------------------------------------------------\n    if (!ImHasFlag(plot.Flags, ImPlotFlags_NoInputs))\n        UpdateInput(plot);\n\n    // fit from FitNextPlotAxes or auto fit\n    for (int i = 0; i < ImAxis_COUNT; ++i) {\n        if (gp.NextPlotData.Fit[i] || plot.Axes[i].IsAutoFitting()) {\n            plot.FitThisFrame = true;\n            plot.Axes[i].FitThisFrame = true;\n        }\n    }\n\n    // RENDER -----------------------------------------------------------------\n\n    const float txt_height = ImGui::GetTextLineHeight();\n\n    // render frame\n    if (!ImHasFlag(plot.Flags, ImPlotFlags_NoFrame))\n        ImGui::RenderFrame(plot.FrameRect.Min, plot.FrameRect.Max, GetStyleColorU32(ImPlotCol_FrameBg), true, Style.FrameRounding);\n\n    // grid bg\n    DrawList.AddRectFilled(plot.PlotRect.Min, plot.PlotRect.Max, GetStyleColorU32(ImPlotCol_PlotBg));\n\n    // transform ticks\n    for (int i = 0; i < ImAxis_COUNT; i++) {\n        ImPlotAxis& axis = plot.Axes[i];\n        if (axis.WillRender()) {\n            for (int t = 0; t < axis.Ticks.Size; t++) {\n                ImPlotTick& tk = axis.Ticks.Ticks[t];\n                tk.PixelPos = IM_ROUND(axis.PlotToPixels(tk.PlotPos));\n            }\n        }\n    }\n\n    // render grid (background)\n    for (int i = 0; i < IMPLOT_NUM_X_AXES; i++) {\n        ImPlotAxis& x_axis = plot.XAxis(i);\n        if (x_axis.Enabled && x_axis.HasGridLines() && !x_axis.IsForeground())\n            RenderGridLinesX(DrawList, x_axis.Ticks, plot.PlotRect, x_axis.ColorMaj, x_axis.ColorMin, gp.Style.MajorGridSize.x, gp.Style.MinorGridSize.x);\n    }\n    for (int i = 0; i < IMPLOT_NUM_Y_AXES; i++) {\n        ImPlotAxis& y_axis = plot.YAxis(i);\n        if (y_axis.Enabled && y_axis.HasGridLines() && !y_axis.IsForeground())\n            RenderGridLinesY(DrawList, y_axis.Ticks, plot.PlotRect,  y_axis.ColorMaj, y_axis.ColorMin, gp.Style.MajorGridSize.y, gp.Style.MinorGridSize.y);\n    }\n\n    // render x axis button, label, tick labels\n    for (int i = 0; i < IMPLOT_NUM_X_AXES; i++) {\n        ImPlotAxis& ax = plot.XAxis(i);\n        if (!ax.Enabled)\n            continue;\n        if ((ax.Hovered || ax.Held) && !plot.Held)\n            DrawList.AddRectFilled(ax.HoverRect.Min, ax.HoverRect.Max, ax.Held ? ax.ColorAct : ax.ColorHov);\n        else if (ax.ColorHiLi != IM_COL32_BLACK_TRANS) {\n            DrawList.AddRectFilled(ax.HoverRect.Min, ax.HoverRect.Max, ax.ColorHiLi);\n            ax.ColorHiLi = IM_COL32_BLACK_TRANS;\n        }\n        else if (ax.ColorBg != IM_COL32_BLACK_TRANS) {\n            DrawList.AddRectFilled(ax.HoverRect.Min, ax.HoverRect.Max, ax.ColorBg);\n        }\n        const ImPlotTickCollection& tkc = ax.Ticks;\n        const bool opp = ax.IsOpposite();\n        if (ax.HasLabel()) {\n            const char* label        = plot.GetAxisLabel(ax);\n            const ImVec2 label_size  = ImGui::CalcTextSize(label);\n            const float label_offset = (ax.HasTickLabels() ? ax.Ticks.MaxSize.y + gp.Style.LabelPadding.y : 0.0f)\n                                     + (ax.IsTime() ? txt_height + gp.Style.LabelPadding.y : 0)\n                                     + gp.Style.LabelPadding.y;\n            const ImVec2 label_pos(plot.PlotRect.GetCenter().x - label_size.x * 0.5f,\n                                   opp ? ax.Datum1 - label_offset - label_size.y : ax.Datum1 + label_offset);\n            DrawList.AddText(label_pos, ax.ColorTxt, label);\n        }\n        if (ax.HasTickLabels()) {\n            for (int j = 0; j < tkc.Size; ++j) {\n                const ImPlotTick& tk = tkc.Ticks[j];\n                const float datum = ax.Datum1 + (opp ? (-gp.Style.LabelPadding.y -txt_height -tk.Level * (txt_height + gp.Style.LabelPadding.y))\n                                                     : gp.Style.LabelPadding.y + tk.Level * (txt_height + gp.Style.LabelPadding.y));\n                if (tk.ShowLabel && tk.PixelPos >= plot.PlotRect.Min.x - 1 && tk.PixelPos <= plot.PlotRect.Max.x + 1) {\n                    ImVec2 start(tk.PixelPos - 0.5f * tk.LabelSize.x, datum);\n                    DrawList.AddText(start, ax.ColorTxt, tkc.GetText(j));\n                }\n            }\n        }\n    }\n\n    // render y axis button, label, tick labels\n    for (int i = 0; i < IMPLOT_NUM_Y_AXES; i++) {\n        ImPlotAxis& ax = plot.YAxis(i);\n        if (!ax.Enabled)\n            continue;\n        if ((ax.Hovered || ax.Held) && !plot.Held)\n            DrawList.AddRectFilled(ax.HoverRect.Min, ax.HoverRect.Max, ax.Held ? ax.ColorAct : ax.ColorHov);\n        else if (ax.ColorHiLi != IM_COL32_BLACK_TRANS) {\n            DrawList.AddRectFilled(ax.HoverRect.Min, ax.HoverRect.Max, ax.ColorHiLi);\n            ax.ColorHiLi = IM_COL32_BLACK_TRANS;\n        }\n        else if (ax.ColorBg != IM_COL32_BLACK_TRANS) {\n            DrawList.AddRectFilled(ax.HoverRect.Min, ax.HoverRect.Max, ax.ColorBg);\n        }\n        const ImPlotTickCollection& tkc = ax.Ticks;\n        const bool opp = ax.IsOpposite();\n        if (ax.HasLabel()) {\n            const char* label        = plot.GetAxisLabel(ax);\n            const ImVec2 label_size  = CalcTextSizeVertical(label);\n            const float label_offset = (ax.HasTickLabels() ? ax.Ticks.MaxSize.x + gp.Style.LabelPadding.x : 0.0f)\n                                     + gp.Style.LabelPadding.x;\n            const ImVec2 label_pos(opp ? ax.Datum1 + label_offset : ax.Datum1 - label_offset - label_size.x,\n                                   plot.PlotRect.GetCenter().y + label_size.y * 0.5f);\n            AddTextVertical(&DrawList, label_pos, ax.ColorTxt, label);\n        }\n        if (ax.HasTickLabels()) {\n            for (int j = 0; j < tkc.Size; ++j) {\n                const ImPlotTick& tk = tkc.Ticks[j];\n                const float datum = ax.Datum1 + (opp ? gp.Style.LabelPadding.x : (-gp.Style.LabelPadding.x - tk.LabelSize.x));\n                if (tk.ShowLabel && tk.PixelPos >= plot.PlotRect.Min.y - 1 && tk.PixelPos <= plot.PlotRect.Max.y + 1) {\n                    ImVec2 start(datum, tk.PixelPos - 0.5f * tk.LabelSize.y);\n                    DrawList.AddText(start, ax.ColorTxt, tkc.GetText(j));\n                }\n            }\n        }\n    }\n\n\n    // clear legend (TODO: put elsewhere)\n    plot.Items.Legend.Reset();\n    // push ID to set item hashes (NB: !!!THIS PROBABLY NEEDS TO BE IN BEGIN PLOT!!!!)\n    ImGui::PushOverrideID(gp.CurrentItems->ID);\n}\n\n//-----------------------------------------------------------------------------\n// EndPlot()\n//-----------------------------------------------------------------------------\n\nvoid EndPlot() {\n    IM_ASSERT_USER_ERROR(GImPlot != NULL, \"No current context. Did you call ImPlot::CreateContext() or ImPlot::SetCurrentContext()?\");\n    IM_ASSERT_USER_ERROR(GImPlot->CurrentPlot != NULL, \"Mismatched BeginPlot()/EndPlot()!\");\n\n    SetupLock();\n\n    ImPlotContext& gp     = *GImPlot;\n    ImGuiContext &G       = *GImGui;\n    ImPlotPlot &plot      = *gp.CurrentPlot;\n    ImGuiWindow * Window  = G.CurrentWindow;\n    ImDrawList & DrawList = *Window->DrawList;\n    const ImGuiIO &   IO  = ImGui::GetIO();\n\n    // FINAL RENDER -----------------------------------------------------------\n\n    const bool render_border  = gp.Style.PlotBorderSize > 0 && gp.Style.Colors[ImPlotCol_PlotBorder].w > 0;\n    const bool any_x_held = plot.Held    || AnyAxesHeld(&plot.Axes[ImAxis_X1], IMPLOT_NUM_X_AXES);\n    const bool any_y_held = plot.Held    || AnyAxesHeld(&plot.Axes[ImAxis_Y1], IMPLOT_NUM_Y_AXES);\n\n    ImGui::PushClipRect(plot.FrameRect.Min, plot.FrameRect.Max, true);\n\n    // render grid (foreground)\n    for (int i = 0; i < IMPLOT_NUM_X_AXES; i++) {\n        ImPlotAxis& x_axis = plot.XAxis(i);\n        if (x_axis.Enabled && x_axis.HasGridLines() && x_axis.IsForeground())\n            RenderGridLinesX(DrawList, x_axis.Ticks, plot.PlotRect, x_axis.ColorMaj, x_axis.ColorMin, gp.Style.MajorGridSize.x, gp.Style.MinorGridSize.x);\n    }\n    for (int i = 0; i < IMPLOT_NUM_Y_AXES; i++) {\n        ImPlotAxis& y_axis = plot.YAxis(i);\n        if (y_axis.Enabled && y_axis.HasGridLines() && y_axis.IsForeground())\n            RenderGridLinesY(DrawList, y_axis.Ticks, plot.PlotRect,  y_axis.ColorMaj, y_axis.ColorMin, gp.Style.MajorGridSize.y, gp.Style.MinorGridSize.y);\n    }\n\n\n    // render title\n    if (plot.HasTitle()) {\n        ImU32 col = GetStyleColorU32(ImPlotCol_TitleText);\n        AddTextCentered(&DrawList,ImVec2(plot.PlotRect.GetCenter().x, plot.CanvasRect.Min.y),col,plot.GetTitle());\n    }\n\n    // render x ticks\n    int count_B = 0, count_T = 0;\n    for (int i = 0; i < IMPLOT_NUM_X_AXES; i++) {\n        const ImPlotAxis& ax = plot.XAxis(i);\n        if (!ax.Enabled)\n            continue;\n        const ImPlotTickCollection& tkc = ax.Ticks;\n        const bool opp = ax.IsOpposite();\n        const bool aux = ((opp && count_T > 0)||(!opp && count_B > 0));\n        if (ax.HasTickMarks()) {\n            const float direction = opp ? 1.0f : -1.0f;\n            for (int j = 0; j < tkc.Size; ++j) {\n                const ImPlotTick& tk = tkc.Ticks[j];\n                if (tk.Level != 0 || tk.PixelPos < plot.PlotRect.Min.x || tk.PixelPos > plot.PlotRect.Max.x)\n                    continue;\n                const ImVec2 start(tk.PixelPos, ax.Datum1);\n                const float len = (!aux && tk.Major) ? gp.Style.MajorTickLen.x  : gp.Style.MinorTickLen.x;\n                const float thk = (!aux && tk.Major) ? gp.Style.MajorTickSize.x : gp.Style.MinorTickSize.x;\n                DrawList.AddLine(start, start + ImVec2(0,direction*len), ax.ColorTick, thk);\n            }\n            if (aux || !render_border)\n                DrawList.AddLine(ImVec2(plot.PlotRect.Min.x,ax.Datum1), ImVec2(plot.PlotRect.Max.x,ax.Datum1), ax.ColorTick, gp.Style.MinorTickSize.x);\n        }\n        count_B += !opp;\n        count_T +=  opp;\n    }\n\n    // render y ticks\n    int count_L = 0, count_R = 0;\n    for (int i = 0; i < IMPLOT_NUM_Y_AXES; i++) {\n        const ImPlotAxis& ax = plot.YAxis(i);\n        if (!ax.Enabled)\n            continue;\n        const ImPlotTickCollection& tkc = ax.Ticks;\n        const bool opp = ax.IsOpposite();\n        const bool aux = ((opp && count_R > 0)||(!opp && count_L > 0));\n        if (ax.HasTickMarks()) {\n            const float direction = opp ? -1.0f : 1.0f;\n            for (int j = 0; j < tkc.Size; ++j) {\n                const ImPlotTick& tk = tkc.Ticks[j];\n                if (tk.Level != 0 || tk.PixelPos < plot.PlotRect.Min.y || tk.PixelPos > plot.PlotRect.Max.y)\n                    continue;\n                const ImVec2 start(ax.Datum1, tk.PixelPos);\n                const float len = (!aux && tk.Major) ? gp.Style.MajorTickLen.y  : gp.Style.MinorTickLen.y;\n                const float thk = (!aux && tk.Major) ? gp.Style.MajorTickSize.y : gp.Style.MinorTickSize.y;\n                DrawList.AddLine(start, start + ImVec2(direction*len,0), ax.ColorTick, thk);\n            }\n            if (aux || !render_border)\n                DrawList.AddLine(ImVec2(ax.Datum1, plot.PlotRect.Min.y), ImVec2(ax.Datum1, plot.PlotRect.Max.y), ax.ColorTick, gp.Style.MinorTickSize.y);\n        }\n        count_L += !opp;\n        count_R +=  opp;\n    }\n    ImGui::PopClipRect();\n\n    // render annotations\n    PushPlotClipRect();\n    for (int i = 0; i < gp.Annotations.Size; ++i) {\n        const char* txt       = gp.Annotations.GetText(i);\n        ImPlotAnnotation& an  = gp.Annotations.Annotations[i];\n        const ImVec2 txt_size = ImGui::CalcTextSize(txt);\n        const ImVec2 size     = txt_size + gp.Style.AnnotationPadding * 2;\n        ImVec2 pos            = an.Pos;\n        if (an.Offset.x == 0)\n            pos.x -= size.x / 2;\n        else if (an.Offset.x > 0)\n            pos.x += an.Offset.x;\n        else\n            pos.x -= size.x - an.Offset.x;\n        if (an.Offset.y == 0)\n            pos.y -= size.y / 2;\n        else if (an.Offset.y > 0)\n            pos.y += an.Offset.y;\n        else\n            pos.y -= size.y - an.Offset.y;\n        if (an.Clamp)\n            pos = ClampLabelPos(pos, size, plot.PlotRect.Min, plot.PlotRect.Max);\n        ImRect rect(pos,pos+size);\n        if (an.Offset.x != 0 || an.Offset.y != 0) {\n            ImVec2 corners[4] = {rect.GetTL(), rect.GetTR(), rect.GetBR(), rect.GetBL()};\n            int min_corner = 0;\n            float min_len = FLT_MAX;\n            for (int c = 0; c < 4; ++c) {\n                float len = ImLengthSqr(an.Pos - corners[c]);\n                if (len < min_len) {\n                    min_corner = c;\n                    min_len = len;\n                }\n            }\n            DrawList.AddLine(an.Pos, corners[min_corner], an.ColorBg);\n        }\n        DrawList.AddRectFilled(rect.Min, rect.Max, an.ColorBg);\n        DrawList.AddText(pos + gp.Style.AnnotationPadding, an.ColorFg, txt);\n    }\n\n    // render selection\n    if (plot.Selected)\n        RenderSelectionRect(DrawList, plot.SelectRect.Min + plot.PlotRect.Min, plot.SelectRect.Max + plot.PlotRect.Min, GetStyleColorVec4(ImPlotCol_Selection));\n\n    // render crosshairs\n    if (ImHasFlag(plot.Flags, ImPlotFlags_Crosshairs) && plot.Hovered && !(any_x_held || any_y_held) && !plot.Selecting && !plot.Items.Legend.Hovered) {\n        ImGui::SetMouseCursor(ImGuiMouseCursor_None);\n        ImVec2 xy = IO.MousePos;\n        ImVec2 h1(plot.PlotRect.Min.x, xy.y);\n        ImVec2 h2(xy.x - 5, xy.y);\n        ImVec2 h3(xy.x + 5, xy.y);\n        ImVec2 h4(plot.PlotRect.Max.x, xy.y);\n        ImVec2 v1(xy.x, plot.PlotRect.Min.y);\n        ImVec2 v2(xy.x, xy.y - 5);\n        ImVec2 v3(xy.x, xy.y + 5);\n        ImVec2 v4(xy.x, plot.PlotRect.Max.y);\n        ImU32 col = GetStyleColorU32(ImPlotCol_Crosshairs);\n        DrawList.AddLine(h1, h2, col);\n        DrawList.AddLine(h3, h4, col);\n        DrawList.AddLine(v1, v2, col);\n        DrawList.AddLine(v3, v4, col);\n    }\n\n    // render mouse pos\n    if (!ImHasFlag(plot.Flags, ImPlotFlags_NoMouseText) && (plot.Hovered || ImHasFlag(plot.MouseTextFlags, ImPlotMouseTextFlags_ShowAlways))) {\n\n        const bool no_aux = ImHasFlag(plot.MouseTextFlags, ImPlotMouseTextFlags_NoAuxAxes);\n        const bool no_fmt = ImHasFlag(plot.MouseTextFlags, ImPlotMouseTextFlags_NoFormat);\n\n        ImGuiTextBuffer& builder = gp.MousePosStringBuilder;\n        builder.Buf.shrink(0);\n        char buff[IMPLOT_LABEL_MAX_SIZE];\n\n        const int num_x = no_aux ? 1 : IMPLOT_NUM_X_AXES;\n        for (int i = 0; i < num_x; ++i) {\n            ImPlotAxis& x_axis = plot.XAxis(i);\n            if (!x_axis.Enabled)\n                continue;\n            if (i > 0)\n                builder.append(\", (\");\n            double v = x_axis.PixelsToPlot(IO.MousePos.x);\n            no_fmt ? DefaultFormatter(v,buff,IMPLOT_LABEL_MAX_SIZE,(void*)IMPLOT_LABEL_FORMAT)\n                   : LabelAxisValue(x_axis,v,buff,IMPLOT_LABEL_MAX_SIZE,true);\n            builder.append(buff);\n            if (i > 0)\n                builder.append(\")\");\n        }\n        builder.append(\", \");\n        const int num_y = no_aux ? 1 : IMPLOT_NUM_Y_AXES;\n        for (int i = 0; i < num_y; ++i) {\n            ImPlotAxis& y_axis = plot.YAxis(i);\n            if (!y_axis.Enabled)\n                continue;\n            if (i > 0)\n                builder.append(\", (\");\n            double v = y_axis.PixelsToPlot(IO.MousePos.y);\n            no_fmt ? DefaultFormatter(v,buff,IMPLOT_LABEL_MAX_SIZE,(void*)IMPLOT_LABEL_FORMAT)\n                   : LabelAxisValue(y_axis,v,buff,IMPLOT_LABEL_MAX_SIZE,true);\n            builder.append(buff);\n            if (i > 0)\n                builder.append(\")\");\n        }\n\n        if (!builder.empty()) {\n            const ImVec2 size = ImGui::CalcTextSize(builder.c_str());\n            const ImVec2 pos = GetLocationPos(plot.PlotRect, size, plot.MouseTextLocation, gp.Style.MousePosPadding);\n            DrawList.AddText(pos, GetStyleColorU32(ImPlotCol_InlayText), builder.c_str());\n        }\n    }\n    PopPlotClipRect();\n\n    // axis side switch\n    if (!plot.Held) {\n        ImVec2 mouse_pos = ImGui::GetIO().MousePos;\n        ImRect trigger_rect = plot.PlotRect;\n        trigger_rect.Expand(-10);\n        for (int i = 0; i < IMPLOT_NUM_X_AXES; ++i) {\n            ImPlotAxis& x_axis = plot.XAxis(i);\n            if (x_axis.Held && plot.PlotRect.Contains(mouse_pos)) {\n                const bool opp = ImHasFlag(x_axis.Flags, ImPlotAxisFlags_Opposite);\n                if (!opp) {\n                    ImRect rect(plot.PlotRect.Min.x - 5, plot.PlotRect.Min.y - 5,\n                                plot.PlotRect.Max.x + 5, plot.PlotRect.Min.y + 5);\n                    if (mouse_pos.y < plot.PlotRect.Max.y - 10)\n                        DrawList.AddRectFilled(rect.Min, rect.Max, x_axis.ColorHov);\n                    if (rect.Contains(mouse_pos))\n                        x_axis.Flags |= ImPlotAxisFlags_Opposite;\n                }\n                else {\n                    ImRect rect(plot.PlotRect.Min.x - 5, plot.PlotRect.Max.y - 5,\n                                plot.PlotRect.Max.x + 5, plot.PlotRect.Max.y + 5);\n                    if (mouse_pos.y > plot.PlotRect.Min.y + 10)\n                        DrawList.AddRectFilled(rect.Min, rect.Max, x_axis.ColorHov);\n                    if (rect.Contains(mouse_pos))\n                        x_axis.Flags &= ~ImPlotAxisFlags_Opposite;\n                }\n            }\n        }\n        for (int i = 0; i < IMPLOT_NUM_Y_AXES; ++i) {\n            ImPlotAxis& y_axis = plot.YAxis(i);\n            if (y_axis.Held && plot.PlotRect.Contains(mouse_pos)) {\n                const bool opp = ImHasFlag(y_axis.Flags, ImPlotAxisFlags_Opposite);\n                if (!opp) {\n                    ImRect rect(plot.PlotRect.Max.x - 5, plot.PlotRect.Min.y - 5,\n                                plot.PlotRect.Max.x + 5, plot.PlotRect.Max.y + 5);\n                    if (mouse_pos.x > plot.PlotRect.Min.x + 10)\n                        DrawList.AddRectFilled(rect.Min, rect.Max, y_axis.ColorHov);\n                    if (rect.Contains(mouse_pos))\n                        y_axis.Flags |= ImPlotAxisFlags_Opposite;\n                }\n                else {\n                    ImRect rect(plot.PlotRect.Min.x - 5, plot.PlotRect.Min.y - 5,\n                                plot.PlotRect.Min.x + 5, plot.PlotRect.Max.y + 5);\n                    if (mouse_pos.x < plot.PlotRect.Max.x - 10)\n                        DrawList.AddRectFilled(rect.Min, rect.Max, y_axis.ColorHov);\n                    if (rect.Contains(mouse_pos))\n                        y_axis.Flags &= ~ImPlotAxisFlags_Opposite;\n                }\n            }\n        }\n    }\n\n    // reset legend hovers\n    plot.Items.Legend.Hovered = false;\n    for (int i = 0; i < plot.Items.GetItemCount(); ++i)\n        plot.Items.GetItemByIndex(i)->LegendHovered = false;\n    // render legend\n    if (!ImHasFlag(plot.Flags, ImPlotFlags_NoLegend) && plot.Items.GetLegendCount() > 0) {\n        ImPlotLegend& legend = plot.Items.Legend;\n        const bool   legend_out  = ImHasFlag(legend.Flags, ImPlotLegendFlags_Outside);\n        const bool   legend_horz = ImHasFlag(legend.Flags, ImPlotLegendFlags_Horizontal);\n        const ImVec2 legend_size = CalcLegendSize(plot.Items, gp.Style.LegendInnerPadding, gp.Style.LegendSpacing, !legend_horz);\n        const ImVec2 legend_pos  = GetLocationPos(legend_out ? plot.FrameRect : plot.PlotRect,\n                                                  legend_size,\n                                                  legend.Location,\n                                                  legend_out ? gp.Style.PlotPadding : gp.Style.LegendPadding);\n        legend.Rect = ImRect(legend_pos, legend_pos + legend_size);\n        // test hover\n        legend.Hovered = ImGui::IsWindowHovered() && legend.Rect.Contains(IO.MousePos);\n\n        if (legend_out)\n            ImGui::PushClipRect(plot.FrameRect.Min, plot.FrameRect.Max, true);\n        else\n            PushPlotClipRect();\n        ImU32  col_bg      = GetStyleColorU32(ImPlotCol_LegendBg);\n        ImU32  col_bd      = GetStyleColorU32(ImPlotCol_LegendBorder);\n        DrawList.AddRectFilled(legend.Rect.Min, legend.Rect.Max, col_bg);\n        DrawList.AddRect(legend.Rect.Min, legend.Rect.Max, col_bd);\n        bool legend_contextable = ShowLegendEntries(plot.Items, legend.Rect, legend.Hovered, gp.Style.LegendInnerPadding, gp.Style.LegendSpacing, !legend_horz, DrawList)\n                                && !ImHasFlag(legend.Flags, ImPlotLegendFlags_NoMenus);\n\n        // main ctx menu\n        if (gp.OpenContextThisFrame && legend_contextable && !ImHasFlag(plot.Flags, ImPlotFlags_NoMenus))\n            ImGui::OpenPopup(\"##LegendContext\");\n        ImGui::PopClipRect();\n        if (ImGui::BeginPopup(\"##LegendContext\")) {\n            ImGui::Text(\"Legend\"); ImGui::Separator();\n            if (ShowLegendContextMenu(legend, !ImHasFlag(plot.Flags, ImPlotFlags_NoLegend)))\n                ImFlipFlag(plot.Flags, ImPlotFlags_NoLegend);\n            ImGui::EndPopup();\n        }\n    }\n    else {\n        plot.Items.Legend.Rect = ImRect();\n    }\n\n    // render border\n    if (render_border)\n        DrawList.AddRect(plot.PlotRect.Min, plot.PlotRect.Max, GetStyleColorU32(ImPlotCol_PlotBorder), 0, ImDrawFlags_RoundCornersAll, gp.Style.PlotBorderSize);\n\n    // render tags\n    for (int i = 0; i < gp.Tags.Size; ++i) {\n        ImPlotTag& tag  = gp.Tags.Tags[i];\n        ImPlotAxis& axis = plot.Axes[tag.Axis];\n        if (!axis.Enabled || !axis.Range.Contains(tag.Value))\n            continue;\n        const char* txt = gp.Tags.GetText(i);\n        ImVec2 text_size = ImGui::CalcTextSize(txt);\n        ImVec2 size = text_size + gp.Style.AnnotationPadding * 2;\n        ImVec2 pos;\n        axis.Ticks.OverrideSizeLate(size);\n        float pix = IM_ROUND(axis.PlotToPixels(tag.Value));\n        if (axis.Vertical) {\n            if (axis.IsOpposite()) {\n                pos = ImVec2(axis.Datum1 + gp.Style.LabelPadding.x, pix - size.y * 0.5f);\n                DrawList.AddTriangleFilled(ImVec2(axis.Datum1,pix), pos, pos + ImVec2(0,size.y), tag.ColorBg);\n            }\n            else {\n                pos = ImVec2(axis.Datum1 - size.x - gp.Style.LabelPadding.x, pix - size.y * 0.5f);\n                DrawList.AddTriangleFilled(pos + ImVec2(size.x,0), ImVec2(axis.Datum1,pix), pos+size, tag.ColorBg);\n            }\n        }\n        else {\n            if (axis.IsOpposite()) {\n                pos = ImVec2(pix - size.x * 0.5f, axis.Datum1 - size.y - gp.Style.LabelPadding.y );\n                DrawList.AddTriangleFilled(pos + ImVec2(0,size.y), pos + size, ImVec2(pix,axis.Datum1), tag.ColorBg);\n            }\n            else {\n                pos = ImVec2(pix - size.x * 0.5f, axis.Datum1 + gp.Style.LabelPadding.y);\n                DrawList.AddTriangleFilled(pos, ImVec2(pix,axis.Datum1), pos + ImVec2(size.x, 0), tag.ColorBg);\n            }\n        }\n        DrawList.AddRectFilled(pos,pos+size,tag.ColorBg);\n        DrawList.AddText(pos+gp.Style.AnnotationPadding,tag.ColorFg,txt);\n    }\n\n    // FIT DATA --------------------------------------------------------------\n    const bool axis_equal = ImHasFlag(plot.Flags, ImPlotFlags_Equal);\n    if (plot.FitThisFrame) {\n        for (int i = 0; i < IMPLOT_NUM_X_AXES; i++) {\n            ImPlotAxis& x_axis = plot.XAxis(i);\n            if (x_axis.FitThisFrame) {\n                x_axis.ApplyFit(gp.Style.FitPadding.x);\n                if (axis_equal && x_axis.OrthoAxis != NULL) {\n                    double aspect = x_axis.GetAspect();\n                    ImPlotAxis& y_axis = *x_axis.OrthoAxis;\n                    if (y_axis.FitThisFrame) {\n                        y_axis.ApplyFit(gp.Style.FitPadding.y);\n                        y_axis.FitThisFrame = false;\n                        aspect = ImMax(aspect, y_axis.GetAspect());\n                    }\n                    x_axis.SetAspect(aspect);\n                    y_axis.SetAspect(aspect);\n                }\n            }\n        }\n        for (int i = 0; i < IMPLOT_NUM_Y_AXES; i++) {\n            ImPlotAxis& y_axis = plot.YAxis(i);\n            if (y_axis.FitThisFrame) {\n                y_axis.ApplyFit(gp.Style.FitPadding.y);\n                if (axis_equal && y_axis.OrthoAxis != NULL) {\n                    double aspect = y_axis.GetAspect();\n                    ImPlotAxis& x_axis = *y_axis.OrthoAxis;\n                    if (x_axis.FitThisFrame) {\n                        x_axis.ApplyFit(gp.Style.FitPadding.x);\n                        x_axis.FitThisFrame = false;\n                        aspect = ImMax(x_axis.GetAspect(), aspect);\n                    }\n                    x_axis.SetAspect(aspect);\n                    y_axis.SetAspect(aspect);\n                }\n            }\n        }\n        plot.FitThisFrame = false;\n    }\n\n    // CONTEXT MENUS -----------------------------------------------------------\n\n    ImGui::PushOverrideID(plot.ID);\n\n    const bool can_ctx = gp.OpenContextThisFrame &&\n                         !ImHasFlag(plot.Flags, ImPlotFlags_NoMenus) &&\n                         !plot.Items.Legend.Hovered;\n\n\n\n    // main ctx menu\n    if (can_ctx && plot.Hovered)\n        ImGui::OpenPopup(\"##PlotContext\");\n    if (ImGui::BeginPopup(\"##PlotContext\")) {\n        ShowPlotContextMenu(plot);\n        ImGui::EndPopup();\n    }\n\n    // axes ctx menus\n    for (int i = 0; i < IMPLOT_NUM_X_AXES; ++i) {\n        ImGui::PushID(i);\n        ImPlotAxis& x_axis = plot.XAxis(i);\n        if (can_ctx && x_axis.Hovered && x_axis.HasMenus())\n            ImGui::OpenPopup(\"##XContext\");\n        if (ImGui::BeginPopup(\"##XContext\")) {\n            ImGui::Text(x_axis.HasLabel() ? plot.GetAxisLabel(x_axis) :  i == 0 ? \"X-Axis\" : \"X-Axis %d\", i + 1);\n            ImGui::Separator();\n            ShowAxisContextMenu(x_axis, axis_equal ? x_axis.OrthoAxis : NULL, true);\n            ImGui::EndPopup();\n        }\n        ImGui::PopID();\n    }\n    for (int i = 0; i < IMPLOT_NUM_Y_AXES; ++i) {\n        ImGui::PushID(i);\n        ImPlotAxis& y_axis = plot.YAxis(i);\n        if (can_ctx && y_axis.Hovered && y_axis.HasMenus())\n            ImGui::OpenPopup(\"##YContext\");\n        if (ImGui::BeginPopup(\"##YContext\")) {\n            ImGui::Text(y_axis.HasLabel() ? plot.GetAxisLabel(y_axis) : i == 0 ? \"Y-Axis\" : \"Y-Axis %d\", i + 1);\n            ImGui::Separator();\n            ShowAxisContextMenu(y_axis, axis_equal ? y_axis.OrthoAxis : NULL, false);\n            ImGui::EndPopup();\n        }\n        ImGui::PopID();\n    }\n    ImGui::PopID();\n\n    // LINKED AXES ------------------------------------------------------------\n\n    for (int i = 0; i < ImAxis_COUNT; ++i)\n        plot.Axes[i].PushLinks();\n\n\n    // CLEANUP ----------------------------------------------------------------\n\n    // remove items\n    if (gp.CurrentItems == &plot.Items)\n        gp.CurrentItems = NULL;\n    // reset the plot items for the next frame\n    for (int i = 0; i < plot.Items.GetItemCount(); ++i) {\n        plot.Items.GetItemByIndex(i)->SeenThisFrame = false;\n    }\n\n    // mark the plot as initialized, i.e. having made it through one frame completely\n    plot.Initialized = true;\n    // Pop ImGui::PushID at the end of BeginPlot\n    ImGui::PopID();\n    // Reset context for next plot\n    ResetCtxForNextPlot(GImPlot);\n\n    // setup next subplot\n    if (gp.CurrentSubplot != NULL) {\n        ImGui::PopID();\n        SubplotNextCell();\n    }\n}\n\n//-----------------------------------------------------------------------------\n// BEGIN/END SUBPLOT\n//-----------------------------------------------------------------------------\n\nstatic const float SUBPLOT_BORDER_SIZE             = 1.0f;\nstatic const float SUBPLOT_SPLITTER_HALF_THICKNESS = 4.0f;\nstatic const float SUBPLOT_SPLITTER_FEEDBACK_TIMER = 0.06f;\n\nvoid SubplotSetCell(int row, int col) {\n    ImPlotContext& gp      = *GImPlot;\n    ImPlotSubplot& subplot = *gp.CurrentSubplot;\n    if (row >= subplot.Rows || col >= subplot.Cols)\n        return;\n    float xoff = 0;\n    float yoff = 0;\n    for (int c = 0; c < col; ++c)\n        xoff += subplot.ColRatios[c];\n    for (int r = 0; r < row; ++r)\n        yoff += subplot.RowRatios[r];\n    const ImVec2 grid_size = subplot.GridRect.GetSize();\n    ImVec2 cpos            = subplot.GridRect.Min + ImVec2(xoff*grid_size.x,yoff*grid_size.y);\n    cpos.x = IM_ROUND(cpos.x);\n    cpos.y = IM_ROUND(cpos.y);\n    ImGui::GetCurrentWindow()->DC.CursorPos =  cpos;\n    // set cell size\n    subplot.CellSize.x = IM_ROUND(subplot.GridRect.GetWidth()  * subplot.ColRatios[col]);\n    subplot.CellSize.y = IM_ROUND(subplot.GridRect.GetHeight() * subplot.RowRatios[row]);\n    // setup links\n    const bool lx = ImHasFlag(subplot.Flags, ImPlotSubplotFlags_LinkAllX);\n    const bool ly = ImHasFlag(subplot.Flags, ImPlotSubplotFlags_LinkAllY);\n    const bool lr = ImHasFlag(subplot.Flags, ImPlotSubplotFlags_LinkRows);\n    const bool lc = ImHasFlag(subplot.Flags, ImPlotSubplotFlags_LinkCols);\n\n    SetNextAxisLinks(ImAxis_X1, lx ? &subplot.ColLinkData[0].Min : lc ? &subplot.ColLinkData[col].Min : NULL,\n                                lx ? &subplot.ColLinkData[0].Max : lc ? &subplot.ColLinkData[col].Max : NULL);\n    SetNextAxisLinks(ImAxis_Y1, ly ? &subplot.RowLinkData[0].Min : lr ? &subplot.RowLinkData[row].Min : NULL,\n                                ly ? &subplot.RowLinkData[0].Max : lr ? &subplot.RowLinkData[row].Max : NULL);\n    // setup alignment\n    if (!ImHasFlag(subplot.Flags, ImPlotSubplotFlags_NoAlign)) {\n        gp.CurrentAlignmentH = &subplot.RowAlignmentData[row];\n        gp.CurrentAlignmentV = &subplot.ColAlignmentData[col];\n    }\n    // set idx\n    if (ImHasFlag(subplot.Flags, ImPlotSubplotFlags_ColMajor))\n        subplot.CurrentIdx = col * subplot.Rows + row;\n    else\n        subplot.CurrentIdx = row * subplot.Cols + col;\n}\n\nvoid SubplotSetCell(int idx) {\n    ImPlotContext& gp      = *GImPlot;\n    ImPlotSubplot& subplot = *gp.CurrentSubplot;\n    if (idx >= subplot.Rows * subplot.Cols)\n        return;\n    int row = 0, col = 0;\n    if (ImHasFlag(subplot.Flags, ImPlotSubplotFlags_ColMajor)) {\n        row = idx % subplot.Rows;\n        col = idx / subplot.Rows;\n    }\n    else {\n        row = idx / subplot.Cols;\n        col = idx % subplot.Cols;\n    }\n    return SubplotSetCell(row, col);\n}\n\nvoid SubplotNextCell() {\n    ImPlotContext& gp      = *GImPlot;\n    ImPlotSubplot& subplot = *gp.CurrentSubplot;\n    SubplotSetCell(++subplot.CurrentIdx);\n}\n\nbool BeginSubplots(const char* title, int rows, int cols, const ImVec2& size, ImPlotSubplotFlags flags, float* row_sizes, float* col_sizes) {\n    IM_ASSERT_USER_ERROR(rows > 0 && cols > 0, \"Invalid sizing arguments!\");\n    IM_ASSERT_USER_ERROR(GImPlot != NULL, \"No current context. Did you call ImPlot::CreateContext() or ImPlot::SetCurrentContext()?\");\n    IM_ASSERT_USER_ERROR(GImPlot->CurrentSubplot == NULL, \"Mismatched BeginSubplots()/EndSubplots()!\");\n    ImPlotContext& gp = *GImPlot;\n    ImGuiContext &G = *GImGui;\n    ImGuiWindow * Window = G.CurrentWindow;\n    if (Window->SkipItems)\n        return false;\n    const ImGuiID ID = Window->GetID(title);\n    bool just_created = gp.Subplots.GetByKey(ID) == NULL;\n    gp.CurrentSubplot = gp.Subplots.GetOrAddByKey(ID);\n    ImPlotSubplot& subplot = *gp.CurrentSubplot;\n    subplot.ID       = ID;\n    subplot.Items.ID = ID - 1;\n    subplot.HasTitle = ImGui::FindRenderedTextEnd(title, NULL) != title;\n    // push ID\n    ImGui::PushID(ID);\n\n    if (just_created)\n        subplot.Flags = flags;\n    else if (flags != subplot.PreviousFlags)\n        subplot.Flags = flags;\n    subplot.PreviousFlags = flags;\n\n    // check for change in rows and cols\n    if (subplot.Rows != rows || subplot.Cols != cols) {\n        subplot.RowAlignmentData.resize(rows);\n        subplot.RowLinkData.resize(rows);\n        subplot.RowRatios.resize(rows);\n        for (int r = 0; r < rows; ++r) {\n            subplot.RowAlignmentData[r].Reset();\n            subplot.RowLinkData[r] = ImPlotRange(0,1);\n            subplot.RowRatios[r] = 1.0f / rows;\n        }\n        subplot.ColAlignmentData.resize(cols);\n        subplot.ColLinkData.resize(cols);\n        subplot.ColRatios.resize(cols);\n        for (int c = 0; c < cols; ++c) {\n            subplot.ColAlignmentData[c].Reset();\n            subplot.ColLinkData[c] = ImPlotRange(0,1);\n            subplot.ColRatios[c] = 1.0f / cols;\n        }\n    }\n    // check incoming size requests\n    float row_sum = 0, col_sum = 0;\n    if (row_sizes != NULL) {\n        row_sum = ImSum(row_sizes, rows);\n        for (int r = 0; r < rows; ++r)\n            subplot.RowRatios[r] = row_sizes[r] / row_sum;\n    }\n    if (col_sizes != NULL) {\n        col_sum = ImSum(col_sizes, cols);\n        for (int c = 0; c < cols; ++c)\n            subplot.ColRatios[c] = col_sizes[c] / col_sum;\n    }\n    subplot.Rows = rows;\n    subplot.Cols = cols;\n\n    // calc plot frame sizes\n    ImVec2 title_size(0.0f, 0.0f);\n    if (!ImHasFlag(subplot.Flags, ImPlotSubplotFlags_NoTitle))\n         title_size = ImGui::CalcTextSize(title, NULL, true);\n    const float pad_top = title_size.x > 0.0f ? title_size.y + gp.Style.LabelPadding.y : 0;\n    const ImVec2 half_pad = gp.Style.PlotPadding/2;\n    const ImVec2 frame_size = ImGui::CalcItemSize(size, gp.Style.PlotDefaultSize.x, gp.Style.PlotDefaultSize.y);\n    subplot.FrameRect = ImRect(Window->DC.CursorPos, Window->DC.CursorPos + frame_size);\n    subplot.GridRect.Min = subplot.FrameRect.Min + half_pad + ImVec2(0,pad_top);\n    subplot.GridRect.Max = subplot.FrameRect.Max - half_pad;\n    subplot.FrameHovered = subplot.FrameRect.Contains(ImGui::GetMousePos()) && ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows);\n\n    // outside legend adjustments (TODO: make function)\n    const bool share_items = ImHasFlag(subplot.Flags, ImPlotSubplotFlags_ShareItems);\n    if (share_items)\n        gp.CurrentItems = &subplot.Items;\n    if (share_items && !ImHasFlag(subplot.Flags, ImPlotSubplotFlags_NoLegend) && subplot.Items.GetLegendCount() > 0) {\n        ImPlotLegend& legend = subplot.Items.Legend;\n        const bool horz = ImHasFlag(legend.Flags, ImPlotLegendFlags_Horizontal);\n        const ImVec2 legend_size = CalcLegendSize(subplot.Items, gp.Style.LegendInnerPadding, gp.Style.LegendSpacing, !horz);\n        const bool west = ImHasFlag(legend.Location, ImPlotLocation_West) && !ImHasFlag(legend.Location, ImPlotLocation_East);\n        const bool east = ImHasFlag(legend.Location, ImPlotLocation_East) && !ImHasFlag(legend.Location, ImPlotLocation_West);\n        const bool north = ImHasFlag(legend.Location, ImPlotLocation_North) && !ImHasFlag(legend.Location, ImPlotLocation_South);\n        const bool south = ImHasFlag(legend.Location, ImPlotLocation_South) && !ImHasFlag(legend.Location, ImPlotLocation_North);\n        if ((west && !horz) || (west && horz && !north && !south))\n            subplot.GridRect.Min.x += (legend_size.x + gp.Style.LegendPadding.x);\n        if ((east && !horz) || (east && horz && !north && !south))\n            subplot.GridRect.Max.x -= (legend_size.x + gp.Style.LegendPadding.x);\n        if ((north && horz) || (north && !horz && !west && !east))\n            subplot.GridRect.Min.y += (legend_size.y + gp.Style.LegendPadding.y);\n        if ((south && horz) || (south && !horz && !west && !east))\n            subplot.GridRect.Max.y -= (legend_size.y + gp.Style.LegendPadding.y);\n    }\n\n    // render single background frame\n    ImGui::RenderFrame(subplot.FrameRect.Min, subplot.FrameRect.Max, GetStyleColorU32(ImPlotCol_FrameBg), true, ImGui::GetStyle().FrameRounding);\n    // render title\n    if (title_size.x > 0.0f && !ImHasFlag(subplot.Flags, ImPlotFlags_NoTitle)) {\n        const ImU32 col = GetStyleColorU32(ImPlotCol_TitleText);\n        AddTextCentered(ImGui::GetWindowDrawList(),ImVec2(subplot.GridRect.GetCenter().x, subplot.GridRect.Min.y - pad_top + half_pad.y),col,title);\n    }\n\n    // render splitters\n    if (!ImHasFlag(subplot.Flags, ImPlotSubplotFlags_NoResize)) {\n        ImDrawList& DrawList = *ImGui::GetWindowDrawList();\n        const ImU32 hov_col = ImGui::ColorConvertFloat4ToU32(GImGui->Style.Colors[ImGuiCol_SeparatorHovered]);\n        const ImU32 act_col = ImGui::ColorConvertFloat4ToU32(GImGui->Style.Colors[ImGuiCol_SeparatorActive]);\n        float xpos = subplot.GridRect.Min.x;\n        float ypos = subplot.GridRect.Min.y;\n        int separator = 1;\n        // bool pass = false;\n        for (int r = 0; r < subplot.Rows-1; ++r) {\n            ypos += subplot.RowRatios[r] * subplot.GridRect.GetHeight();\n            const ImGuiID sep_id = subplot.ID + separator;\n            ImGui::KeepAliveID(sep_id);\n            const ImRect sep_bb = ImRect(subplot.GridRect.Min.x, ypos-SUBPLOT_SPLITTER_HALF_THICKNESS, subplot.GridRect.Max.x, ypos+SUBPLOT_SPLITTER_HALF_THICKNESS);\n            bool sep_hov = false, sep_hld = false;\n            const bool sep_clk = ImGui::ButtonBehavior(sep_bb, sep_id, &sep_hov, &sep_hld, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_AllowItemOverlap | ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnDoubleClick);\n            if ((sep_hov && G.HoveredIdTimer > SUBPLOT_SPLITTER_FEEDBACK_TIMER) || sep_hld) {\n                if (sep_clk && ImGui::IsMouseDoubleClicked(0)) {\n                    float p = (subplot.RowRatios[r] + subplot.RowRatios[r+1])/2;\n                    subplot.RowRatios[r] = subplot.RowRatios[r+1] = p;\n                }\n                if (sep_clk) {\n                    subplot.TempSizes[0] = subplot.RowRatios[r];\n                    subplot.TempSizes[1] = subplot.RowRatios[r+1];\n                }\n                if (sep_hld) {\n                    float dp = ImGui::GetMouseDragDelta(0).y  / subplot.GridRect.GetHeight();\n                    if (subplot.TempSizes[0] + dp > 0.1f && subplot.TempSizes[1] - dp > 0.1f) {\n                        subplot.RowRatios[r]   = subplot.TempSizes[0] + dp;\n                        subplot.RowRatios[r+1] = subplot.TempSizes[1] - dp;\n                    }\n                }\n                DrawList.AddLine(ImVec2(IM_ROUND(subplot.GridRect.Min.x),IM_ROUND(ypos)),\n                                 ImVec2(IM_ROUND(subplot.GridRect.Max.x),IM_ROUND(ypos)),\n                                 sep_hld ? act_col : hov_col, SUBPLOT_BORDER_SIZE);\n                ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeNS);\n            }\n            separator++;\n        }\n        for (int c = 0; c < subplot.Cols-1; ++c) {\n            xpos += subplot.ColRatios[c] * subplot.GridRect.GetWidth();\n            const ImGuiID sep_id = subplot.ID + separator;\n            ImGui::KeepAliveID(sep_id);\n            const ImRect sep_bb = ImRect(xpos-SUBPLOT_SPLITTER_HALF_THICKNESS, subplot.GridRect.Min.y, xpos+SUBPLOT_SPLITTER_HALF_THICKNESS, subplot.GridRect.Max.y);\n            bool sep_hov = false, sep_hld = false;\n            const bool sep_clk = ImGui::ButtonBehavior(sep_bb, sep_id, &sep_hov, &sep_hld, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_AllowItemOverlap | ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnDoubleClick);\n            if ((sep_hov && G.HoveredIdTimer > SUBPLOT_SPLITTER_FEEDBACK_TIMER) || sep_hld) {\n                if (sep_clk && ImGui::IsMouseDoubleClicked(0)) {\n                    float p = (subplot.ColRatios[c] + subplot.ColRatios[c+1])/2;\n                    subplot.ColRatios[c] = subplot.ColRatios[c+1] = p;\n                }\n                if (sep_clk) {\n                    subplot.TempSizes[0] = subplot.ColRatios[c];\n                    subplot.TempSizes[1] = subplot.ColRatios[c+1];\n                }\n                if (sep_hld) {\n                    float dp = ImGui::GetMouseDragDelta(0).x / subplot.GridRect.GetWidth();\n                    if (subplot.TempSizes[0] + dp > 0.1f && subplot.TempSizes[1] - dp > 0.1f) {\n                        subplot.ColRatios[c]   = subplot.TempSizes[0] + dp;\n                        subplot.ColRatios[c+1] = subplot.TempSizes[1] - dp;\n                    }\n                }\n                DrawList.AddLine(ImVec2(IM_ROUND(xpos),IM_ROUND(subplot.GridRect.Min.y)),\n                                 ImVec2(IM_ROUND(xpos),IM_ROUND(subplot.GridRect.Max.y)),\n                                 sep_hld ? act_col : hov_col, SUBPLOT_BORDER_SIZE);\n                ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeEW);\n            }\n            separator++;\n        }\n    }\n\n    // set outgoing sizes\n    if (row_sizes != NULL) {\n        for (int r = 0; r < rows; ++r)\n            row_sizes[r] = subplot.RowRatios[r] * row_sum;\n    }\n    if (col_sizes != NULL) {\n        for (int c = 0; c < cols; ++c)\n            col_sizes[c] = subplot.ColRatios[c] * col_sum;\n    }\n\n    // push styling\n    PushStyleColor(ImPlotCol_FrameBg, IM_COL32_BLACK_TRANS);\n    PushStyleVar(ImPlotStyleVar_PlotPadding, half_pad);\n    PushStyleVar(ImPlotStyleVar_PlotMinSize, ImVec2(0,0));\n    ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize,0);\n\n    // set initial cursor pos\n    Window->DC.CursorPos = subplot.GridRect.Min;\n    // begin alignments\n    for (int r = 0; r < subplot.Rows; ++r)\n        subplot.RowAlignmentData[r].Begin();\n    for (int c = 0; c < subplot.Cols; ++c)\n        subplot.ColAlignmentData[c].Begin();\n    // clear legend data\n    subplot.Items.Legend.Reset();\n    // Setup first subplot\n    SubplotSetCell(0,0);\n    return true;\n}\n\nvoid EndSubplots() {\n    IM_ASSERT_USER_ERROR(GImPlot != NULL, \"No current context. Did you call ImPlot::CreateContext() or ImPlot::SetCurrentContext()?\");\n    IM_ASSERT_USER_ERROR(GImPlot->CurrentSubplot != NULL, \"Mismatched BeginSubplots()/EndSubplots()!\");\n    ImPlotContext& gp = *GImPlot;\n    ImPlotSubplot& subplot = *GImPlot->CurrentSubplot;\n    // set alignments\n    for (int r = 0; r < subplot.Rows; ++r)\n        subplot.RowAlignmentData[r].End();\n    for (int c = 0; c < subplot.Cols; ++c)\n        subplot.ColAlignmentData[c].End();\n    // pop styling\n    PopStyleColor();\n    PopStyleVar();\n    PopStyleVar();\n    ImGui::PopStyleVar();\n    // legend\n    subplot.Items.Legend.Hovered = false;\n    for (int i = 0; i < subplot.Items.GetItemCount(); ++i)\n        subplot.Items.GetItemByIndex(i)->LegendHovered = false;\n    // render legend\n    const bool share_items = ImHasFlag(subplot.Flags, ImPlotSubplotFlags_ShareItems);\n    ImDrawList& DrawList = *ImGui::GetWindowDrawList();\n    if (share_items && !ImHasFlag(subplot.Flags, ImPlotSubplotFlags_NoLegend) && subplot.Items.GetLegendCount() > 0) {\n        const bool   legend_horz = ImHasFlag(subplot.Items.Legend.Flags, ImPlotLegendFlags_Horizontal);\n        const ImVec2 legend_size = CalcLegendSize(subplot.Items, gp.Style.LegendInnerPadding, gp.Style.LegendSpacing, !legend_horz);\n        const ImVec2 legend_pos  = GetLocationPos(subplot.FrameRect, legend_size, subplot.Items.Legend.Location, gp.Style.PlotPadding);\n        subplot.Items.Legend.Rect = ImRect(legend_pos, legend_pos + legend_size);\n        subplot.Items.Legend.Hovered = subplot.FrameHovered && subplot.Items.Legend.Rect.Contains(ImGui::GetIO().MousePos);\n        ImGui::PushClipRect(subplot.FrameRect.Min, subplot.FrameRect.Max, true);\n        ImU32  col_bg      = GetStyleColorU32(ImPlotCol_LegendBg);\n        ImU32  col_bd      = GetStyleColorU32(ImPlotCol_LegendBorder);\n        DrawList.AddRectFilled(subplot.Items.Legend.Rect.Min, subplot.Items.Legend.Rect.Max, col_bg);\n        DrawList.AddRect(subplot.Items.Legend.Rect.Min, subplot.Items.Legend.Rect.Max, col_bd);\n        bool legend_contextable = ShowLegendEntries(subplot.Items, subplot.Items.Legend.Rect, subplot.Items.Legend.Hovered, gp.Style.LegendInnerPadding, gp.Style.LegendSpacing, !legend_horz, DrawList)\n                                && !ImHasFlag(subplot.Items.Legend.Flags, ImPlotLegendFlags_NoMenus);\n        if (legend_contextable && !ImHasFlag(subplot.Flags, ImPlotSubplotFlags_NoMenus) && ImGui::GetIO().MouseReleased[gp.InputMap.Menu])\n            ImGui::OpenPopup(\"##LegendContext\");\n        ImGui::PopClipRect();\n        if (ImGui::BeginPopup(\"##LegendContext\")) {\n            ImGui::Text(\"Legend\"); ImGui::Separator();\n            if (ShowLegendContextMenu(subplot.Items.Legend, !ImHasFlag(subplot.Flags, ImPlotFlags_NoLegend)))\n                ImFlipFlag(subplot.Flags, ImPlotFlags_NoLegend);\n            ImGui::EndPopup();\n        }\n    }\n    else {\n        subplot.Items.Legend.Rect = ImRect();\n    }\n    // remove items\n    if (gp.CurrentItems == &subplot.Items)\n        gp.CurrentItems = NULL;\n    // reset the plot items for the next frame (TODO: put this elswhere)\n    for (int i = 0; i < subplot.Items.GetItemCount(); ++i) {\n        subplot.Items.GetItemByIndex(i)->SeenThisFrame = false;\n    }\n    // pop id\n    ImGui::PopID();\n    // set DC back correctly\n    GImGui->CurrentWindow->DC.CursorPos = subplot.FrameRect.Min;\n    ImGui::Dummy(subplot.FrameRect.GetSize());\n    ResetCtxForNextSubplot(GImPlot);\n\n}\n\n//-----------------------------------------------------------------------------\n// [SECTION] Plot Utils\n//-----------------------------------------------------------------------------\n\nvoid SetAxis(ImAxis axis) {\n    ImPlotContext& gp = *GImPlot;\n    IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, \"SetAxis() needs to be called between BeginPlot() and EndPlot()!\");\n    IM_ASSERT_USER_ERROR(axis >= ImAxis_X1 && axis < ImAxis_COUNT, \"Axis index out of bounds!\");\n    IM_ASSERT_USER_ERROR(gp.CurrentPlot->Axes[axis].Enabled, \"Axis is not enabled! Did you forget to call SetupAxis()?\");\n    SetupLock();\n    if (axis < ImAxis_Y1)\n        gp.CurrentPlot->CurrentX = axis;\n    else\n        gp.CurrentPlot->CurrentY = axis;\n}\n\nvoid SetAxes(ImAxis x_idx, ImAxis y_idx) {\n    ImPlotContext& gp = *GImPlot;\n    IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, \"SetAxes() needs to be called between BeginPlot() and EndPlot()!\");\n    IM_ASSERT_USER_ERROR(x_idx >= ImAxis_X1 && x_idx < ImAxis_Y1, \"X-Axis index out of bounds!\");\n    IM_ASSERT_USER_ERROR(y_idx >= ImAxis_Y1 && y_idx < ImAxis_COUNT, \"Y-Axis index out of bounds!\");\n    IM_ASSERT_USER_ERROR(gp.CurrentPlot->Axes[x_idx].Enabled, \"Axis is not enabled! Did you forget to call SetupAxis()?\");\n    IM_ASSERT_USER_ERROR(gp.CurrentPlot->Axes[y_idx].Enabled, \"Axis is not enabled! Did you forget to call SetupAxis()?\");\n    SetupLock();\n    gp.CurrentPlot->CurrentX = x_idx;\n    gp.CurrentPlot->CurrentY = y_idx;\n}\n\nImPlotPoint PixelsToPlot(float x, float y, ImAxis x_idx, ImAxis y_idx) {\n    ImPlotContext& gp = *GImPlot;\n    IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, \"PixelsToPlot() needs to be called between BeginPlot() and EndPlot()!\");\n    IM_ASSERT_USER_ERROR(x_idx == IMPLOT_AUTO || (x_idx >= ImAxis_X1 && x_idx < ImAxis_Y1),    \"X-Axis index out of bounds!\");\n    IM_ASSERT_USER_ERROR(y_idx == IMPLOT_AUTO || (y_idx >= ImAxis_Y1 && y_idx < ImAxis_COUNT), \"Y-Axis index out of bounds!\");\n    SetupLock();\n    ImPlotPlot& plot   = *gp.CurrentPlot;\n    ImPlotAxis& x_axis = x_idx == IMPLOT_AUTO ? plot.Axes[plot.CurrentX] : plot.Axes[x_idx];\n    ImPlotAxis& y_axis = y_idx == IMPLOT_AUTO ? plot.Axes[plot.CurrentY] : plot.Axes[y_idx];\n    return ImPlotPoint( x_axis.PixelsToPlot(x), y_axis.PixelsToPlot(y) );\n}\n\nImPlotPoint PixelsToPlot(const ImVec2& pix, ImAxis x_idx, ImAxis y_idx) {\n    return PixelsToPlot(pix.x, pix.y, x_idx, y_idx);\n}\n\nImVec2 PlotToPixels(double x, double y, ImAxis x_idx, ImAxis y_idx) {\n    ImPlotContext& gp = *GImPlot;\n    IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, \"PlotToPixels() needs to be called between BeginPlot() and EndPlot()!\");\n    IM_ASSERT_USER_ERROR(x_idx == IMPLOT_AUTO || (x_idx >= ImAxis_X1 && x_idx < ImAxis_Y1),    \"X-Axis index out of bounds!\");\n    IM_ASSERT_USER_ERROR(y_idx == IMPLOT_AUTO || (y_idx >= ImAxis_Y1 && y_idx < ImAxis_COUNT), \"Y-Axis index out of bounds!\");\n    SetupLock();\n    ImPlotPlot& plot = *gp.CurrentPlot;\n    ImPlotAxis& x_axis = x_idx == IMPLOT_AUTO ? plot.Axes[plot.CurrentX] : plot.Axes[x_idx];\n    ImPlotAxis& y_axis = y_idx == IMPLOT_AUTO ? plot.Axes[plot.CurrentY] : plot.Axes[y_idx];\n    return ImVec2( x_axis.PlotToPixels(x), y_axis.PlotToPixels(y) );\n}\n\nImVec2 PlotToPixels(const ImPlotPoint& plt, ImAxis x_idx, ImAxis y_idx) {\n    return PlotToPixels(plt.x, plt.y, x_idx, y_idx);\n}\n\nImVec2 GetPlotPos() {\n    ImPlotContext& gp = *GImPlot;\n    IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, \"GetPlotPos() needs to be called between BeginPlot() and EndPlot()!\");\n    SetupLock();\n    return gp.CurrentPlot->PlotRect.Min;\n}\n\nImVec2 GetPlotSize() {\n    ImPlotContext& gp = *GImPlot;\n    IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, \"GetPlotSize() needs to be called between BeginPlot() and EndPlot()!\");\n    SetupLock();\n    return gp.CurrentPlot->PlotRect.GetSize();\n}\n\nImPlotPoint GetPlotMousePos(ImAxis x_idx, ImAxis y_idx) {\n    IM_ASSERT_USER_ERROR(GImPlot->CurrentPlot != NULL, \"GetPlotMousePos() needs to be called between BeginPlot() and EndPlot()!\");\n    SetupLock();\n    return PixelsToPlot(ImGui::GetMousePos(), x_idx, y_idx);\n}\n\nImPlotRect GetPlotLimits(ImAxis x_idx, ImAxis y_idx) {\n    ImPlotContext& gp = *GImPlot;\n    IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, \"GetPlotLimits() needs to be called between BeginPlot() and EndPlot()!\");\n    IM_ASSERT_USER_ERROR(x_idx == IMPLOT_AUTO || (x_idx >= ImAxis_X1 && x_idx < ImAxis_Y1),    \"X-Axis index out of bounds!\");\n    IM_ASSERT_USER_ERROR(y_idx == IMPLOT_AUTO || (y_idx >= ImAxis_Y1 && y_idx < ImAxis_COUNT), \"Y-Axis index out of bounds!\");\n    SetupLock();\n    ImPlotPlot& plot = *gp.CurrentPlot;\n    ImPlotAxis& x_axis = x_idx == IMPLOT_AUTO ? plot.Axes[plot.CurrentX] : plot.Axes[x_idx];\n    ImPlotAxis& y_axis = y_idx == IMPLOT_AUTO ? plot.Axes[plot.CurrentY] : plot.Axes[y_idx];\n    ImPlotRect limits;\n    limits.X = x_axis.Range;\n    limits.Y = y_axis.Range;\n    return limits;\n}\n\nbool IsPlotHovered() {\n    ImPlotContext& gp = *GImPlot;\n    IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, \"IsPlotHovered() needs to be called between BeginPlot() and EndPlot()!\");\n    SetupLock();\n    return gp.CurrentPlot->Hovered;\n}\n\nbool IsAxisHovered(ImAxis axis) {\n    ImPlotContext& gp = *GImPlot;\n    IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, \"IsPlotXAxisHovered() needs to be called between BeginPlot() and EndPlot()!\");\n    SetupLock();\n    return gp.CurrentPlot->Axes[axis].Hovered;\n}\n\nbool IsSubplotsHovered() {\n    ImPlotContext& gp = *GImPlot;\n    IM_ASSERT_USER_ERROR(gp.CurrentSubplot != NULL, \"IsSubplotsHovered() needs to be called between BeginSubplots() and EndSubplots()!\");\n    return gp.CurrentSubplot->FrameHovered;\n}\n\nbool IsPlotSelected() {\n    ImPlotContext& gp = *GImPlot;\n    IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, \"IsPlotSelected() needs to be called between BeginPlot() and EndPlot()!\");\n    SetupLock();\n    return gp.CurrentPlot->Selected;\n}\n\nImPlotRect GetPlotSelection(ImAxis x_idx, ImAxis y_idx) {\n    ImPlotContext& gp = *GImPlot;\n    IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, \"GetPlotSelection() needs to be called between BeginPlot() and EndPlot()!\");\n    SetupLock();\n    ImPlotPlot& plot = *gp.CurrentPlot;\n    if (!plot.Selected)\n        return ImPlotRect(0,0,0,0);\n    ImPlotPoint p1 = PixelsToPlot(plot.SelectRect.Min + plot.PlotRect.Min, x_idx, y_idx);\n    ImPlotPoint p2 = PixelsToPlot(plot.SelectRect.Max + plot.PlotRect.Min, x_idx, y_idx);\n    ImPlotRect result;\n    result.X.Min = ImMin(p1.x, p2.x);\n    result.X.Max = ImMax(p1.x, p2.x);\n    result.Y.Min = ImMin(p1.y, p2.y);\n    result.Y.Max = ImMax(p1.y, p2.y);\n    return result;\n}\n\nvoid CancelPlotSelection() {\n    ImPlotContext& gp = *GImPlot;\n    IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, \"CancelPlotSelection() needs to be called between BeginPlot() and EndPlot()!\");\n    SetupLock();\n    ImPlotPlot& plot = *gp.CurrentPlot;\n    if (plot.Selected)\n        plot.Selected = plot.Selecting = false;\n}\n\nvoid HideNextItem(bool hidden, ImPlotCond cond) {\n    ImPlotContext& gp = *GImPlot;\n    gp.NextItemData.HasHidden  = true;\n    gp.NextItemData.Hidden     = hidden;\n    gp.NextItemData.HiddenCond = cond;\n}\n\n//-----------------------------------------------------------------------------\n// [SECTION] Plot Tools\n//-----------------------------------------------------------------------------\n\nvoid Annotation(double x, double y, const ImVec4& col, const ImVec2& offset, bool clamp, bool round) {\n    ImPlotContext& gp = *GImPlot;\n    IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, \"Annotation() needs to be called between BeginPlot() and EndPlot()!\");\n    SetupLock();\n    char x_buff[IMPLOT_LABEL_MAX_SIZE];\n    char y_buff[IMPLOT_LABEL_MAX_SIZE];\n    ImPlotAxis& x_axis = gp.CurrentPlot->Axes[gp.CurrentPlot->CurrentX];\n    ImPlotAxis& y_axis = gp.CurrentPlot->Axes[gp.CurrentPlot->CurrentX];\n    LabelAxisValue(x_axis, x, x_buff, sizeof(x_buff), round);\n    LabelAxisValue(y_axis, y, y_buff, sizeof(y_buff), round);\n    Annotation(x,y,col,offset,clamp,\"%s, %s\",x_buff,y_buff);\n}\n\nvoid AnnotationV(double x, double y, const ImVec4& col, const ImVec2& offset, bool clamp, const char* fmt, va_list args) {\n    ImPlotContext& gp = *GImPlot;\n    IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, \"Annotation() needs to be called between BeginPlot() and EndPlot()!\");\n    SetupLock();\n    ImVec2 pos = PlotToPixels(x,y,IMPLOT_AUTO,IMPLOT_AUTO);\n    ImU32  bg  = ImGui::GetColorU32(col);\n    ImU32  fg  = col.w == 0 ? GetStyleColorU32(ImPlotCol_InlayText) : CalcTextColor(col);\n    gp.Annotations.AppendV(pos, offset, bg, fg, clamp, fmt, args);\n}\n\nvoid Annotation(double x, double y, const ImVec4& col, const ImVec2& offset, bool clamp, const char* fmt, ...) {\n    va_list args;\n    va_start(args, fmt);\n    AnnotationV(x,y,col,offset,clamp,fmt,args);\n    va_end(args);\n}\n\nvoid TagV(ImAxis axis, double v, const ImVec4& col, const char* fmt, va_list args) {\n    ImPlotContext& gp = *GImPlot;\n    SetupLock();\n    ImU32 bg = ImGui::GetColorU32(col);\n    ImU32 fg = col.w == 0 ? GetStyleColorU32(ImPlotCol_AxisText) : CalcTextColor(col);\n    gp.Tags.AppendV(axis,v,bg,fg,fmt,args);\n}\n\nvoid Tag(ImAxis axis, double v, const ImVec4& col, const char* fmt, ...) {\n    va_list args;\n    va_start(args, fmt);\n    TagV(axis,v,col,fmt,args);\n    va_end(args);\n}\n\nvoid Tag(ImAxis axis, double v, const ImVec4& color, bool round) {\n    ImPlotContext& gp = *GImPlot;\n    SetupLock();\n    char buff[IMPLOT_LABEL_MAX_SIZE];\n    ImPlotAxis& ax = gp.CurrentPlot->Axes[axis];\n    LabelAxisValue(ax, v, buff, sizeof(buff), round);\n    Tag(axis,v,color,\"%s\",buff);\n}\n\nIMPLOT_API void TagX(double x, const ImVec4& color, bool round) {\n    IM_ASSERT_USER_ERROR(GImPlot->CurrentPlot != NULL, \"TagX() needs to be called between BeginPlot() and EndPlot()!\");\n    Tag(GImPlot->CurrentPlot->CurrentX, x, color, round);\n}\n\nIMPLOT_API void TagX(double x, const ImVec4& color, const char* fmt, ...) {\n    IM_ASSERT_USER_ERROR(GImPlot->CurrentPlot != NULL, \"TagX() needs to be called between BeginPlot() and EndPlot()!\");\n    va_list args;\n    va_start(args, fmt);\n    TagV(GImPlot->CurrentPlot->CurrentX,x,color,fmt,args);\n    va_end(args);\n}\n\nIMPLOT_API void TagXV(double x, const ImVec4& color, const char* fmt, va_list args) {\n    IM_ASSERT_USER_ERROR(GImPlot->CurrentPlot != NULL, \"TagX() needs to be called between BeginPlot() and EndPlot()!\");\n    TagV(GImPlot->CurrentPlot->CurrentX, x, color, fmt, args);\n}\n\nIMPLOT_API void TagY(double y, const ImVec4& color, bool round) {\n    IM_ASSERT_USER_ERROR(GImPlot->CurrentPlot != NULL, \"TagY() needs to be called between BeginPlot() and EndPlot()!\");\n    Tag(GImPlot->CurrentPlot->CurrentY, y, color, round);\n}\n\nIMPLOT_API void TagY(double y, const ImVec4& color, const char* fmt, ...) {\n    IM_ASSERT_USER_ERROR(GImPlot->CurrentPlot != NULL, \"TagY() needs to be called between BeginPlot() and EndPlot()!\");\n    va_list args;\n    va_start(args, fmt);\n    TagV(GImPlot->CurrentPlot->CurrentY,y,color,fmt,args);\n    va_end(args);\n}\n\nIMPLOT_API void TagYV(double y, const ImVec4& color, const char* fmt, va_list args) {\n    IM_ASSERT_USER_ERROR(GImPlot->CurrentPlot != NULL, \"TagY() needs to be called between BeginPlot() and EndPlot()!\");\n    TagV(GImPlot->CurrentPlot->CurrentY, y, color, fmt, args);\n}\n\nstatic const float DRAG_GRAB_HALF_SIZE = 4.0f;\n\nbool DragPoint(int n_id, double* x, double* y, const ImVec4& col, float radius, ImPlotDragToolFlags flags) {\n    ImGui::PushID(\"#IMPLOT_DRAG_POINT\");\n    IM_ASSERT_USER_ERROR(GImPlot->CurrentPlot != NULL, \"DragPoint() needs to be called between BeginPlot() and EndPlot()!\");\n    SetupLock();\n\n    if (!ImHasFlag(flags,ImPlotDragToolFlags_NoFit) && FitThisFrame()) {\n        FitPoint(ImPlotPoint(*x,*y));\n    }\n\n    const bool input = !ImHasFlag(flags, ImPlotDragToolFlags_NoInputs);\n    const bool show_curs = !ImHasFlag(flags, ImPlotDragToolFlags_NoCursors);\n    const bool no_delay = !ImHasFlag(flags, ImPlotDragToolFlags_Delayed);\n    const float grab_half_size = ImMax(DRAG_GRAB_HALF_SIZE, radius);\n    const ImVec4 color = IsColorAuto(col) ? ImGui::GetStyleColorVec4(ImGuiCol_Text) : col;\n    const ImU32 col32 = ImGui::ColorConvertFloat4ToU32(color);\n\n    ImVec2 pos = PlotToPixels(*x,*y,IMPLOT_AUTO,IMPLOT_AUTO);\n    const ImGuiID id = ImGui::GetCurrentWindow()->GetID(n_id);\n    ImRect rect(pos.x-grab_half_size,pos.y-grab_half_size,pos.x+grab_half_size,pos.y+grab_half_size);\n    bool hovered = false, held = false;\n\n    if (input)\n        ImGui::ButtonBehavior(rect,id,&hovered,&held);\n\n    bool dragging = false;\n    if (held && ImGui::IsMouseDragging(0)) {\n        *x = ImPlot::GetPlotMousePos(IMPLOT_AUTO,IMPLOT_AUTO).x;\n        *y = ImPlot::GetPlotMousePos(IMPLOT_AUTO,IMPLOT_AUTO).y;\n        dragging = true;\n    }\n\n    PushPlotClipRect();\n    ImDrawList& DrawList = *GetPlotDrawList();\n    if ((hovered || held) && show_curs)\n        ImGui::SetMouseCursor(ImGuiMouseCursor_Hand);\n    if (dragging && no_delay)\n        pos = PlotToPixels(*x,*y,IMPLOT_AUTO,IMPLOT_AUTO);\n    DrawList.AddCircleFilled(pos, radius, col32);\n    PopPlotClipRect();\n\n    ImGui::PopID();\n    return dragging;\n}\n\nbool DragLineX(int n_id, double* value, const ImVec4& col, float thickness, ImPlotDragToolFlags flags) {\n    ImGui::PushID(\"#IMPLOT_DRAG_LINE_X\");\n    ImPlotContext& gp = *GImPlot;\n    IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, \"DragLineX() needs to be called between BeginPlot() and EndPlot()!\");\n    SetupLock();\n\n    if (!ImHasFlag(flags,ImPlotDragToolFlags_NoFit) && FitThisFrame()) {\n        FitPointX(*value);\n    }\n\n    const bool input = !ImHasFlag(flags, ImPlotDragToolFlags_NoInputs);\n    const bool show_curs = !ImHasFlag(flags, ImPlotDragToolFlags_NoCursors);\n    const bool no_delay = !ImHasFlag(flags, ImPlotDragToolFlags_Delayed);\n    const float grab_half_size = ImMax(DRAG_GRAB_HALF_SIZE, thickness/2);\n    float yt = gp.CurrentPlot->PlotRect.Min.y;\n    float yb = gp.CurrentPlot->PlotRect.Max.y;\n    float x  = IM_ROUND(PlotToPixels(*value,0,IMPLOT_AUTO,IMPLOT_AUTO).x);\n    const ImGuiID id = ImGui::GetCurrentWindow()->GetID(n_id);\n    ImRect rect(x-grab_half_size,yt,x+grab_half_size,yb);\n    bool hovered = false, held = false;\n\n    if (input)\n        ImGui::ButtonBehavior(rect,id,&hovered,&held);\n\n    if ((hovered || held) && show_curs)\n        ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeEW);\n\n    float len = gp.Style.MajorTickLen.x;\n    ImVec4 color = IsColorAuto(col) ? ImGui::GetStyleColorVec4(ImGuiCol_Text) : col;\n    ImU32 col32 = ImGui::ColorConvertFloat4ToU32(color);\n\n    bool dragging = false;\n    if (held && ImGui::IsMouseDragging(0)) {\n        *value = ImPlot::GetPlotMousePos(IMPLOT_AUTO,IMPLOT_AUTO).x;\n        dragging = true;\n    }\n\n    PushPlotClipRect();\n    ImDrawList& DrawList = *GetPlotDrawList();\n    if (dragging && no_delay)\n        x  = IM_ROUND(PlotToPixels(*value,0,IMPLOT_AUTO,IMPLOT_AUTO).x);\n    DrawList.AddLine(ImVec2(x,yt), ImVec2(x,yb),     col32,   thickness);\n    DrawList.AddLine(ImVec2(x,yt), ImVec2(x,yt+len), col32, 3*thickness);\n    DrawList.AddLine(ImVec2(x,yb), ImVec2(x,yb-len), col32, 3*thickness);\n    PopPlotClipRect();\n\n    ImGui::PopID();\n    return dragging;\n}\n\nbool DragLineY(int n_id, double* value, const ImVec4& col, float thickness, ImPlotDragToolFlags flags) {\n    ImGui::PushID(\"#IMPLOT_DRAG_LINE_Y\");\n    ImPlotContext& gp = *GImPlot;\n    IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, \"DragLineY() needs to be called between BeginPlot() and EndPlot()!\");\n    SetupLock();\n\n    if (!ImHasFlag(flags,ImPlotDragToolFlags_NoFit) && FitThisFrame()) {\n        FitPointY(*value);\n    }\n\n    const bool input = !ImHasFlag(flags, ImPlotDragToolFlags_NoInputs);\n    const bool show_curs = !ImHasFlag(flags, ImPlotDragToolFlags_NoCursors);\n    const bool no_delay = !ImHasFlag(flags, ImPlotDragToolFlags_Delayed);\n    const float grab_half_size = ImMax(DRAG_GRAB_HALF_SIZE, thickness/2);\n    float xl = gp.CurrentPlot->PlotRect.Min.x;\n    float xr = gp.CurrentPlot->PlotRect.Max.x;\n    float y  = IM_ROUND(PlotToPixels(0, *value,IMPLOT_AUTO,IMPLOT_AUTO).y);\n\n    const ImGuiID id = ImGui::GetCurrentWindow()->GetID(n_id);\n    ImRect rect(xl,y-grab_half_size,xr,y+grab_half_size);\n    bool hovered = false, held = false;\n\n    if (input)\n        ImGui::ButtonBehavior(rect,id,&hovered,&held);\n\n    if ((hovered || held) && show_curs)\n        ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeNS);\n\n    float len = gp.Style.MajorTickLen.y;\n    ImVec4 color = IsColorAuto(col) ? ImGui::GetStyleColorVec4(ImGuiCol_Text) : col;\n    ImU32 col32 = ImGui::ColorConvertFloat4ToU32(color);\n\n    bool dragging = false;\n    if (held && ImGui::IsMouseDragging(0)) {\n        *value = ImPlot::GetPlotMousePos(IMPLOT_AUTO,IMPLOT_AUTO).y;\n        dragging = true;\n    }\n\n    PushPlotClipRect();\n    ImDrawList& DrawList = *GetPlotDrawList();\n    if (dragging && no_delay)\n        y  = IM_ROUND(PlotToPixels(0, *value,IMPLOT_AUTO,IMPLOT_AUTO).y);\n    DrawList.AddLine(ImVec2(xl,y), ImVec2(xr,y),     col32,   thickness);\n    DrawList.AddLine(ImVec2(xl,y), ImVec2(xl+len,y), col32, 3*thickness);\n    DrawList.AddLine(ImVec2(xr,y), ImVec2(xr-len,y), col32, 3*thickness);\n    PopPlotClipRect();\n\n    ImGui::PopID();\n    return dragging;\n}\n\nbool DragRect(int n_id, double* x_min, double* y_min, double* x_max, double* y_max, const ImVec4& col, ImPlotDragToolFlags flags) {\n    ImGui::PushID(\"#IMPLOT_DRAG_RECT\");\n    IM_ASSERT_USER_ERROR(GImPlot->CurrentPlot != NULL, \"DragRect() needs to be called between BeginPlot() and EndPlot()!\");\n    SetupLock();\n\n    if (!ImHasFlag(flags,ImPlotDragToolFlags_NoFit) && FitThisFrame()) {\n        FitPoint(ImPlotPoint(*x_min,*y_min));\n        FitPoint(ImPlotPoint(*x_max,*y_max));\n    }\n\n    const bool input = !ImHasFlag(flags, ImPlotDragToolFlags_NoInputs);\n    const bool show_curs = !ImHasFlag(flags, ImPlotDragToolFlags_NoCursors);\n    const bool no_delay = !ImHasFlag(flags, ImPlotDragToolFlags_Delayed);\n    bool    h[] = {true,false,true,false};\n    double* x[] = {x_min,x_max,x_max,x_min};\n    double* y[] = {y_min,y_min,y_max,y_max};\n    ImVec2 p[4];\n    for (int i = 0; i < 4; ++i)\n        p[i] = PlotToPixels(*x[i],*y[i],IMPLOT_AUTO,IMPLOT_AUTO);\n    ImVec2 pc = PlotToPixels((*x_min+*x_max)/2,(*y_min+*y_max)/2,IMPLOT_AUTO,IMPLOT_AUTO);\n    ImRect rect(ImMin(p[0],p[2]),ImMax(p[0],p[2]));\n    ImRect rect_grab = rect; rect_grab.Expand(DRAG_GRAB_HALF_SIZE);\n\n    ImGuiMouseCursor cur[4];\n    if (show_curs) {\n        cur[0] = (rect.Min.x == p[0].x && rect.Min.y == p[0].y) || (rect.Max.x == p[0].x && rect.Max.y == p[0].y) ? ImGuiMouseCursor_ResizeNWSE : ImGuiMouseCursor_ResizeNESW;\n        cur[1] = cur[0] == ImGuiMouseCursor_ResizeNWSE ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;\n        cur[2] = cur[1] == ImGuiMouseCursor_ResizeNWSE ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;\n        cur[3] = cur[2] == ImGuiMouseCursor_ResizeNWSE ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;\n    }\n\n    ImVec4 color = IsColorAuto(col) ? ImGui::GetStyleColorVec4(ImGuiCol_Text) : col;\n    ImU32 col32 = ImGui::ColorConvertFloat4ToU32(color);\n    color.w *= 0.25f;\n    ImU32 col32_a = ImGui::ColorConvertFloat4ToU32(color);\n    const ImGuiID id = ImGui::GetCurrentWindow()->GetID(n_id);\n\n    bool dragging = false;\n    bool hovered = false, held = false;\n    ImRect b_rect(pc.x-DRAG_GRAB_HALF_SIZE,pc.y-DRAG_GRAB_HALF_SIZE,pc.x+DRAG_GRAB_HALF_SIZE,pc.y+DRAG_GRAB_HALF_SIZE);\n\n    if (input)\n        ImGui::ButtonBehavior(b_rect,id,&hovered,&held);\n\n    if ((hovered || held) && show_curs)\n        ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeAll);\n    if (held && ImGui::IsMouseDragging(0)) {\n        for (int i = 0; i < 4; ++i) {\n            ImPlotPoint pp = PixelsToPlot(p[i] + ImGui::GetIO().MouseDelta,IMPLOT_AUTO,IMPLOT_AUTO);\n            *y[i] = pp.y;\n            *x[i] = pp.x;\n        }\n        dragging = true;\n    }\n\n    for (int i = 0; i < 4; ++i) {\n        // points\n        b_rect = ImRect(p[i].x-DRAG_GRAB_HALF_SIZE,p[i].y-DRAG_GRAB_HALF_SIZE,p[i].x+DRAG_GRAB_HALF_SIZE,p[i].y+DRAG_GRAB_HALF_SIZE);\n        ImGuiID p_id = id + i + 1;\n        ImGui::KeepAliveID(p_id);\n        if (input)\n            ImGui::ButtonBehavior(b_rect,p_id,&hovered,&held);\n        if ((hovered || held) && show_curs)\n            ImGui::SetMouseCursor(cur[i]);\n\n        if (held && ImGui::IsMouseDragging(0)) {\n            *x[i] = ImPlot::GetPlotMousePos(IMPLOT_AUTO,IMPLOT_AUTO).x;\n            *y[i] = ImPlot::GetPlotMousePos(IMPLOT_AUTO,IMPLOT_AUTO).y;\n            dragging = true;\n        }\n\n        // edges\n        ImVec2 e_min = ImMin(p[i],p[(i+1)%4]);\n        ImVec2 e_max = ImMax(p[i],p[(i+1)%4]);\n        b_rect = h[i] ? ImRect(e_min.x + DRAG_GRAB_HALF_SIZE, e_min.y - DRAG_GRAB_HALF_SIZE, e_max.x - DRAG_GRAB_HALF_SIZE, e_max.y + DRAG_GRAB_HALF_SIZE)\n                    : ImRect(e_min.x - DRAG_GRAB_HALF_SIZE, e_min.y + DRAG_GRAB_HALF_SIZE, e_max.x + DRAG_GRAB_HALF_SIZE, e_max.y - DRAG_GRAB_HALF_SIZE);\n        ImGuiID e_id = id + i + 5;\n        ImGui::KeepAliveID(e_id);\n        if (input)\n            ImGui::ButtonBehavior(b_rect,e_id,&hovered,&held);\n        if ((hovered || held) && show_curs)\n            h[i] ? ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeNS) : ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeEW);\n        if (held && ImGui::IsMouseDragging(0)) {\n            if (h[i])\n                *y[i] = ImPlot::GetPlotMousePos(IMPLOT_AUTO,IMPLOT_AUTO).y;\n            else\n                *x[i] = ImPlot::GetPlotMousePos(IMPLOT_AUTO,IMPLOT_AUTO).x;\n            dragging = true;\n        }\n        if (hovered && ImGui::IsMouseDoubleClicked(0))\n        {\n            ImPlotRect b = GetPlotLimits(IMPLOT_AUTO,IMPLOT_AUTO);\n            if (h[i])\n                *y[i] = ((y[i] == y_min && *y_min < *y_max) || (y[i] == y_max && *y_max < *y_min)) ? b.Y.Min : b.Y.Max;\n            else\n                *x[i] = ((x[i] == x_min && *x_min < *x_max) || (x[i] == x_max && *x_max < *x_min)) ? b.X.Min : b.X.Max;\n            dragging = true;\n        }\n    }\n\n\n    PushPlotClipRect();\n    ImDrawList& DrawList = *GetPlotDrawList();\n    if (dragging && no_delay) {\n        for (int i = 0; i < 4; ++i)\n            p[i] = PlotToPixels(*x[i],*y[i],IMPLOT_AUTO,IMPLOT_AUTO);\n        pc = PlotToPixels((*x_min+*x_max)/2,(*y_min+*y_max)/2,IMPLOT_AUTO,IMPLOT_AUTO);\n        rect = ImRect(ImMin(p[0],p[2]),ImMax(p[0],p[2]));\n    }\n    DrawList.AddRectFilled(rect.Min, rect.Max, col32_a);\n    DrawList.AddRect(rect.Min, rect.Max, col32);\n    if (input && (dragging || rect_grab.Contains(ImGui::GetMousePos()))) {\n        DrawList.AddCircleFilled(pc,DRAG_GRAB_HALF_SIZE,col32);\n        for (int i = 0; i < 4; ++i)\n            DrawList.AddCircleFilled(p[i],DRAG_GRAB_HALF_SIZE,col32);\n    }\n    PopPlotClipRect();\n    ImGui::PopID();\n    return dragging;\n}\n\nbool DragRect(int id, ImPlotRect* bounds, const ImVec4& col, ImPlotDragToolFlags flags) {\n    return DragRect(id, &bounds->X.Min, &bounds->Y.Min,&bounds->X.Max, &bounds->Y.Max, col, flags);\n}\n\n//-----------------------------------------------------------------------------\n// [SECTION] Legend Utils and Tools\n//-----------------------------------------------------------------------------\n\nbool IsLegendEntryHovered(const char* label_id) {\n    ImPlotContext& gp = *GImPlot;\n    IM_ASSERT_USER_ERROR(gp.CurrentItems != NULL, \"IsPlotItemHighlight() needs to be called within an itemized context!\");\n    SetupLock();\n    ImGuiID id = ImGui::GetIDWithSeed(label_id, NULL, gp.CurrentItems->ID);\n    ImPlotItem* item = gp.CurrentItems->GetItem(id);\n    return item && item->LegendHovered;\n}\n\nbool BeginLegendPopup(const char* label_id, ImGuiMouseButton mouse_button) {\n    ImPlotContext& gp = *GImPlot;\n    IM_ASSERT_USER_ERROR(gp.CurrentItems != NULL, \"BeginLegendPopup() needs to be called within an itemized context!\");\n    SetupLock();\n    ImGuiWindow* window = GImGui->CurrentWindow;\n    if (window->SkipItems)\n        return false;\n    ImGuiID id = ImGui::GetIDWithSeed(label_id, NULL, gp.CurrentItems->ID);\n    if (ImGui::IsMouseReleased(mouse_button)) {\n        ImPlotItem* item = gp.CurrentItems->GetItem(id);\n        if (item && item->LegendHovered)\n            ImGui::OpenPopupEx(id);\n    }\n    return ImGui::BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);\n}\n\nvoid EndLegendPopup() {\n    SetupLock();\n    ImGui::EndPopup();\n}\n\nvoid ShowAltLegend(const char* title_id, bool vertical, const ImVec2 size, bool interactable) {\n    ImPlotContext& gp    = *GImPlot;\n    ImGuiContext &G      = *GImGui;\n    ImGuiWindow * Window = G.CurrentWindow;\n    if (Window->SkipItems)\n        return;\n    ImDrawList &DrawList = *Window->DrawList;\n    ImPlotPlot* plot = GetPlot(title_id);\n    ImVec2 legend_size;\n    ImVec2 default_size = gp.Style.LegendPadding * 2;\n    if (plot != NULL) {\n        legend_size  = CalcLegendSize(plot->Items, gp.Style.LegendInnerPadding, gp.Style.LegendSpacing, vertical);\n        default_size = legend_size + gp.Style.LegendPadding * 2;\n    }\n    ImVec2 frame_size = ImGui::CalcItemSize(size, default_size.x, default_size.y);\n    ImRect bb_frame = ImRect(Window->DC.CursorPos, Window->DC.CursorPos + frame_size);\n    ImGui::ItemSize(bb_frame);\n    if (!ImGui::ItemAdd(bb_frame, 0, &bb_frame))\n        return;\n    ImGui::RenderFrame(bb_frame.Min, bb_frame.Max, GetStyleColorU32(ImPlotCol_FrameBg), true, G.Style.FrameRounding);\n    DrawList.PushClipRect(bb_frame.Min, bb_frame.Max, true);\n    if (plot != NULL) {\n        const ImVec2 legend_pos  = GetLocationPos(bb_frame, legend_size, 0, gp.Style.LegendPadding);\n        const ImRect legend_bb(legend_pos, legend_pos + legend_size);\n        interactable = interactable && bb_frame.Contains(ImGui::GetIO().MousePos);\n        // render legend box\n        ImU32  col_bg      = GetStyleColorU32(ImPlotCol_LegendBg);\n        ImU32  col_bd      = GetStyleColorU32(ImPlotCol_LegendBorder);\n        DrawList.AddRectFilled(legend_bb.Min, legend_bb.Max, col_bg);\n        DrawList.AddRect(legend_bb.Min, legend_bb.Max, col_bd);\n        // render entries\n        ShowLegendEntries(plot->Items, legend_bb, interactable, gp.Style.LegendInnerPadding, gp.Style.LegendSpacing, vertical, DrawList);\n    }\n    DrawList.PopClipRect();\n}\n\n//-----------------------------------------------------------------------------\n// [SECTION] Drag and Drop Utils\n//-----------------------------------------------------------------------------\n\nbool BeginDragDropTargetPlot() {\n    SetupLock();\n    ImRect rect = GImPlot->CurrentPlot->PlotRect;\n    return ImGui::BeginDragDropTargetCustom(rect, GImPlot->CurrentPlot->ID);\n}\n\nbool BeginDragDropTargetAxis(ImAxis axis) {\n    SetupLock();\n    ImPlotPlot& plot = *GImPlot->CurrentPlot;\n    ImPlotAxis& ax = plot.Axes[axis];\n    ImRect rect = ax.HoverRect;\n    rect.Expand(-3.5f);\n    return ImGui::BeginDragDropTargetCustom(rect, ax.ID);\n}\n\nbool BeginDragDropTargetLegend() {\n    SetupLock();\n    ImPlotItemGroup& items = *GImPlot->CurrentItems;\n    ImRect rect = items.Legend.Rect;\n    return ImGui::BeginDragDropTargetCustom(rect, items.ID);\n}\n\nvoid EndDragDropTarget() {\n    SetupLock();\n\tImGui::EndDragDropTarget();\n}\n\nbool BeginDragDropSourcePlot(ImGuiDragDropFlags flags) {\n    SetupLock();\n    ImPlotPlot* plot = GImPlot->CurrentPlot;\n    if (GImGui->IO.KeyMods == GImPlot->InputMap.OverrideMod || GImGui->DragDropPayload.SourceId == plot->ID)\n        return ImGui::ItemAdd(plot->PlotRect, plot->ID) && ImGui::BeginDragDropSource(flags);\n    return false;\n}\n\nbool BeginDragDropSourceAxis(ImAxis idx, ImGuiDragDropFlags flags) {\n    SetupLock();\n    ImPlotAxis& axis = GImPlot->CurrentPlot->Axes[idx];\n    if (GImGui->IO.KeyMods == GImPlot->InputMap.OverrideMod || GImGui->DragDropPayload.SourceId == axis.ID)\n        return ImGui::ItemAdd(axis.HoverRect, axis.ID) && ImGui::BeginDragDropSource(flags);\n    return false;\n}\n\nbool BeginDragDropSourceItem(const char* label_id, ImGuiDragDropFlags flags) {\n    SetupLock();\n    ImPlotContext& gp = *GImPlot;\n    IM_ASSERT_USER_ERROR(gp.CurrentItems != NULL, \"BeginDragDropSourceItem() needs to be called within an itemized context!\");\n    ImGuiID item_id = ImGui::GetIDWithSeed(label_id, NULL, gp.CurrentItems->ID);\n    ImPlotItem* item = gp.CurrentItems->GetItem(item_id);\n    if (item != NULL) {\n        return ImGui::ItemAdd(item->LegendHoverRect, item->ID) && ImGui::BeginDragDropSource(flags);\n    }\n    return false;\n}\n\nvoid EndDragDropSource() {\n    SetupLock();\n    ImGui::EndDragDropSource();\n}\n\n//-----------------------------------------------------------------------------\n// [SECTION] Aligned Plots\n//-----------------------------------------------------------------------------\n\nbool BeginAlignedPlots(const char* group_id, bool vertical) {\n    IM_ASSERT_USER_ERROR(GImPlot != NULL, \"No current context. Did you call ImPlot::CreateContext() or ImPlot::SetCurrentContext()?\");\n    IM_ASSERT_USER_ERROR(GImPlot->CurrentAlignmentH == NULL && GImPlot->CurrentAlignmentV == NULL, \"Mismatched BeginAlignedPlots()/EndAlignedPlots()!\");\n    ImPlotContext& gp = *GImPlot;\n    ImGuiContext &G = *GImGui;\n    ImGuiWindow * Window = G.CurrentWindow;\n    if (Window->SkipItems)\n        return false;\n    const ImGuiID ID = Window->GetID(group_id);\n    ImPlotAlignmentData* alignment = gp.AlignmentData.GetOrAddByKey(ID);\n    if (vertical)\n        gp.CurrentAlignmentV = alignment;\n    else\n        gp.CurrentAlignmentH = alignment;\n    if (alignment->Vertical != vertical)\n        alignment->Reset();\n    alignment->Vertical = vertical;\n    alignment->Begin();\n    return true;\n}\n\nvoid EndAlignedPlots() {\n    IM_ASSERT_USER_ERROR(GImPlot != NULL, \"No current context. Did you call ImPlot::CreateContext() or ImPlot::SetCurrentContext()?\");\n    IM_ASSERT_USER_ERROR(GImPlot->CurrentAlignmentH != NULL || GImPlot->CurrentAlignmentV != NULL, \"Mismatched BeginAlignedPlots()/EndAlignedPlots()!\");\n    ImPlotContext& gp = *GImPlot;\n    ImPlotAlignmentData* alignment = gp.CurrentAlignmentH != NULL ? gp.CurrentAlignmentH : (gp.CurrentAlignmentV != NULL ? gp.CurrentAlignmentV : NULL);\n    if (alignment)\n        alignment->End();\n    ResetCtxForNextAlignedPlots(GImPlot);\n}\n\n//-----------------------------------------------------------------------------\n// [SECTION] Plot and Item Styling\n//-----------------------------------------------------------------------------\n\nImPlotStyle& GetStyle() {\n    IM_ASSERT_USER_ERROR(GImPlot != NULL, \"No current context. Did you call ImPlot::CreateContext() or ImPlot::SetCurrentContext()?\");\n    ImPlotContext& gp = *GImPlot;\n    return gp.Style;\n}\n\nvoid PushStyleColor(ImPlotCol idx, ImU32 col) {\n    ImPlotContext& gp = *GImPlot;\n    ImGuiColorMod backup;\n    backup.Col = idx;\n    backup.BackupValue = gp.Style.Colors[idx];\n    gp.ColorModifiers.push_back(backup);\n    gp.Style.Colors[idx] = ImGui::ColorConvertU32ToFloat4(col);\n}\n\nvoid PushStyleColor(ImPlotCol idx, const ImVec4& col) {\n    ImPlotContext& gp = *GImPlot;\n    ImGuiColorMod backup;\n    backup.Col = idx;\n    backup.BackupValue = gp.Style.Colors[idx];\n    gp.ColorModifiers.push_back(backup);\n    gp.Style.Colors[idx] = col;\n}\n\nvoid PopStyleColor(int count) {\n    ImPlotContext& gp = *GImPlot;\n    IM_ASSERT_USER_ERROR(count <= gp.ColorModifiers.Size, \"You can't pop more modifiers than have been pushed!\");\n    while (count > 0)\n    {\n        ImGuiColorMod& backup = gp.ColorModifiers.back();\n        gp.Style.Colors[backup.Col] = backup.BackupValue;\n        gp.ColorModifiers.pop_back();\n        count--;\n    }\n}\n\nvoid PushStyleVar(ImPlotStyleVar idx, float val) {\n    ImPlotContext& gp = *GImPlot;\n    const ImPlotStyleVarInfo* var_info = GetPlotStyleVarInfo(idx);\n    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1) {\n        float* pvar = (float*)var_info->GetVarPtr(&gp.Style);\n        gp.StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar));\n        *pvar = val;\n        return;\n    }\n    IM_ASSERT(0 && \"Called PushStyleVar() float variant but variable is not a float!\");\n}\n\nvoid PushStyleVar(ImPlotStyleVar idx, int val) {\n    ImPlotContext& gp = *GImPlot;\n    const ImPlotStyleVarInfo* var_info = GetPlotStyleVarInfo(idx);\n    if (var_info->Type == ImGuiDataType_S32 && var_info->Count == 1) {\n        int* pvar = (int*)var_info->GetVarPtr(&gp.Style);\n        gp.StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar));\n        *pvar = val;\n        return;\n    }\n    else if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1) {\n        float* pvar = (float*)var_info->GetVarPtr(&gp.Style);\n        gp.StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar));\n        *pvar = (float)val;\n        return;\n    }\n    IM_ASSERT(0 && \"Called PushStyleVar() int variant but variable is not a int!\");\n}\n\nvoid PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)\n{\n    ImPlotContext& gp = *GImPlot;\n    const ImPlotStyleVarInfo* var_info = GetPlotStyleVarInfo(idx);\n    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2)\n    {\n        ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&gp.Style);\n        gp.StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar));\n        *pvar = val;\n        return;\n    }\n    IM_ASSERT(0 && \"Called PushStyleVar() ImVec2 variant but variable is not a ImVec2!\");\n}\n\nvoid PopStyleVar(int count) {\n    ImPlotContext& gp = *GImPlot;\n    IM_ASSERT_USER_ERROR(count <= gp.StyleModifiers.Size, \"You can't pop more modifiers than have been pushed!\");\n    while (count > 0) {\n        ImGuiStyleMod& backup = gp.StyleModifiers.back();\n        const ImPlotStyleVarInfo* info = GetPlotStyleVarInfo(backup.VarIdx);\n        void* data = info->GetVarPtr(&gp.Style);\n        if (info->Type == ImGuiDataType_Float && info->Count == 1) {\n            ((float*)data)[0] = backup.BackupFloat[0];\n        }\n        else if (info->Type == ImGuiDataType_Float && info->Count == 2) {\n             ((float*)data)[0] = backup.BackupFloat[0];\n             ((float*)data)[1] = backup.BackupFloat[1];\n        }\n        else if (info->Type == ImGuiDataType_S32 && info->Count == 1) {\n            ((int*)data)[0] = backup.BackupInt[0];\n        }\n        gp.StyleModifiers.pop_back();\n        count--;\n    }\n}\n\n//------------------------------------------------------------------------------\n// [Section] Colormaps\n//------------------------------------------------------------------------------\n\nImPlotColormap AddColormap(const char* name, const ImVec4* colormap, int size, bool qual) {\n    ImPlotContext& gp = *GImPlot;\n    IM_ASSERT_USER_ERROR(size > 1, \"The colormap size must be greater than 1!\");\n    IM_ASSERT_USER_ERROR(gp.ColormapData.GetIndex(name) == -1, \"The colormap name has already been used!\");\n    ImVector<ImU32> buffer;\n    buffer.resize(size);\n    for (int i = 0; i < size; ++i)\n        buffer[i] = ImGui::ColorConvertFloat4ToU32(colormap[i]);\n    return gp.ColormapData.Append(name, buffer.Data, size, qual);\n}\n\nImPlotColormap AddColormap(const char* name, const ImU32*  colormap, int size, bool qual) {\n    ImPlotContext& gp = *GImPlot;\n    IM_ASSERT_USER_ERROR(size > 1, \"The colormap size must be greater than 1!\");\n    IM_ASSERT_USER_ERROR(gp.ColormapData.GetIndex(name) == -1, \"The colormap name has already be used!\");\n    return gp.ColormapData.Append(name, colormap, size, qual);\n}\n\nint GetColormapCount() {\n    ImPlotContext& gp = *GImPlot;\n    return gp.ColormapData.Count;\n}\n\nconst char* GetColormapName(ImPlotColormap colormap) {\n    ImPlotContext& gp = *GImPlot;\n    return gp.ColormapData.GetName(colormap);\n}\n\nImPlotColormap GetColormapIndex(const char* name) {\n    ImPlotContext& gp = *GImPlot;\n    return gp.ColormapData.GetIndex(name);\n}\n\nvoid PushColormap(ImPlotColormap colormap) {\n    ImPlotContext& gp = *GImPlot;\n    IM_ASSERT_USER_ERROR(colormap >= 0 && colormap < gp.ColormapData.Count, \"The colormap index is invalid!\");\n    gp.ColormapModifiers.push_back(gp.Style.Colormap);\n    gp.Style.Colormap = colormap;\n}\n\nvoid PushColormap(const char* name) {\n    ImPlotContext& gp = *GImPlot;\n    ImPlotColormap idx = gp.ColormapData.GetIndex(name);\n    IM_ASSERT_USER_ERROR(idx != -1, \"The colormap name is invalid!\");\n    PushColormap(idx);\n}\n\nvoid PopColormap(int count) {\n    ImPlotContext& gp = *GImPlot;\n    IM_ASSERT_USER_ERROR(count <= gp.ColormapModifiers.Size, \"You can't pop more modifiers than have been pushed!\");\n    while (count > 0) {\n        const ImPlotColormap& backup = gp.ColormapModifiers.back();\n        gp.Style.Colormap     = backup;\n        gp.ColormapModifiers.pop_back();\n        count--;\n    }\n}\n\nImU32 NextColormapColorU32() {\n    ImPlotContext& gp = *GImPlot;\n    IM_ASSERT_USER_ERROR(gp.CurrentItems != NULL, \"NextColormapColor() needs to be called between BeginPlot() and EndPlot()!\");\n    int idx = gp.CurrentItems->ColormapIdx % gp.ColormapData.GetKeyCount(gp.Style.Colormap);\n    ImU32 col  = gp.ColormapData.GetKeyColor(gp.Style.Colormap, idx);\n    gp.CurrentItems->ColormapIdx++;\n    return col;\n}\n\nImVec4 NextColormapColor() {\n    return ImGui::ColorConvertU32ToFloat4(NextColormapColorU32());\n}\n\nint GetColormapSize(ImPlotColormap cmap) {\n    ImPlotContext& gp = *GImPlot;\n    cmap = cmap == IMPLOT_AUTO ? gp.Style.Colormap : cmap;\n    IM_ASSERT_USER_ERROR(cmap >= 0 && cmap < gp.ColormapData.Count, \"Invalid colormap index!\");\n    return gp.ColormapData.GetKeyCount(cmap);\n}\n\nImU32 GetColormapColorU32(int idx, ImPlotColormap cmap) {\n    ImPlotContext& gp = *GImPlot;\n    cmap = cmap == IMPLOT_AUTO ? gp.Style.Colormap : cmap;\n    IM_ASSERT_USER_ERROR(cmap >= 0 && cmap < gp.ColormapData.Count, \"Invalid colormap index!\");\n    idx = idx % gp.ColormapData.GetKeyCount(cmap);\n    return gp.ColormapData.GetKeyColor(cmap, idx);\n}\n\nImVec4 GetColormapColor(int idx, ImPlotColormap cmap) {\n    return ImGui::ColorConvertU32ToFloat4(GetColormapColorU32(idx,cmap));\n}\n\nImU32  SampleColormapU32(float t, ImPlotColormap cmap) {\n    ImPlotContext& gp = *GImPlot;\n    cmap = cmap == IMPLOT_AUTO ? gp.Style.Colormap : cmap;\n    IM_ASSERT_USER_ERROR(cmap >= 0 && cmap < gp.ColormapData.Count, \"Invalid colormap index!\");\n    return gp.ColormapData.LerpTable(cmap, t);\n}\n\nImVec4 SampleColormap(float t, ImPlotColormap cmap) {\n    return ImGui::ColorConvertU32ToFloat4(SampleColormapU32(t,cmap));\n}\n\nvoid RenderColorBar(const ImU32* colors, int size, ImDrawList& DrawList, const ImRect& bounds, bool vert, bool reversed, bool continuous) {\n    const int n = continuous ? size - 1 : size;\n    ImU32 col1, col2;\n    if (vert) {\n        const float step = bounds.GetHeight() / n;\n        ImRect rect(bounds.Min.x, bounds.Min.y, bounds.Max.x, bounds.Min.y + step);\n        for (int i = 0; i < n; ++i) {\n            if (reversed) {\n                col1 = colors[size-i-1];\n                col2 = continuous ? colors[size-i-2] : col1;\n            }\n            else {\n                col1 = colors[i];\n                col2 = continuous ? colors[i+1] : col1;\n            }\n            DrawList.AddRectFilledMultiColor(rect.Min, rect.Max, col1, col1, col2, col2);\n            rect.TranslateY(step);\n        }\n    }\n    else {\n        const float step = bounds.GetWidth() / n;\n        ImRect rect(bounds.Min.x, bounds.Min.y, bounds.Min.x + step, bounds.Max.y);\n        for (int i = 0; i < n; ++i) {\n            if (reversed) {\n                col1 = colors[size-i-1];\n                col2 = continuous ? colors[size-i-2] : col1;\n            }\n            else {\n                col1 = colors[i];\n                col2 = continuous ? colors[i+1] : col1;\n            }\n            DrawList.AddRectFilledMultiColor(rect.Min, rect.Max, col1, col2, col2, col1);\n            rect.TranslateX(step);\n        }\n    }\n}\n\nvoid ColormapScale(const char* label, double scale_min, double scale_max, const ImVec2& size, ImPlotColormap cmap, const char* fmt) {\n    ImGuiContext &G      = *GImGui;\n    ImGuiWindow * Window = G.CurrentWindow;\n    if (Window->SkipItems)\n        return;\n\n    const ImGuiID ID = Window->GetID(label);\n    ImVec2 label_size(0,0);\n    label_size = ImGui::CalcTextSize(label,NULL,true);\n\n    ImPlotContext& gp = *GImPlot;\n    cmap = cmap == IMPLOT_AUTO ? gp.Style.Colormap : cmap;\n    IM_ASSERT_USER_ERROR(cmap >= 0 && cmap < gp.ColormapData.Count, \"Invalid colormap index!\");\n\n    ImVec2 frame_size  = ImGui::CalcItemSize(size, 0, gp.Style.PlotDefaultSize.y);\n    if (frame_size.y < gp.Style.PlotMinSize.y && size.y < 0.0f)\n        frame_size.y = gp.Style.PlotMinSize.y;\n\n    ImPlotRange range(scale_min,scale_max);\n    gp.CTicks.Reset();\n    AddTicksDefault(range, frame_size.y, true, gp.CTicks, DefaultFormatter, (void*)fmt);\n\n    const float txt_off   = gp.Style.LabelPadding.x;\n    const float pad_right = txt_off + gp.CTicks.MaxSize.x + (label_size.x > 0 ? txt_off + label_size.y : 0);\n    float bar_w           = 20;\n\n    if (frame_size.x == 0)\n        frame_size.x = bar_w + pad_right + 2 * gp.Style.PlotPadding.x;\n    else {\n        bar_w = frame_size.x - (pad_right + 2 * gp.Style.PlotPadding.x);\n        if (bar_w < gp.Style.MajorTickLen.y)\n            bar_w = gp.Style.MajorTickLen.y;\n    }\n\n    ImDrawList &DrawList = *Window->DrawList;\n    ImRect bb_frame = ImRect(Window->DC.CursorPos, Window->DC.CursorPos + frame_size);\n    ImGui::ItemSize(bb_frame);\n    if (!ImGui::ItemAdd(bb_frame, ID, &bb_frame))\n        return;\n\n    ImGui::RenderFrame(bb_frame.Min, bb_frame.Max, GetStyleColorU32(ImPlotCol_FrameBg), true, G.Style.FrameRounding);\n    ImRect bb_grad(bb_frame.Min + gp.Style.PlotPadding, bb_frame.Min + ImVec2(bar_w + gp.Style.PlotPadding.x, frame_size.y - gp.Style.PlotPadding.y));\n\n    ImGui::PushClipRect(bb_frame.Min, bb_frame.Max, true);\n    RenderColorBar(gp.ColormapData.GetKeys(cmap), gp.ColormapData.GetKeyCount(cmap), DrawList, bb_grad, true, true, !gp.ColormapData.IsQual(cmap));\n    const ImU32 col_tick = GetStyleColorU32(ImPlotCol_AxisText);\n    const ImU32 col_text = ImGui::GetColorU32(ImGuiCol_Text);\n    for (int i = 0; i < gp.CTicks.Size; ++i) {\n        const float ypos = ImRemap((float)gp.CTicks.Ticks[i].PlotPos, (float)range.Max, (float)range.Min, bb_grad.Min.y, bb_grad.Max.y);\n        const float tick_width = gp.CTicks.Ticks[i].Major ? gp.Style.MajorTickLen.y : gp.Style.MinorTickLen.y;\n        const float tick_thick = gp.CTicks.Ticks[i].Major ? gp.Style.MajorTickSize.y : gp.Style.MinorTickSize.y;\n        if (ypos < bb_grad.Max.y - 2 && ypos > bb_grad.Min.y + 2)\n            DrawList.AddLine(ImVec2(bb_grad.Max.x-1, ypos), ImVec2(bb_grad.Max.x - tick_width, ypos), col_tick, tick_thick);\n        DrawList.AddText(ImVec2(bb_grad.Max.x-1, ypos) + ImVec2(txt_off, -gp.CTicks.Ticks[i].LabelSize.y * 0.5f), col_text, gp.CTicks.GetText(i));\n    }\n    if (label_size.x > 0) {\n        ImVec2 label_pos(bb_grad.Max.x - 1 + 2*txt_off + gp.CTicks.MaxSize.x, bb_grad.GetCenter().y + label_size.x*0.5f );\n        const char* label_end = ImGui::FindRenderedTextEnd(label);\n        AddTextVertical(&DrawList,label_pos,col_text,label,label_end);\n    }\n    DrawList.AddRect(bb_grad.Min, bb_grad.Max, GetStyleColorU32(ImPlotCol_PlotBorder));\n    ImGui::PopClipRect();\n}\n\nbool ColormapSlider(const char* label, float* t, ImVec4* out, const char* format, ImPlotColormap cmap) {\n    *t = ImClamp(*t,0.0f,1.0f);\n    ImGuiContext &G      = *GImGui;\n    ImGuiWindow * Window = G.CurrentWindow;\n    if (Window->SkipItems)\n        return false;\n    ImPlotContext& gp = *GImPlot;\n    cmap = cmap == IMPLOT_AUTO ? gp.Style.Colormap : cmap;\n    IM_ASSERT_USER_ERROR(cmap >= 0 && cmap < gp.ColormapData.Count, \"Invalid colormap index!\");\n    const ImU32* keys  = GImPlot->ColormapData.GetKeys(cmap);\n    const int    count = GImPlot->ColormapData.GetKeyCount(cmap);\n    const bool   qual  = GImPlot->ColormapData.IsQual(cmap);\n    const ImVec2 pos  = ImGui::GetCurrentWindow()->DC.CursorPos;\n    const float w     = ImGui::CalcItemWidth();\n    const float h     = ImGui::GetFrameHeight();\n    const ImRect rect = ImRect(pos.x,pos.y,pos.x+w,pos.y+h);\n    RenderColorBar(keys,count,*ImGui::GetWindowDrawList(),rect,false,false,!qual);\n    const ImU32 grab = CalcTextColor(GImPlot->ColormapData.LerpTable(cmap,*t));\n    // const ImU32 text = CalcTextColor(GImPlot->ColormapData.LerpTable(cmap,0.5f));\n    ImGui::PushStyleColor(ImGuiCol_FrameBg,IM_COL32_BLACK_TRANS);\n    ImGui::PushStyleColor(ImGuiCol_FrameBgActive,IM_COL32_BLACK_TRANS);\n    ImGui::PushStyleColor(ImGuiCol_FrameBgHovered,ImVec4(1,1,1,0.1f));\n    ImGui::PushStyleColor(ImGuiCol_SliderGrab,grab);\n    ImGui::PushStyleColor(ImGuiCol_SliderGrabActive, grab);\n    ImGui::PushStyleVar(ImGuiStyleVar_GrabMinSize,2);\n    ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding,0);\n    const bool changed = ImGui::SliderFloat(label,t,0,1,format);\n    ImGui::PopStyleColor(5);\n    ImGui::PopStyleVar(2);\n    if (out != NULL)\n        *out = ImGui::ColorConvertU32ToFloat4(GImPlot->ColormapData.LerpTable(cmap,*t));\n    return changed;\n}\n\nbool ColormapButton(const char* label, const ImVec2& size_arg, ImPlotColormap cmap) {\n    ImGuiContext &G      = *GImGui;\n    const ImGuiStyle& style = G.Style;\n    ImGuiWindow * Window = G.CurrentWindow;\n    if (Window->SkipItems)\n        return false;\n    ImPlotContext& gp = *GImPlot;\n    cmap = cmap == IMPLOT_AUTO ? gp.Style.Colormap : cmap;\n    IM_ASSERT_USER_ERROR(cmap >= 0 && cmap < gp.ColormapData.Count, \"Invalid colormap index!\");\n    const ImU32* keys  = GImPlot->ColormapData.GetKeys(cmap);\n    const int    count = GImPlot->ColormapData.GetKeyCount(cmap);\n    const bool   qual  = GImPlot->ColormapData.IsQual(cmap);\n    const ImVec2 pos  = ImGui::GetCurrentWindow()->DC.CursorPos;\n    const ImVec2 label_size = ImGui::CalcTextSize(label, NULL, true);\n    ImVec2 size = ImGui::CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0f, label_size.y + style.FramePadding.y * 2.0f);\n    const ImRect rect = ImRect(pos.x,pos.y,pos.x+size.x,pos.y+size.y);\n    RenderColorBar(keys,count,*ImGui::GetWindowDrawList(),rect,false,false,!qual);\n    const ImU32 text = CalcTextColor(GImPlot->ColormapData.LerpTable(cmap,G.Style.ButtonTextAlign.x));\n    ImGui::PushStyleColor(ImGuiCol_Button,IM_COL32_BLACK_TRANS);\n    ImGui::PushStyleColor(ImGuiCol_ButtonHovered,ImVec4(1,1,1,0.1f));\n    ImGui::PushStyleColor(ImGuiCol_ButtonActive,ImVec4(1,1,1,0.2f));\n    ImGui::PushStyleColor(ImGuiCol_Text,text);\n    ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding,0);\n    const bool pressed = ImGui::Button(label,size);\n    ImGui::PopStyleColor(4);\n    ImGui::PopStyleVar(1);\n    return pressed;\n}\n\n//-----------------------------------------------------------------------------\n// [Section] Miscellaneous\n//-----------------------------------------------------------------------------\n\nImPlotInputMap& GetInputMap() {\n    IM_ASSERT_USER_ERROR(GImPlot != NULL, \"No current context. Did you call ImPlot::CreateContext() or ImPlot::SetCurrentContext()?\");\n    ImPlotContext& gp = *GImPlot;\n    return gp.InputMap;\n}\n\nvoid MapInputDefault(ImPlotInputMap* dst) {\n    ImPlotInputMap& map = dst ? *dst : GetInputMap();\n    map.Pan             = ImGuiMouseButton_Left;\n    map.PanMod          = ImGuiKeyModFlags_None;\n    map.Fit             = ImGuiMouseButton_Left;\n    map.Menu            = ImGuiMouseButton_Right;\n    map.Select          = ImGuiMouseButton_Right;\n    map.SelectMod       = ImGuiKeyModFlags_None;\n    map.SelectCancel    = ImGuiMouseButton_Left;\n    map.SelectHorzMod   = ImGuiKeyModFlags_Alt;\n    map.SelectVertMod   = ImGuiKeyModFlags_Shift;\n    map.OverrideMod     = ImGuiKeyModFlags_Ctrl;\n    map.ZoomMod         = ImGuiKeyModFlags_None;\n    map.ZoomRate        = 0.1f;\n}\n\nvoid MapInputReverse(ImPlotInputMap* dst) {\n    ImPlotInputMap& map = dst ? *dst : GetInputMap();\n    map.Pan             = ImGuiMouseButton_Right;\n    map.PanMod          = ImGuiKeyModFlags_None;\n    map.Fit             = ImGuiMouseButton_Left;\n    map.Menu            = ImGuiMouseButton_Right;\n    map.Select          = ImGuiMouseButton_Left;\n    map.SelectMod       = ImGuiKeyModFlags_None;\n    map.SelectCancel    = ImGuiMouseButton_Right;\n    map.SelectHorzMod   = ImGuiKeyModFlags_Alt;\n    map.SelectVertMod   = ImGuiKeyModFlags_Shift;\n    map.OverrideMod     = ImGuiKeyModFlags_Ctrl;\n    map.ZoomMod         = ImGuiKeyModFlags_None;\n    map.ZoomRate        = 0.1f;\n}\n\n//-----------------------------------------------------------------------------\n// [Section] Miscellaneous\n//-----------------------------------------------------------------------------\n\nvoid ItemIcon(const ImVec4& col) {\n    ItemIcon(ImGui::ColorConvertFloat4ToU32(col));\n}\n\nvoid ItemIcon(ImU32 col) {\n    const float txt_size = ImGui::GetTextLineHeight();\n    ImVec2 size(txt_size-4,txt_size);\n    ImGuiWindow* window = ImGui::GetCurrentWindow();\n    ImVec2 pos = window->DC.CursorPos;\n    ImGui::GetWindowDrawList()->AddRectFilled(pos + ImVec2(0,2), pos + size - ImVec2(0,2), col);\n    ImGui::Dummy(size);\n}\n\nvoid ColormapIcon(ImPlotColormap cmap) {\n    ImPlotContext& gp = *GImPlot;\n    const float txt_size = ImGui::GetTextLineHeight();\n    ImVec2 size(txt_size-4,txt_size);\n    ImGuiWindow* window = ImGui::GetCurrentWindow();\n    ImVec2 pos = window->DC.CursorPos;\n    ImRect rect(pos+ImVec2(0,2),pos+size-ImVec2(0,2));\n    ImDrawList& DrawList = *ImGui::GetWindowDrawList();\n    RenderColorBar(gp.ColormapData.GetKeys(cmap),gp.ColormapData.GetKeyCount(cmap),DrawList,rect,false,false,!gp.ColormapData.IsQual(cmap));\n    ImGui::Dummy(size);\n}\n\nImDrawList* GetPlotDrawList() {\n    return ImGui::GetWindowDrawList();\n}\n\nvoid PushPlotClipRect(float expand) {\n    ImPlotContext& gp = *GImPlot;\n    IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, \"PushPlotClipRect() needs to be called between BeginPlot() and EndPlot()!\");\n    SetupLock();\n    ImRect rect = gp.CurrentPlot->PlotRect;\n    rect.Expand(expand);\n    ImGui::PushClipRect(rect.Min, rect.Max, true);\n}\n\nvoid PopPlotClipRect() {\n    SetupLock();\n    ImGui::PopClipRect();\n}\n\nstatic void HelpMarker(const char* desc) {\n    ImGui::TextDisabled(\"(?)\");\n    if (ImGui::IsItemHovered()) {\n        ImGui::BeginTooltip();\n        ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);\n        ImGui::TextUnformatted(desc);\n        ImGui::PopTextWrapPos();\n        ImGui::EndTooltip();\n    }\n}\n\nbool ShowStyleSelector(const char* label)\n{\n    static int style_idx = -1;\n    if (ImGui::Combo(label, &style_idx, \"Auto\\0Classic\\0Dark\\0Light\\0\"))\n    {\n        switch (style_idx)\n        {\n        case 0: StyleColorsAuto(); break;\n        case 1: StyleColorsClassic(); break;\n        case 2: StyleColorsDark(); break;\n        case 3: StyleColorsLight(); break;\n        }\n        return true;\n    }\n    return false;\n}\n\nbool ShowColormapSelector(const char* label) {\n    ImPlotContext& gp = *GImPlot;\n    bool set = false;\n    if (ImGui::BeginCombo(label, gp.ColormapData.GetName(gp.Style.Colormap))) {\n        for (int i = 0; i < gp.ColormapData.Count; ++i) {\n            const char* name = gp.ColormapData.GetName(i);\n            if (ImGui::Selectable(name, gp.Style.Colormap == i)) {\n                gp.Style.Colormap = i;\n                ImPlot::BustItemCache();\n                set = true;\n            }\n        }\n        ImGui::EndCombo();\n    }\n    return set;\n}\n\nbool ShowInputMapSelector(const char* label) {\n    static int map_idx = -1;\n    if (ImGui::Combo(label, &map_idx, \"Default\\0Reversed\\0\"))\n    {\n        switch (map_idx)\n        {\n        case 0: MapInputDefault(); break;\n        case 1: MapInputReverse(); break;\n        }\n        return true;\n    }\n    return false;\n}\n\n\nvoid ShowStyleEditor(ImPlotStyle* ref) {\n    ImPlotContext& gp = *GImPlot;\n    ImPlotStyle& style = GetStyle();\n    static ImPlotStyle ref_saved_style;\n    // Default to using internal storage as reference\n    static bool init = true;\n    if (init && ref == NULL)\n        ref_saved_style = style;\n    init = false;\n    if (ref == NULL)\n        ref = &ref_saved_style;\n\n    if (ImPlot::ShowStyleSelector(\"Colors##Selector\"))\n        ref_saved_style = style;\n\n    // Save/Revert button\n    if (ImGui::Button(\"Save Ref\"))\n        *ref = ref_saved_style = style;\n    ImGui::SameLine();\n    if (ImGui::Button(\"Revert Ref\"))\n        style = *ref;\n    ImGui::SameLine();\n    HelpMarker(\"Save/Revert in local non-persistent storage. Default Colors definition are not affected. \"\n               \"Use \\\"Export\\\" below to save them somewhere.\");\n    if (ImGui::BeginTabBar(\"##StyleEditor\")) {\n        if (ImGui::BeginTabItem(\"Variables\")) {\n            ImGui::Text(\"Item Styling\");\n            ImGui::SliderFloat(\"LineWeight\", &style.LineWeight, 0.0f, 5.0f, \"%.1f\");\n            ImGui::SliderFloat(\"MarkerSize\", &style.MarkerSize, 2.0f, 10.0f, \"%.1f\");\n            ImGui::SliderFloat(\"MarkerWeight\", &style.MarkerWeight, 0.0f, 5.0f, \"%.1f\");\n            ImGui::SliderFloat(\"FillAlpha\", &style.FillAlpha, 0.0f, 1.0f, \"%.2f\");\n            ImGui::SliderFloat(\"ErrorBarSize\", &style.ErrorBarSize, 0.0f, 10.0f, \"%.1f\");\n            ImGui::SliderFloat(\"ErrorBarWeight\", &style.ErrorBarWeight, 0.0f, 5.0f, \"%.1f\");\n            ImGui::SliderFloat(\"DigitalBitHeight\", &style.DigitalBitHeight, 0.0f, 20.0f, \"%.1f\");\n            ImGui::SliderFloat(\"DigitalBitGap\", &style.DigitalBitGap, 0.0f, 20.0f, \"%.1f\");\n            float indent = ImGui::CalcItemWidth() - ImGui::GetFrameHeight();\n            ImGui::Indent(ImGui::CalcItemWidth() - ImGui::GetFrameHeight());\n            ImGui::Checkbox(\"AntiAliasedLines\", &style.AntiAliasedLines);\n            ImGui::Unindent(indent);\n            ImGui::Text(\"Plot Styling\");\n            ImGui::SliderFloat(\"PlotBorderSize\", &style.PlotBorderSize, 0.0f, 2.0f, \"%.0f\");\n            ImGui::SliderFloat(\"MinorAlpha\", &style.MinorAlpha, 0.0f, 1.0f, \"%.2f\");\n            ImGui::SliderFloat2(\"MajorTickLen\", (float*)&style.MajorTickLen, 0.0f, 20.0f, \"%.0f\");\n            ImGui::SliderFloat2(\"MinorTickLen\", (float*)&style.MinorTickLen, 0.0f, 20.0f, \"%.0f\");\n            ImGui::SliderFloat2(\"MajorTickSize\",  (float*)&style.MajorTickSize, 0.0f, 2.0f, \"%.1f\");\n            ImGui::SliderFloat2(\"MinorTickSize\", (float*)&style.MinorTickSize, 0.0f, 2.0f, \"%.1f\");\n            ImGui::SliderFloat2(\"MajorGridSize\", (float*)&style.MajorGridSize, 0.0f, 2.0f, \"%.1f\");\n            ImGui::SliderFloat2(\"MinorGridSize\", (float*)&style.MinorGridSize, 0.0f, 2.0f, \"%.1f\");\n            ImGui::SliderFloat2(\"PlotDefaultSize\", (float*)&style.PlotDefaultSize, 0.0f, 1000, \"%.0f\");\n            ImGui::SliderFloat2(\"PlotMinSize\", (float*)&style.PlotMinSize, 0.0f, 300, \"%.0f\");\n            ImGui::Text(\"Plot Padding\");\n            ImGui::SliderFloat2(\"PlotPadding\", (float*)&style.PlotPadding, 0.0f, 20.0f, \"%.0f\");\n            ImGui::SliderFloat2(\"LabelPadding\", (float*)&style.LabelPadding, 0.0f, 20.0f, \"%.0f\");\n            ImGui::SliderFloat2(\"LegendPadding\", (float*)&style.LegendPadding, 0.0f, 20.0f, \"%.0f\");\n            ImGui::SliderFloat2(\"LegendInnerPadding\", (float*)&style.LegendInnerPadding, 0.0f, 10.0f, \"%.0f\");\n            ImGui::SliderFloat2(\"LegendSpacing\", (float*)&style.LegendSpacing, 0.0f, 5.0f, \"%.0f\");\n            ImGui::SliderFloat2(\"MousePosPadding\", (float*)&style.MousePosPadding, 0.0f, 20.0f, \"%.0f\");\n            ImGui::SliderFloat2(\"AnnotationPadding\", (float*)&style.AnnotationPadding, 0.0f, 5.0f, \"%.0f\");\n            ImGui::SliderFloat2(\"FitPadding\", (float*)&style.FitPadding, 0, 0.2f, \"%.2f\");\n\n            ImGui::EndTabItem();\n        }\n        if (ImGui::BeginTabItem(\"Colors\")) {\n            static int output_dest = 0;\n            static bool output_only_modified = false;\n\n            if (ImGui::Button(\"Export\", ImVec2(75,0))) {\n                if (output_dest == 0)\n                    ImGui::LogToClipboard();\n                else\n                    ImGui::LogToTTY();\n                ImGui::LogText(\"ImVec4* colors = ImPlot::GetStyle().Colors;\\n\");\n                for (int i = 0; i < ImPlotCol_COUNT; i++) {\n                    const ImVec4& col = style.Colors[i];\n                    const char* name = ImPlot::GetStyleColorName(i);\n                    if (!output_only_modified || memcmp(&col, &ref->Colors[i], sizeof(ImVec4)) != 0) {\n                        if (IsColorAuto(i))\n                            ImGui::LogText(\"colors[ImPlotCol_%s]%*s= IMPLOT_AUTO_COL;\\n\",name,14 - (int)strlen(name), \"\");\n                        else\n                            ImGui::LogText(\"colors[ImPlotCol_%s]%*s= ImVec4(%.2ff, %.2ff, %.2ff, %.2ff);\\n\",\n                                        name, 14 - (int)strlen(name), \"\", col.x, col.y, col.z, col.w);\n                    }\n                }\n                ImGui::LogFinish();\n            }\n            ImGui::SameLine(); ImGui::SetNextItemWidth(120); ImGui::Combo(\"##output_type\", &output_dest, \"To Clipboard\\0To TTY\\0\");\n            ImGui::SameLine(); ImGui::Checkbox(\"Only Modified Colors\", &output_only_modified);\n\n            static ImGuiTextFilter filter;\n            filter.Draw(\"Filter colors\", ImGui::GetFontSize() * 16);\n\n            static ImGuiColorEditFlags alpha_flags = ImGuiColorEditFlags_AlphaPreviewHalf;\n            if (ImGui::RadioButton(\"Opaque\", alpha_flags == ImGuiColorEditFlags_None))             { alpha_flags = ImGuiColorEditFlags_None; } ImGui::SameLine();\n            if (ImGui::RadioButton(\"Alpha\",  alpha_flags == ImGuiColorEditFlags_AlphaPreview))     { alpha_flags = ImGuiColorEditFlags_AlphaPreview; } ImGui::SameLine();\n            if (ImGui::RadioButton(\"Both\",   alpha_flags == ImGuiColorEditFlags_AlphaPreviewHalf)) { alpha_flags = ImGuiColorEditFlags_AlphaPreviewHalf; } ImGui::SameLine();\n            HelpMarker(\n                \"In the color list:\\n\"\n                \"Left-click on colored square to open color picker,\\n\"\n                \"Right-click to open edit options menu.\");\n            ImGui::Separator();\n            ImGui::PushItemWidth(-160);\n            for (int i = 0; i < ImPlotCol_COUNT; i++) {\n                const char* name = ImPlot::GetStyleColorName(i);\n                if (!filter.PassFilter(name))\n                    continue;\n                ImGui::PushID(i);\n                ImVec4 temp = GetStyleColorVec4(i);\n                const bool is_auto = IsColorAuto(i);\n                if (!is_auto)\n                    ImGui::PushStyleVar(ImGuiStyleVar_Alpha, 0.25f);\n                if (ImGui::Button(\"Auto\")) {\n                    if (is_auto)\n                        style.Colors[i] = temp;\n                    else\n                        style.Colors[i] = IMPLOT_AUTO_COL;\n                    BustItemCache();\n                }\n                if (!is_auto)\n                    ImGui::PopStyleVar();\n                ImGui::SameLine();\n                if (ImGui::ColorEdit4(name, &temp.x, ImGuiColorEditFlags_NoInputs | alpha_flags)) {\n                    style.Colors[i] = temp;\n                    BustItemCache();\n                }\n                if (memcmp(&style.Colors[i], &ref->Colors[i], sizeof(ImVec4)) != 0) {\n                    ImGui::SameLine(175); if (ImGui::Button(\"Save\")) { ref->Colors[i] = style.Colors[i]; }\n                    ImGui::SameLine(); if (ImGui::Button(\"Revert\")) {\n                        style.Colors[i] = ref->Colors[i];\n                        BustItemCache();\n                    }\n                }\n                ImGui::PopID();\n            }\n            ImGui::PopItemWidth();\n            ImGui::Separator();\n            ImGui::Text(\"Colors that are set to Auto (i.e. IMPLOT_AUTO_COL) will\\n\"\n                        \"be automatically deduced from your ImGui style or the\\n\"\n                        \"current ImPlot Colormap. If you want to style individual\\n\"\n                        \"plot items, use Push/PopStyleColor around its function.\");\n            ImGui::EndTabItem();\n        }\n        if (ImGui::BeginTabItem(\"Colormaps\")) {\n            static int output_dest = 0;\n            if (ImGui::Button(\"Export\", ImVec2(75,0))) {\n                if (output_dest == 0)\n                    ImGui::LogToClipboard();\n                else\n                    ImGui::LogToTTY();\n                int size = GetColormapSize();\n                const char* name = GetColormapName(gp.Style.Colormap);\n                ImGui::LogText(\"static const ImU32 %s_Data[%d] = {\\n\", name, size);\n                for (int i = 0; i < size; ++i) {\n                    ImU32 col = GetColormapColorU32(i,gp.Style.Colormap);\n                    ImGui::LogText(\"    %u%s\\n\", col, i == size - 1 ? \"\" : \",\");\n                }\n                ImGui::LogText(\"};\\nImPlotColormap %s = ImPlot::AddColormap(\\\"%s\\\", %s_Data, %d);\", name, name, name, size);\n                ImGui::LogFinish();\n            }\n            ImGui::SameLine(); ImGui::SetNextItemWidth(120); ImGui::Combo(\"##output_type\", &output_dest, \"To Clipboard\\0To TTY\\0\");\n            ImGui::SameLine();\n            static bool edit = false;\n            ImGui::Checkbox(\"Edit Mode\",&edit);\n\n            // built-in/added\n            ImGui::Separator();\n            for (int i = 0; i < gp.ColormapData.Count; ++i) {\n                ImGui::PushID(i);\n                int size = gp.ColormapData.GetKeyCount(i);\n                bool selected = i == gp.Style.Colormap;\n\n                const char* name = GetColormapName(i);\n                if (!selected)\n                    ImGui::PushStyleVar(ImGuiStyleVar_Alpha, 0.25f);\n                if (ImGui::Button(name, ImVec2(100,0))) {\n                    gp.Style.Colormap = i;\n                    BustItemCache();\n                }\n                if (!selected)\n                    ImGui::PopStyleVar();\n                ImGui::SameLine();\n                ImGui::BeginGroup();\n                if (edit) {\n                    for (int c = 0; c < size; ++c) {\n                        ImGui::PushID(c);\n                        ImVec4 col4 = ImGui::ColorConvertU32ToFloat4(gp.ColormapData.GetKeyColor(i,c));\n                        if (ImGui::ColorEdit4(\"\",&col4.x,ImGuiColorEditFlags_NoInputs)) {\n                            ImU32 col32 = ImGui::ColorConvertFloat4ToU32(col4);\n                            gp.ColormapData.SetKeyColor(i,c,col32);\n                            BustItemCache();\n                        }\n                        if ((c + 1) % 12 != 0 && c != size -1)\n                            ImGui::SameLine();\n                        ImGui::PopID();\n                    }\n                }\n                else {\n                    if (ImPlot::ColormapButton(\"##\",ImVec2(-1,0),i))\n                        edit = true;\n                }\n                ImGui::EndGroup();\n                ImGui::PopID();\n            }\n\n\n            static ImVector<ImVec4> custom;\n            if (custom.Size == 0) {\n                custom.push_back(ImVec4(1,0,0,1));\n                custom.push_back(ImVec4(0,1,0,1));\n                custom.push_back(ImVec4(0,0,1,1));\n            }\n            ImGui::Separator();\n            ImGui::BeginGroup();\n            static char name[16] = \"MyColormap\";\n\n\n            if (ImGui::Button(\"+\", ImVec2((100 - ImGui::GetStyle().ItemSpacing.x)/2,0)))\n                custom.push_back(ImVec4(0,0,0,1));\n            ImGui::SameLine();\n            if (ImGui::Button(\"-\", ImVec2((100 - ImGui::GetStyle().ItemSpacing.x)/2,0)) && custom.Size > 2)\n                custom.pop_back();\n            ImGui::SetNextItemWidth(100);\n            ImGui::InputText(\"##Name\",name,16,ImGuiInputTextFlags_CharsNoBlank);\n            static bool qual = true;\n            ImGui::Checkbox(\"Qualitative\",&qual);\n            if (ImGui::Button(\"Add\", ImVec2(100, 0)) && gp.ColormapData.GetIndex(name)==-1)\n                AddColormap(name,custom.Data,custom.Size,qual);\n\n            ImGui::EndGroup();\n            ImGui::SameLine();\n            ImGui::BeginGroup();\n            for (int c = 0; c < custom.Size; ++c) {\n                ImGui::PushID(c);\n                if (ImGui::ColorEdit4(\"##Col1\", &custom[c].x, ImGuiColorEditFlags_NoInputs)) {\n\n                }\n                if ((c + 1) % 12 != 0)\n                    ImGui::SameLine();\n                ImGui::PopID();\n            }\n            ImGui::EndGroup();\n\n\n            ImGui::EndTabItem();\n        }\n        ImGui::EndTabBar();\n    }\n}\n\nvoid ShowUserGuide() {\n        ImGui::BulletText(\"Left-click drag within the plot area to pan X and Y axes.\");\n    ImGui::Indent();\n        ImGui::BulletText(\"Left-click drag on axis labels to pan an individual axis.\");\n    ImGui::Unindent();\n    ImGui::BulletText(\"Scroll in the plot area to zoom both X any Y axes.\");\n    ImGui::Indent();\n        ImGui::BulletText(\"Scroll on axis labels to zoom an individual axis.\");\n    ImGui::Unindent();\n    ImGui::BulletText(\"Right-click drag to box select data.\");\n    ImGui::Indent();\n        ImGui::BulletText(\"Hold Alt to expand box selection horizontally.\");\n        ImGui::BulletText(\"Hold Shift to expand box selection vertically.\");\n        ImGui::BulletText(\"Left-click while box selecting to cancel the selection.\");\n    ImGui::Unindent();\n    ImGui::BulletText(\"Double left-click to fit all visible data.\");\n    ImGui::Indent();\n        ImGui::BulletText(\"Double left-click axis labels to fit the individual axis.\");\n    ImGui::Unindent();\n    ImGui::BulletText(\"Right-click open the full plot context menu.\");\n    ImGui::Indent();\n        ImGui::BulletText(\"Right-click axis labels to open an individual axis context menu.\");\n    ImGui::Unindent();\n    ImGui::BulletText(\"Click legend label icons to show/hide plot items.\");\n}\n\nvoid ShowTicksMetrics(const ImPlotTickCollection& ticks) {\n    ImGui::BulletText(\"Size: %d\", ticks.Size);\n    ImGui::BulletText(\"MaxSize: [%f,%f]\", ticks.MaxSize.x, ticks.MaxSize.y);\n}\n\nvoid ShowAxisMetrics(const ImPlotPlot& plot, const ImPlotAxis& axis) {\n    ImGui::BulletText(\"Label: %s\", axis.LabelOffset == -1 ? \"[none]\" : plot.GetAxisLabel(axis));\n    ImGui::BulletText(\"Flags: 0x%08X\", axis.Flags);\n    ImGui::BulletText(\"Range: [%f,%f]\",axis.Range.Min, axis.Range.Max);\n    ImGui::BulletText(\"Pixels: %f\", axis.PixelSize());\n    ImGui::BulletText(\"Aspect: %f\", axis.GetAspect());\n    ImGui::BulletText(axis.OrthoAxis == NULL ? \"OrtherAxis: NULL\" : \"OrthoAxis: 0x%08X\", axis.OrthoAxis->ID);\n    ImGui::BulletText(\"LinkedMin: %p\", (void*)axis.LinkedMin);\n    ImGui::BulletText(\"LinkedMax: %p\", (void*)axis.LinkedMax);\n    ImGui::BulletText(\"HasRange: %s\", axis.HasRange ? \"true\" : \"false\");\n    ImGui::BulletText(\"Hovered: %s\", axis.Hovered ? \"true\" : \"false\");\n    ImGui::BulletText(\"Held: %s\", axis.Held ? \"true\" : \"false\");\n\n    if (ImGui::TreeNode(\"Transform\")) {\n        ImGui::BulletText(\"PixelMin: %f\", axis.PixelMin);\n        ImGui::BulletText(\"PixelMax: %f\", axis.PixelMax);\n        ImGui::BulletText(\"LinM: %f\", axis.LinM);\n        ImGui::BulletText(\"LogD: %f\", axis.LogD);\n        ImGui::TreePop();\n    }\n\n    if (ImGui::TreeNode(\"Ticks\")) {\n        ShowTicksMetrics(axis.Ticks);\n        ImGui::TreePop();\n    }\n}\n\nvoid ShowMetricsWindow(bool* p_popen) {\n\n    static bool show_plot_rects = false;\n    static bool show_axes_rects = false;\n    static bool show_axis_rects = false;\n    static bool show_canvas_rects = false;\n    static bool show_frame_rects = false;\n    static bool show_subplot_frame_rects = false;\n    static bool show_subplot_grid_rects = false;\n\n    ImDrawList& fg = *ImGui::GetForegroundDrawList();\n\n    ImPlotContext& gp = *GImPlot;\n    // ImGuiContext& g = *GImGui;\n    ImGuiIO& io = ImGui::GetIO();\n    ImGui::Begin(\"ImPlot Metrics\", p_popen);\n    ImGui::Text(\"ImPlot \" IMPLOT_VERSION);\n    ImGui::Text(\"Application average %.3f ms/frame (%.1f FPS)\", 1000.0f / io.Framerate, io.Framerate);\n    ImGui::Text(\"Mouse Position: [%.0f,%.0f]\", io.MousePos.x, io.MousePos.y);\n    ImGui::Separator();\n    if (ImGui::TreeNode(\"Tools\")) {\n        if (ImGui::Button(\"Bust Plot Cache\"))\n            BustPlotCache();\n        ImGui::SameLine();\n        if (ImGui::Button(\"Bust Item Cache\"))\n            BustItemCache();\n        ImGui::Checkbox(\"Show Frame Rects\", &show_frame_rects);\n        ImGui::Checkbox(\"Show Canvas Rects\",&show_canvas_rects);\n        ImGui::Checkbox(\"Show Plot Rects\",  &show_plot_rects);\n        ImGui::Checkbox(\"Show Axes Rects\",  &show_axes_rects);\n        ImGui::Checkbox(\"Show Axis Rects\",  &show_axis_rects);\n        ImGui::Checkbox(\"Show Subplot Frame Rects\",  &show_subplot_frame_rects);\n        ImGui::Checkbox(\"Show Subplot Grid Rects\",  &show_subplot_grid_rects);\n        ImGui::TreePop();\n    }\n    const int n_plots = gp.Plots.GetBufSize();\n    const int n_subplots = gp.Subplots.GetBufSize();\n    // render rects\n    for (int p = 0; p < n_plots; ++p) {\n        ImPlotPlot* plot = gp.Plots.GetByIndex(p);\n        if (show_frame_rects)\n            fg.AddRect(plot->FrameRect.Min, plot->FrameRect.Max, IM_COL32(255,0,255,255));\n        if (show_canvas_rects)\n            fg.AddRect(plot->CanvasRect.Min, plot->CanvasRect.Max, IM_COL32(0,255,255,255));\n        if (show_plot_rects)\n            fg.AddRect(plot->PlotRect.Min, plot->PlotRect.Max, IM_COL32(255,255,0,255));\n        if (show_axes_rects)\n            fg.AddRect(plot->AxesRect.Min, plot->AxesRect.Max, IM_COL32(0,255,128,255));\n        if (show_axis_rects) {\n            for (int i = 0; i < ImAxis_COUNT; ++i) {\n                if (plot->Axes[i].Enabled)\n                    fg.AddRect(plot->Axes[i].HoverRect.Min, plot->Axes[i].HoverRect.Max, IM_COL32(0,255,0,255));\n            }\n        }\n    }\n    for (int p = 0; p < n_subplots; ++p) {\n        ImPlotSubplot* subplot = gp.Subplots.GetByIndex(p);\n        if (show_subplot_frame_rects)\n            fg.AddRect(subplot->FrameRect.Min, subplot->FrameRect.Max, IM_COL32(255,0,0,255));\n        if (show_subplot_grid_rects)\n            fg.AddRect(subplot->GridRect.Min, subplot->GridRect.Max, IM_COL32(0,0,255,255));\n    }\n    if (ImGui::TreeNode(\"Plots\",\"Plots (%d)\", n_plots)) {\n        for (int p = 0; p < n_plots; ++p) {\n            // plot\n            ImPlotPlot& plot = *gp.Plots.GetByIndex(p);\n            ImGui::PushID(p);\n            if (ImGui::TreeNode(\"Plot\", \"Plot [0x%08X]\", plot.ID)) {\n                int n_items = plot.Items.GetItemCount();\n                if (ImGui::TreeNode(\"Items\", \"Items (%d)\", n_items)) {\n                    for (int i = 0; i < n_items; ++i) {\n                        ImPlotItem* item = plot.Items.GetItemByIndex(i);\n                        ImGui::PushID(i);\n                        if (ImGui::TreeNode(\"Item\", \"Item [0x%08X]\", item->ID)) {\n                            ImGui::Bullet(); ImGui::Checkbox(\"Show\", &item->Show);\n                            ImGui::Bullet();\n                            ImVec4 temp = ImGui::ColorConvertU32ToFloat4(item->Color);\n                            if (ImGui::ColorEdit4(\"Color\",&temp.x, ImGuiColorEditFlags_NoInputs))\n                                item->Color = ImGui::ColorConvertFloat4ToU32(temp);\n\n                            ImGui::BulletText(\"NameOffset: %d\",item->NameOffset);\n                            ImGui::BulletText(\"Name: %s\", item->NameOffset != -1 ? plot.Items.Legend.Labels.Buf.Data + item->NameOffset : \"N/A\");\n                            ImGui::BulletText(\"Hovered: %s\",item->LegendHovered ? \"true\" : \"false\");\n                            ImGui::TreePop();\n                        }\n                        ImGui::PopID();\n                    }\n                    ImGui::TreePop();\n                }\n                char buff[16];\n                for (int i = 0; i < IMPLOT_NUM_X_AXES; ++i) {\n                    ImFormatString(buff,16,\"X-Axis %d\", i+1);\n                    if (plot.XAxis(i).Enabled && ImGui::TreeNode(buff, \"X-Axis %d [0x%08X]\", i+1, plot.XAxis(i).ID)) {\n                        ShowAxisMetrics(plot, plot.XAxis(i));\n                        ImGui::TreePop();\n                    }\n                }\n                for (int i = 0; i < IMPLOT_NUM_Y_AXES; ++i) {\n                    ImFormatString(buff,16,\"Y-Axis %d\", i+1);\n                    if (plot.YAxis(i).Enabled && ImGui::TreeNode(buff, \"Y-Axis %d [0x%08X]\", i+1, plot.YAxis(i).ID)) {\n                        ShowAxisMetrics(plot, plot.YAxis(i));\n                        ImGui::TreePop();\n                    }\n                }\n                ImGui::BulletText(\"Title: %s\", plot.HasTitle() ? plot.GetTitle() : \"none\");\n                ImGui::BulletText(\"Flags: 0x%08X\", plot.Flags);\n                ImGui::BulletText(\"Initialized: %s\", plot.Initialized ? \"true\" : \"false\");\n                ImGui::BulletText(\"Selecting: %s\", plot.Selecting ? \"true\" : \"false\");\n                ImGui::BulletText(\"Selected: %s\", plot.Selected ? \"true\" : \"false\");\n                ImGui::BulletText(\"Hovered: %s\", plot.Hovered ? \"true\" : \"false\");\n                ImGui::BulletText(\"Held: %s\", plot.Held ? \"true\" : \"false\");\n                ImGui::BulletText(\"LegendHovered: %s\", plot.Items.Legend.Hovered ? \"true\" : \"false\");\n                ImGui::BulletText(\"ContextLocked: %s\", plot.ContextLocked ? \"true\" : \"false\");\n                ImGui::TreePop();\n            }\n            ImGui::PopID();\n        }\n        ImGui::TreePop();\n    }\n\n    if (ImGui::TreeNode(\"Subplots\",\"Subplots (%d)\", n_subplots)) {\n        for (int p = 0; p < n_subplots; ++p) {\n            // plot\n            ImPlotSubplot& plot = *gp.Subplots.GetByIndex(p);\n            ImGui::PushID(p);\n            if (ImGui::TreeNode(\"Subplot\", \"Subplot [0x%08X]\", plot.ID)) {\n                int n_items = plot.Items.GetItemCount();\n                if (ImGui::TreeNode(\"Items\", \"Items (%d)\", n_items)) {\n                    for (int i = 0; i < n_items; ++i) {\n                        ImPlotItem* item = plot.Items.GetItemByIndex(i);\n                        ImGui::PushID(i);\n                        if (ImGui::TreeNode(\"Item\", \"Item [0x%08X]\", item->ID)) {\n                            ImGui::Bullet(); ImGui::Checkbox(\"Show\", &item->Show);\n                            ImGui::Bullet();\n                            ImVec4 temp = ImGui::ColorConvertU32ToFloat4(item->Color);\n                            if (ImGui::ColorEdit4(\"Color\",&temp.x, ImGuiColorEditFlags_NoInputs))\n                                item->Color = ImGui::ColorConvertFloat4ToU32(temp);\n\n                            ImGui::BulletText(\"NameOffset: %d\",item->NameOffset);\n                            ImGui::BulletText(\"Name: %s\", item->NameOffset != -1 ? plot.Items.Legend.Labels.Buf.Data + item->NameOffset : \"N/A\");\n                            ImGui::BulletText(\"Hovered: %s\",item->LegendHovered ? \"true\" : \"false\");\n                            ImGui::TreePop();\n                        }\n                        ImGui::PopID();\n                    }\n                    ImGui::TreePop();\n                }\n                ImGui::BulletText(\"Flags: 0x%08X\", plot.Flags);\n                ImGui::BulletText(\"FrameHovered: %s\", plot.FrameHovered ? \"true\" : \"false\");\n                ImGui::BulletText(\"LegendHovered: %s\", plot.Items.Legend.Hovered ? \"true\" : \"false\");\n                ImGui::TreePop();\n            }\n            ImGui::PopID();\n        }\n        ImGui::TreePop();\n    }\n    if (ImGui::TreeNode(\"Colormaps\")) {\n        ImGui::BulletText(\"Colormaps:  %d\", gp.ColormapData.Count);\n        ImGui::BulletText(\"Memory: %d bytes\", gp.ColormapData.Tables.Size * 4);\n        if (ImGui::TreeNode(\"Data\")) {\n            for (int m = 0; m < gp.ColormapData.Count; ++m) {\n                if (ImGui::TreeNode(gp.ColormapData.GetName(m))) {\n                    int count = gp.ColormapData.GetKeyCount(m);\n                    int size = gp.ColormapData.GetTableSize(m);\n                    bool qual = gp.ColormapData.IsQual(m);\n                    ImGui::BulletText(\"Qualitative: %s\", qual ? \"true\" : \"false\");\n                    ImGui::BulletText(\"Key Count: %d\", count);\n                    ImGui::BulletText(\"Table Size: %d\", size);\n                    ImGui::Indent();\n\n                    static float t = 0.5;\n                    ImVec4 samp;\n                    float wid = 32 * 10 - ImGui::GetFrameHeight() - ImGui::GetStyle().ItemSpacing.x;\n                    ImGui::SetNextItemWidth(wid);\n                    ImPlot::ColormapSlider(\"##Sample\",&t,&samp,\"%.3f\",m);\n                    ImGui::SameLine();\n                    ImGui::ColorButton(\"Sampler\",samp);\n                    ImGui::PushStyleColor(ImGuiCol_FrameBg, ImVec4(0,0,0,0));\n                    ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0,0));\n                    for (int c = 0; c < size; ++c) {\n                        ImVec4 col = ImGui::ColorConvertU32ToFloat4(gp.ColormapData.GetTableColor(m,c));\n                        ImGui::PushID(m*1000+c);\n                        ImGui::ColorButton(\"\",col,0,ImVec2(10,10));\n                        ImGui::PopID();\n                        if ((c + 1) % 32 != 0 && c != size - 1)\n                            ImGui::SameLine();\n                    }\n                    ImGui::PopStyleVar();\n                    ImGui::PopStyleColor();\n                    ImGui::Unindent();\n                    ImGui::TreePop();\n                }\n            }\n            ImGui::TreePop();\n        }\n        ImGui::TreePop();\n    }\n    ImGui::End();\n}\n\nbool ShowDatePicker(const char* id, int* level, ImPlotTime* t, const ImPlotTime* t1, const ImPlotTime* t2) {\n\n    ImGui::PushID(id);\n    ImGui::BeginGroup();\n\n    ImGuiStyle& style = ImGui::GetStyle();\n    ImVec4 col_txt    = style.Colors[ImGuiCol_Text];\n    ImVec4 col_dis    = style.Colors[ImGuiCol_TextDisabled];\n    ImVec4 col_btn    = style.Colors[ImGuiCol_Button];\n    ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0,0,0,0));\n    ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0,0));\n\n    const float ht    = ImGui::GetFrameHeight();\n    ImVec2 cell_size(ht*1.25f,ht);\n    char buff[32];\n    bool clk = false;\n    tm& Tm = GImPlot->Tm;\n\n    const int min_yr = 1970;\n    const int max_yr = 2999;\n\n    // t1 parts\n    int t1_mo = 0; int t1_md = 0; int t1_yr = 0;\n    if (t1 != NULL) {\n        GetTime(*t1,&Tm);\n        t1_mo = Tm.tm_mon;\n        t1_md = Tm.tm_mday;\n        t1_yr = Tm.tm_year + 1900;\n    }\n\n     // t2 parts\n    int t2_mo = 0; int t2_md = 0; int t2_yr = 0;\n    if (t2 != NULL) {\n        GetTime(*t2,&Tm);\n        t2_mo = Tm.tm_mon;\n        t2_md = Tm.tm_mday;\n        t2_yr = Tm.tm_year + 1900;\n    }\n\n    // day widget\n    if (*level == 0) {\n        *t = FloorTime(*t, ImPlotTimeUnit_Day);\n        GetTime(*t, &Tm);\n        const int this_year = Tm.tm_year + 1900;\n        const int last_year = this_year - 1;\n        const int next_year = this_year + 1;\n        const int this_mon  = Tm.tm_mon;\n        const int last_mon  = this_mon == 0 ? 11 : this_mon - 1;\n        const int next_mon  = this_mon == 11 ? 0 : this_mon + 1;\n        const int days_this_mo = GetDaysInMonth(this_year, this_mon);\n        const int days_last_mo = GetDaysInMonth(this_mon == 0 ? last_year : this_year, last_mon);\n        ImPlotTime t_first_mo = FloorTime(*t,ImPlotTimeUnit_Mo);\n        GetTime(t_first_mo,&Tm);\n        const int first_wd = Tm.tm_wday;\n        // month year\n        ImFormatString(buff, 32, \"%s %d\", MONTH_NAMES[this_mon], this_year);\n        if (ImGui::Button(buff))\n            *level = 1;\n        ImGui::SameLine(5*cell_size.x);\n        BeginDisabledControls(this_year <= min_yr && this_mon == 0);\n        if (ImGui::ArrowButtonEx(\"##Up\",ImGuiDir_Up,cell_size))\n            *t = AddTime(*t, ImPlotTimeUnit_Mo, -1);\n        EndDisabledControls(this_year <= min_yr && this_mon == 0);\n        ImGui::SameLine();\n        BeginDisabledControls(this_year >= max_yr && this_mon == 11);\n        if (ImGui::ArrowButtonEx(\"##Down\",ImGuiDir_Down,cell_size))\n            *t = AddTime(*t, ImPlotTimeUnit_Mo, 1);\n        EndDisabledControls(this_year >= max_yr && this_mon == 11);\n        // render weekday abbreviations\n        ImGui::PushItemFlag(ImGuiItemFlags_Disabled, true);\n        for (int i = 0; i < 7; ++i) {\n            ImGui::Button(WD_ABRVS[i],cell_size);\n            if (i != 6) { ImGui::SameLine(); }\n        }\n        ImGui::PopItemFlag();\n        // 0 = last mo, 1 = this mo, 2 = next mo\n        int mo = first_wd > 0 ? 0 : 1;\n        int day = mo == 1 ? 1 : days_last_mo - first_wd + 1;\n        for (int i = 0; i < 6; ++i) {\n            for (int j = 0; j < 7; ++j) {\n                if (mo == 0 && day > days_last_mo) {\n                    mo = 1;\n                    day = 1;\n                }\n                else if (mo == 1 && day > days_this_mo) {\n                    mo = 2;\n                    day = 1;\n                }\n                const int now_yr = (mo == 0 && this_mon == 0) ? last_year : ((mo == 2 && this_mon == 11) ? next_year : this_year);\n                const int now_mo = mo == 0 ? last_mon : (mo == 1 ? this_mon : next_mon);\n                const int now_md = day;\n\n                const bool off_mo   = mo == 0 || mo == 2;\n                const bool t1_or_t2 = (t1 != NULL && t1_mo == now_mo && t1_yr == now_yr && t1_md == now_md) ||\n                                      (t2 != NULL && t2_mo == now_mo && t2_yr == now_yr && t2_md == now_md);\n\n                if (off_mo)\n                    ImGui::PushStyleColor(ImGuiCol_Text, col_dis);\n                if (t1_or_t2) {\n                    ImGui::PushStyleColor(ImGuiCol_Button, col_btn);\n                    ImGui::PushStyleColor(ImGuiCol_Text, col_txt);\n                }\n                ImGui::PushID(i*7+j);\n                ImFormatString(buff,32,\"%d\",day);\n                if (now_yr == min_yr-1 || now_yr == max_yr+1) {\n                    ImGui::Dummy(cell_size);\n                }\n                else if (ImGui::Button(buff,cell_size) && !clk) {\n                    *t = MakeTime(now_yr, now_mo, now_md);\n                    clk = true;\n                }\n                ImGui::PopID();\n                if (t1_or_t2)\n                    ImGui::PopStyleColor(2);\n                if (off_mo)\n                    ImGui::PopStyleColor();\n                if (j != 6)\n                    ImGui::SameLine();\n                day++;\n            }\n        }\n    }\n    // month widget\n    else if (*level == 1) {\n        *t = FloorTime(*t, ImPlotTimeUnit_Mo);\n        GetTime(*t, &Tm);\n        int this_yr  = Tm.tm_year + 1900;\n        ImFormatString(buff, 32, \"%d\", this_yr);\n        if (ImGui::Button(buff))\n            *level = 2;\n        BeginDisabledControls(this_yr <= min_yr);\n        ImGui::SameLine(5*cell_size.x);\n        if (ImGui::ArrowButtonEx(\"##Up\",ImGuiDir_Up,cell_size))\n            *t = AddTime(*t, ImPlotTimeUnit_Yr, -1);\n        EndDisabledControls(this_yr <= min_yr);\n        ImGui::SameLine();\n        BeginDisabledControls(this_yr >= max_yr);\n        if (ImGui::ArrowButtonEx(\"##Down\",ImGuiDir_Down,cell_size))\n            *t = AddTime(*t, ImPlotTimeUnit_Yr, 1);\n        EndDisabledControls(this_yr >= max_yr);\n        // ImGui::Dummy(cell_size);\n        cell_size.x *= 7.0f/4.0f;\n        cell_size.y *= 7.0f/3.0f;\n        int mo = 0;\n        for (int i = 0; i < 3; ++i) {\n            for (int j = 0; j < 4; ++j) {\n                const bool t1_or_t2 = (t1 != NULL && t1_yr == this_yr && t1_mo == mo) ||\n                                      (t2 != NULL && t2_yr == this_yr && t2_mo == mo);\n                if (t1_or_t2)\n                    ImGui::PushStyleColor(ImGuiCol_Button, col_btn);\n                if (ImGui::Button(MONTH_ABRVS[mo],cell_size) && !clk) {\n                    *t = MakeTime(this_yr, mo);\n                    *level = 0;\n                }\n                if (t1_or_t2)\n                    ImGui::PopStyleColor();\n                if (j != 3)\n                    ImGui::SameLine();\n                mo++;\n            }\n        }\n    }\n    else if (*level == 2) {\n        *t = FloorTime(*t, ImPlotTimeUnit_Yr);\n        int this_yr = GetYear(*t);\n        int yr = this_yr  - this_yr % 20;\n        ImGui::PushItemFlag(ImGuiItemFlags_Disabled, true);\n        ImFormatString(buff,32,\"%d-%d\",yr,yr+19);\n        ImGui::Button(buff);\n        ImGui::PopItemFlag();\n        ImGui::SameLine(5*cell_size.x);\n        BeginDisabledControls(yr <= min_yr);\n        if (ImGui::ArrowButtonEx(\"##Up\",ImGuiDir_Up,cell_size))\n            *t = MakeTime(yr-20);\n        EndDisabledControls(yr <= min_yr);\n        ImGui::SameLine();\n        BeginDisabledControls(yr + 20 >= max_yr);\n        if (ImGui::ArrowButtonEx(\"##Down\",ImGuiDir_Down,cell_size))\n            *t = MakeTime(yr+20);\n        EndDisabledControls(yr+ 20 >= max_yr);\n        // ImGui::Dummy(cell_size);\n        cell_size.x *= 7.0f/4.0f;\n        cell_size.y *= 7.0f/5.0f;\n        for (int i = 0; i < 5; ++i) {\n            for (int j = 0; j < 4; ++j) {\n                const bool t1_or_t2 = (t1 != NULL && t1_yr == yr) || (t2 != NULL && t2_yr == yr);\n                if (t1_or_t2)\n                    ImGui::PushStyleColor(ImGuiCol_Button, col_btn);\n                ImFormatString(buff,32,\"%d\",yr);\n                if (yr<1970||yr>3000) {\n                    ImGui::Dummy(cell_size);\n                }\n                else if (ImGui::Button(buff,cell_size)) {\n                    *t = MakeTime(yr);\n                    *level = 1;\n                }\n                if (t1_or_t2)\n                    ImGui::PopStyleColor();\n                if (j != 3)\n                    ImGui::SameLine();\n                yr++;\n            }\n        }\n    }\n    ImGui::PopStyleVar();\n    ImGui::PopStyleColor();\n    ImGui::EndGroup();\n    ImGui::PopID();\n    return clk;\n}\n\nbool ShowTimePicker(const char* id, ImPlotTime* t) {\n    ImGui::PushID(id);\n    tm& Tm = GImPlot->Tm;\n    GetTime(*t,&Tm);\n\n    static const char* nums[] = { \"00\",\"01\",\"02\",\"03\",\"04\",\"05\",\"06\",\"07\",\"08\",\"09\",\n                                  \"10\",\"11\",\"12\",\"13\",\"14\",\"15\",\"16\",\"17\",\"18\",\"19\",\n                                  \"20\",\"21\",\"22\",\"23\",\"24\",\"25\",\"26\",\"27\",\"28\",\"29\",\n                                  \"30\",\"31\",\"32\",\"33\",\"34\",\"35\",\"36\",\"37\",\"38\",\"39\",\n                                  \"40\",\"41\",\"42\",\"43\",\"44\",\"45\",\"46\",\"47\",\"48\",\"49\",\n                                  \"50\",\"51\",\"52\",\"53\",\"54\",\"55\",\"56\",\"57\",\"58\",\"59\"};\n\n    static const char* am_pm[] = {\"am\",\"pm\"};\n\n    bool hour24 = GImPlot->Style.Use24HourClock;\n\n    int hr  = hour24 ? Tm.tm_hour : ((Tm.tm_hour == 0 || Tm.tm_hour == 12) ? 12 : Tm.tm_hour % 12);\n    int min = Tm.tm_min;\n    int sec = Tm.tm_sec;\n    int ap  = Tm.tm_hour < 12 ? 0 : 1;\n\n    bool changed = false;\n\n    ImVec2 spacing = ImGui::GetStyle().ItemSpacing;\n    spacing.x = 0;\n    float width    = ImGui::CalcTextSize(\"888\").x;\n    float height   = ImGui::GetFrameHeight();\n\n    ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, spacing);\n    ImGui::PushStyleVar(ImGuiStyleVar_ScrollbarSize,2.0f);\n    ImGui::PushStyleColor(ImGuiCol_FrameBg, ImVec4(0,0,0,0));\n    ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0,0,0,0));\n    ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, ImGui::GetStyleColorVec4(ImGuiCol_ButtonHovered));\n\n    ImGui::SetNextItemWidth(width);\n    if (ImGui::BeginCombo(\"##hr\",nums[hr],ImGuiComboFlags_NoArrowButton)) {\n        const int ia = hour24 ? 0 : 1;\n        const int ib = hour24 ? 24 : 13;\n        for (int i = ia; i < ib; ++i) {\n            if (ImGui::Selectable(nums[i],i==hr)) {\n                hr = i;\n                changed = true;\n            }\n        }\n        ImGui::EndCombo();\n    }\n    ImGui::SameLine();\n    ImGui::Text(\":\");\n    ImGui::SameLine();\n    ImGui::SetNextItemWidth(width);\n    if (ImGui::BeginCombo(\"##min\",nums[min],ImGuiComboFlags_NoArrowButton)) {\n        for (int i = 0; i < 60; ++i) {\n            if (ImGui::Selectable(nums[i],i==min)) {\n                min = i;\n                changed = true;\n            }\n        }\n        ImGui::EndCombo();\n    }\n    ImGui::SameLine();\n    ImGui::Text(\":\");\n    ImGui::SameLine();\n    ImGui::SetNextItemWidth(width);\n    if (ImGui::BeginCombo(\"##sec\",nums[sec],ImGuiComboFlags_NoArrowButton)) {\n        for (int i = 0; i < 60; ++i) {\n            if (ImGui::Selectable(nums[i],i==sec)) {\n                sec = i;\n                changed = true;\n            }\n        }\n        ImGui::EndCombo();\n    }\n    if (!hour24) {\n        ImGui::SameLine();\n        if (ImGui::Button(am_pm[ap],ImVec2(0,height))) {\n            ap = 1 - ap;\n            changed = true;\n        }\n    }\n\n    ImGui::PopStyleColor(3);\n    ImGui::PopStyleVar(2);\n    ImGui::PopID();\n\n    if (changed) {\n        if (!hour24)\n            hr = hr % 12 + ap * 12;\n        Tm.tm_hour = hr;\n        Tm.tm_min  = min;\n        Tm.tm_sec  = sec;\n        *t = MkTime(&Tm);\n    }\n\n    return changed;\n}\n\nvoid StyleColorsAuto(ImPlotStyle* dst) {\n    ImPlotStyle* style              = dst ? dst : &ImPlot::GetStyle();\n    ImVec4* colors                  = style->Colors;\n\n    style->MinorAlpha               = 0.25f;\n\n    colors[ImPlotCol_Line]          = IMPLOT_AUTO_COL;\n    colors[ImPlotCol_Fill]          = IMPLOT_AUTO_COL;\n    colors[ImPlotCol_MarkerOutline] = IMPLOT_AUTO_COL;\n    colors[ImPlotCol_MarkerFill]    = IMPLOT_AUTO_COL;\n    colors[ImPlotCol_ErrorBar]      = IMPLOT_AUTO_COL;\n    colors[ImPlotCol_FrameBg]       = IMPLOT_AUTO_COL;\n    colors[ImPlotCol_PlotBg]        = IMPLOT_AUTO_COL;\n    colors[ImPlotCol_PlotBorder]    = IMPLOT_AUTO_COL;\n    colors[ImPlotCol_LegendBg]      = IMPLOT_AUTO_COL;\n    colors[ImPlotCol_LegendBorder]  = IMPLOT_AUTO_COL;\n    colors[ImPlotCol_LegendText]    = IMPLOT_AUTO_COL;\n    colors[ImPlotCol_TitleText]     = IMPLOT_AUTO_COL;\n    colors[ImPlotCol_InlayText]     = IMPLOT_AUTO_COL;\n    colors[ImPlotCol_PlotBorder]    = IMPLOT_AUTO_COL;\n    colors[ImPlotCol_AxisText]      = IMPLOT_AUTO_COL;\n    colors[ImPlotCol_AxisGrid]      = IMPLOT_AUTO_COL;\n    colors[ImPlotCol_AxisTick]      = IMPLOT_AUTO_COL;\n    colors[ImPlotCol_AxisBg]        = IMPLOT_AUTO_COL;\n    colors[ImPlotCol_AxisBgHovered] = IMPLOT_AUTO_COL;\n    colors[ImPlotCol_AxisBgActive]  = IMPLOT_AUTO_COL;\n    colors[ImPlotCol_Selection]     = IMPLOT_AUTO_COL;\n    colors[ImPlotCol_Crosshairs]    = IMPLOT_AUTO_COL;\n}\n\nvoid StyleColorsClassic(ImPlotStyle* dst) {\n    ImPlotStyle* style              = dst ? dst : &ImPlot::GetStyle();\n    ImVec4* colors                  = style->Colors;\n\n    style->MinorAlpha               = 0.5f;\n\n    colors[ImPlotCol_Line]          = IMPLOT_AUTO_COL;\n    colors[ImPlotCol_Fill]          = IMPLOT_AUTO_COL;\n    colors[ImPlotCol_MarkerOutline] = IMPLOT_AUTO_COL;\n    colors[ImPlotCol_MarkerFill]    = IMPLOT_AUTO_COL;\n    colors[ImPlotCol_ErrorBar]      = ImVec4(0.90f, 0.90f, 0.90f, 1.00f);\n    colors[ImPlotCol_FrameBg]       = ImVec4(0.43f, 0.43f, 0.43f, 0.39f);\n    colors[ImPlotCol_PlotBg]        = ImVec4(0.00f, 0.00f, 0.00f, 0.35f);\n    colors[ImPlotCol_PlotBorder]    = ImVec4(0.50f, 0.50f, 0.50f, 0.50f);\n    colors[ImPlotCol_LegendBg]      = ImVec4(0.11f, 0.11f, 0.14f, 0.92f);\n    colors[ImPlotCol_LegendBorder]  = ImVec4(0.50f, 0.50f, 0.50f, 0.50f);\n    colors[ImPlotCol_LegendText]    = ImVec4(0.90f, 0.90f, 0.90f, 1.00f);\n    colors[ImPlotCol_TitleText]     = ImVec4(0.90f, 0.90f, 0.90f, 1.00f);\n    colors[ImPlotCol_InlayText]     = ImVec4(0.90f, 0.90f, 0.90f, 1.00f);\n    colors[ImPlotCol_AxisText]      = ImVec4(0.90f, 0.90f, 0.90f, 1.00f);\n    colors[ImPlotCol_AxisGrid]      = ImVec4(0.90f, 0.90f, 0.90f, 0.25f);\n    colors[ImPlotCol_AxisTick]      = IMPLOT_AUTO_COL; // TODO\n    colors[ImPlotCol_AxisBg]        = IMPLOT_AUTO_COL; // TODO\n    colors[ImPlotCol_AxisBgHovered] = IMPLOT_AUTO_COL; // TODO\n    colors[ImPlotCol_AxisBgActive]  = IMPLOT_AUTO_COL; // TODO\n    colors[ImPlotCol_Selection]     = ImVec4(0.97f, 0.97f, 0.39f, 1.00f);\n    colors[ImPlotCol_Crosshairs]    = ImVec4(0.50f, 0.50f, 0.50f, 0.75f);\n}\n\nvoid StyleColorsDark(ImPlotStyle* dst) {\n    ImPlotStyle* style              = dst ? dst : &ImPlot::GetStyle();\n    ImVec4* colors                  = style->Colors;\n\n    style->MinorAlpha               = 0.25f;\n\n    colors[ImPlotCol_Line]          = IMPLOT_AUTO_COL;\n    colors[ImPlotCol_Fill]          = IMPLOT_AUTO_COL;\n    colors[ImPlotCol_MarkerOutline] = IMPLOT_AUTO_COL;\n    colors[ImPlotCol_MarkerFill]    = IMPLOT_AUTO_COL;\n    colors[ImPlotCol_ErrorBar]      = IMPLOT_AUTO_COL;\n    colors[ImPlotCol_FrameBg]       = ImVec4(1.00f, 1.00f, 1.00f, 0.07f);\n    colors[ImPlotCol_PlotBg]        = ImVec4(0.00f, 0.00f, 0.00f, 0.50f);\n    colors[ImPlotCol_PlotBorder]    = ImVec4(0.43f, 0.43f, 0.50f, 0.50f);\n    colors[ImPlotCol_LegendBg]      = ImVec4(0.08f, 0.08f, 0.08f, 0.94f);\n    colors[ImPlotCol_LegendBorder]  = ImVec4(0.43f, 0.43f, 0.50f, 0.50f);\n    colors[ImPlotCol_LegendText]    = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);\n    colors[ImPlotCol_TitleText]     = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);\n    colors[ImPlotCol_InlayText]     = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);\n    colors[ImPlotCol_AxisText]      = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);\n    colors[ImPlotCol_AxisGrid]      = ImVec4(1.00f, 1.00f, 1.00f, 0.25f);\n    colors[ImPlotCol_AxisTick]      = IMPLOT_AUTO_COL; // TODO\n    colors[ImPlotCol_AxisBg]        = IMPLOT_AUTO_COL; // TODO\n    colors[ImPlotCol_AxisBgHovered] = IMPLOT_AUTO_COL; // TODO\n    colors[ImPlotCol_AxisBgActive]  = IMPLOT_AUTO_COL; // TODO\n    colors[ImPlotCol_Selection]     = ImVec4(1.00f, 0.60f, 0.00f, 1.00f);\n    colors[ImPlotCol_Crosshairs]    = ImVec4(1.00f, 1.00f, 1.00f, 0.50f);\n}\n\nvoid StyleColorsLight(ImPlotStyle* dst) {\n    ImPlotStyle* style              = dst ? dst : &ImPlot::GetStyle();\n    ImVec4* colors                  = style->Colors;\n\n    style->MinorAlpha               = 1.0f;\n\n    colors[ImPlotCol_Line]          = IMPLOT_AUTO_COL;\n    colors[ImPlotCol_Fill]          = IMPLOT_AUTO_COL;\n    colors[ImPlotCol_MarkerOutline] = IMPLOT_AUTO_COL;\n    colors[ImPlotCol_MarkerFill]    = IMPLOT_AUTO_COL;\n    colors[ImPlotCol_ErrorBar]      = IMPLOT_AUTO_COL;\n    colors[ImPlotCol_FrameBg]       = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);\n    colors[ImPlotCol_PlotBg]        = ImVec4(0.42f, 0.57f, 1.00f, 0.13f);\n    colors[ImPlotCol_PlotBorder]    = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);\n    colors[ImPlotCol_LegendBg]      = ImVec4(1.00f, 1.00f, 1.00f, 0.98f);\n    colors[ImPlotCol_LegendBorder]  = ImVec4(0.82f, 0.82f, 0.82f, 0.80f);\n    colors[ImPlotCol_LegendText]    = ImVec4(0.00f, 0.00f, 0.00f, 1.00f);\n    colors[ImPlotCol_TitleText]     = ImVec4(0.00f, 0.00f, 0.00f, 1.00f);\n    colors[ImPlotCol_InlayText]     = ImVec4(0.00f, 0.00f, 0.00f, 1.00f);\n    colors[ImPlotCol_AxisText]      = ImVec4(0.00f, 0.00f, 0.00f, 1.00f);\n    colors[ImPlotCol_AxisGrid]      = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);\n    colors[ImPlotCol_AxisTick]      = ImVec4(0.00f, 0.00f, 0.00f, 0.25f);\n    colors[ImPlotCol_AxisBg]        = IMPLOT_AUTO_COL; // TODO\n    colors[ImPlotCol_AxisBgHovered] = IMPLOT_AUTO_COL; // TODO\n    colors[ImPlotCol_AxisBgActive]  = IMPLOT_AUTO_COL; // TODO\n    colors[ImPlotCol_Selection]     = ImVec4(0.82f, 0.64f, 0.03f, 1.00f);\n    colors[ImPlotCol_Crosshairs]    = ImVec4(0.00f, 0.00f, 0.00f, 0.50f);\n}\n\n//-----------------------------------------------------------------------------\n// [SECTION] Obsolete Functions/Types\n//-----------------------------------------------------------------------------\n\n#ifndef IMPLOT_DISABLE_OBSOLETE_FUNCTIONS\n\nbool BeginPlot(const char* title, const char* x_label, const char* y1_label, const ImVec2& size,\n               ImPlotFlags flags, ImPlotAxisFlags x_flags, ImPlotAxisFlags y1_flags, ImPlotAxisFlags y2_flags, ImPlotAxisFlags y3_flags,\n               const char* y2_label, const char* y3_label)\n{\n    if (!BeginPlot(title, size, flags))\n        return false;\n    SetupAxis(ImAxis_X1, x_label, x_flags);\n    SetupAxis(ImAxis_Y1, y1_label, y1_flags);\n    if (ImHasFlag(flags, ImPlotFlags_YAxis2))\n        SetupAxis(ImAxis_Y2, y2_label, y2_flags);\n    if (ImHasFlag(flags, ImPlotFlags_YAxis3))\n        SetupAxis(ImAxis_Y3, y3_label, y3_flags);\n    return true;\n}\n\n#endif\n\n}  // namespace ImPlot\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/implot/implot.h",
    "content": "// MIT License\n\n// Copyright (c) 2021 Evan Pezent\n\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n// ImPlot v0.13 WIP\n\n// Table of Contents:\n//\n// [SECTION] Macros and Defines\n// [SECTION] Enums and Types\n// [SECTION] Callbacks\n// [SECTION] Contexts\n// [SECTION] Begin/End Plot\n// [SECTION] Begin/End Subplot\n// [SECTION] Setup\n// [SECTION] SetNext\n// [SECTION] Plot Items\n// [SECTION] Plot Tools\n// [SECTION] Plot Utils\n// [SECTION] Legend Utils\n// [SECTION] Drag and Drop\n// [SECTION] Styling\n// [SECTION] Colormaps\n// [SECTION] Input Mapping\n// [SECTION] Miscellaneous\n// [SECTION] Demo\n// [SECTION] Obsolete API\n\n#pragma once\n#include \"imgui.h\"\n\n//-----------------------------------------------------------------------------\n// [SECTION] Macros and Defines\n//-----------------------------------------------------------------------------\n\n// Define attributes of all API symbols declarations (e.g. for DLL under Windows)\n// Using ImPlot via a shared library is not recommended, because we don't guarantee\n// backward nor forward ABI compatibility and also function call overhead. If you\n// do use ImPlot as a DLL, be sure to call SetImGuiContext (see Miscellanous section).\n#ifndef IMPLOT_API\n#define IMPLOT_API\n#endif\n\n// ImPlot version string.\n#define IMPLOT_VERSION \"0.13 WIP\"\n// Indicates variable should deduced automatically.\n#define IMPLOT_AUTO -1\n// Special color used to indicate that a color should be deduced automatically.\n#define IMPLOT_AUTO_COL ImVec4(0,0,0,-1)\n// Macro for templated plotting functions; keeps header clean.\n#define IMPLOT_TMP template <typename T> IMPLOT_API\n\n//-----------------------------------------------------------------------------\n// [SECTION] Enums and Types\n//-----------------------------------------------------------------------------\n\n// Forward declarations\nstruct ImPlotContext;             // ImPlot context (opaque struct, see implot_internal.h)\n\n// Enums/Flags\ntypedef int ImAxis;               // -> enum ImAxis_\ntypedef int ImPlotFlags;          // -> enum ImPlotFlags_\ntypedef int ImPlotAxisFlags;      // -> enum ImPlotAxisFlags_\ntypedef int ImPlotSubplotFlags;   // -> enum ImPlotSubplotFlags_\ntypedef int ImPlotLegendFlags;    // -> enum ImPlotLegendFlags_\ntypedef int ImPlotMouseTextFlags; // -> enum ImPlotMouseTextFlags_\ntypedef int ImPlotDragToolFlags;  // -> ImPlotDragToolFlags_\ntypedef int ImPlotBarGroupsFlags; // -> ImPlotBarGroupsFlags_\n\ntypedef int ImPlotCond;           // -> enum ImPlotCond_\ntypedef int ImPlotCol;            // -> enum ImPlotCol_\ntypedef int ImPlotStyleVar;       // -> enum ImPlotStyleVar_\ntypedef int ImPlotMarker;         // -> enum ImPlotMarker_\ntypedef int ImPlotColormap;       // -> enum ImPlotColormap_\ntypedef int ImPlotLocation;       // -> enum ImPlotLocation_\ntypedef int ImPlotBin;            // -> enum ImPlotBin_\n\n// Axis indices. The values assigned may change; NEVER hardcode these.\nenum ImAxis_ {\n    // horizontal axes\n    ImAxis_X1 = 0, // enabled by default\n    ImAxis_X2,     // disabled by default\n    ImAxis_X3,     // disabled by default\n    // vertical axes\n    ImAxis_Y1,     // enabled by default\n    ImAxis_Y2,     // disabled by default\n    ImAxis_Y3,     // disabled by default\n    // bookeeping\n    ImAxis_COUNT\n};\n\n// Options for plots (see BeginPlot).\nenum ImPlotFlags_ {\n    ImPlotFlags_None          = 0,       // default\n    ImPlotFlags_NoTitle       = 1 << 0,  // the plot title will not be displayed (titles are also hidden if preceeded by double hashes, e.g. \"##MyPlot\")\n    ImPlotFlags_NoLegend      = 1 << 1,  // the legend will not be displayed\n    ImPlotFlags_NoMouseText   = 1 << 2,  // the mouse position, in plot coordinates, will not be displayed inside of the plot\n    ImPlotFlags_NoInputs      = 1 << 3,  // the user will not be able to interact with the plot\n    ImPlotFlags_NoMenus       = 1 << 4,  // the user will not be able to open context menus\n    ImPlotFlags_NoBoxSelect   = 1 << 5,  // the user will not be able to box-select\n    ImPlotFlags_NoChild       = 1 << 6,  // a child window region will not be used to capture mouse scroll (can boost performance for single ImGui window applications)\n    ImPlotFlags_NoFrame       = 1 << 7,  // the ImGui frame will not be rendered\n    ImPlotFlags_Equal         = 1 << 8,  // x and y axes pairs will be constrained to have the same units/pixel\n    ImPlotFlags_Crosshairs    = 1 << 9,  // the default mouse cursor will be replaced with a crosshair when hovered\n    ImPlotFlags_AntiAliased   = 1 << 10, // plot items will be software anti-aliased (not recommended for high density plots, prefer MSAA)\n    ImPlotFlags_CanvasOnly    = ImPlotFlags_NoTitle | ImPlotFlags_NoLegend | ImPlotFlags_NoMenus | ImPlotFlags_NoBoxSelect | ImPlotFlags_NoMouseText\n};\n\n// Options for plot axes (see SetupAxis).\nenum ImPlotAxisFlags_ {\n    ImPlotAxisFlags_None          = 0,       // default\n    ImPlotAxisFlags_NoLabel       = 1 << 0,  // the axis label will not be displayed (axis labels also hidden if the supplied string name is NULL)\n    ImPlotAxisFlags_NoGridLines   = 1 << 1,  // no grid lines will be displayed\n    ImPlotAxisFlags_NoTickMarks   = 1 << 2,  // no tick marks will be displayed\n    ImPlotAxisFlags_NoTickLabels  = 1 << 3,  // no text labels will be displayed\n    ImPlotAxisFlags_NoInitialFit  = 1 << 4,  // axis will not be initially fit to data extents on the first rendered frame\n    ImPlotAxisFlags_NoMenus       = 1 << 5,  // the user will not be able to open context menus with right-click\n    ImPlotAxisFlags_Opposite      = 1 << 6,  // axis ticks and labels will be rendered on conventionally opposite side (i.e, right or top)\n    ImPlotAxisFlags_Foreground    = 1 << 7,  // grid lines will be displayed in the foreground (i.e. on top of data) in stead of the background\n    ImPlotAxisFlags_LogScale      = 1 << 8,  // a logartithmic (base 10) axis scale will be used (mutually exclusive with ImPlotAxisFlags_Time)\n    ImPlotAxisFlags_Time          = 1 << 9,  // axis will display date/time formatted labels (mutually exclusive with ImPlotAxisFlags_LogScale)\n    ImPlotAxisFlags_Invert        = 1 << 10, // the axis will be inverted\n    ImPlotAxisFlags_AutoFit       = 1 << 11, // axis will be auto-fitting to data extents\n    ImPlotAxisFlags_RangeFit      = 1 << 12, // axis will only fit points if the point is in the visible range of the **orthogonal** axis\n    ImPlotAxisFlags_LockMin       = 1 << 13, // the axis minimum value will be locked when panning/zooming\n    ImPlotAxisFlags_LockMax       = 1 << 14, // the axis maximum value will be locked when panning/zooming\n    ImPlotAxisFlags_Lock          = ImPlotAxisFlags_LockMin | ImPlotAxisFlags_LockMax,\n    ImPlotAxisFlags_NoDecorations = ImPlotAxisFlags_NoLabel | ImPlotAxisFlags_NoGridLines | ImPlotAxisFlags_NoTickMarks | ImPlotAxisFlags_NoTickLabels,\n    ImPlotAxisFlags_AuxDefault    = ImPlotAxisFlags_NoGridLines | ImPlotAxisFlags_Opposite\n};\n\n// Options for subplots (see BeginSubplot).\nenum ImPlotSubplotFlags_ {\n    ImPlotSubplotFlags_None        = 0,       // default\n    ImPlotSubplotFlags_NoTitle     = 1 << 0,  // the subplot title will not be displayed (titles are also hidden if preceeded by double hashes, e.g. \"##MySubplot\")\n    ImPlotSubplotFlags_NoLegend    = 1 << 1,  // the legend will not be displayed (only applicable if ImPlotSubplotFlags_ShareItems is enabled)\n    ImPlotSubplotFlags_NoMenus     = 1 << 2,  // the user will not be able to open context menus with right-click\n    ImPlotSubplotFlags_NoResize    = 1 << 3,  // resize splitters between subplot cells will be not be provided\n    ImPlotSubplotFlags_NoAlign     = 1 << 4,  // subplot edges will not be aligned vertically or horizontally\n    ImPlotSubplotFlags_ShareItems  = 1 << 5,  // items across all subplots will be shared and rendered into a single legend entry\n    ImPlotSubplotFlags_LinkRows    = 1 << 6,  // link the y-axis limits of all plots in each row (does not apply to auxiliary axes)\n    ImPlotSubplotFlags_LinkCols    = 1 << 7,  // link the x-axis limits of all plots in each column (does not apply to auxiliary axes)\n    ImPlotSubplotFlags_LinkAllX    = 1 << 8,  // link the x-axis limits in every plot in the subplot (does not apply to auxiliary axes)\n    ImPlotSubplotFlags_LinkAllY    = 1 << 9,  // link the y-axis limits in every plot in the subplot (does not apply to auxiliary axes)\n    ImPlotSubplotFlags_ColMajor    = 1 << 10  // subplots are added in column major order instead of the default row major order\n};\n\n// Options for legends (see SetupLegend)\nenum ImPlotLegendFlags_ {\n    ImPlotLegendFlags_None            = 0,      // default\n    ImPlotLegendFlags_NoButtons       = 1 << 0, // legend icons will not function as hide/show buttons\n    ImPlotLegendFlags_NoHighlightItem = 1 << 1, // plot items will not be highlighted when their legend entry is hovered\n    ImPlotLegendFlags_NoHighlightAxis = 1 << 2, // axes will not be highlighted when legend entries are hovered (only relevant if x/y-axis count > 1)\n    ImPlotLegendFlags_NoMenus         = 1 << 3, // the user will not be able to open context menus with right-click\n    ImPlotLegendFlags_Outside         = 1 << 4, // legend will be rendered outside of the plot area\n    ImPlotLegendFlags_Horizontal      = 1 << 5, // legend entries will be displayed horizontally\n};\n\n// Options for mouse hover text (see SetupMouseText)\nenum ImPlotMouseTextFlags_ {\n    ImPlotMouseTextFlags_None        = 0,      // default\n    ImPlotMouseTextFlags_NoAuxAxes   = 1 << 0, // only show the mouse position for primary axes\n    ImPlotMouseTextFlags_NoFormat    = 1 << 1, // axes label formatters won't be used to render text\n    ImPlotMouseTextFlags_ShowAlways  = 1 << 2, // always display mouse position even if plot not hovered\n};\n\n// Options for DragPoint, DragLine, DragRect\nenum ImPlotDragToolFlags_ {\n    ImPlotDragToolFlags_None      = 0,      // default\n    ImPlotDragToolFlags_NoCursors = 1 << 0, // drag tools won't change cursor icons when hovered or held\n    ImPlotDragToolFlags_NoFit     = 1 << 1, // the drag tool won't be considered for plot fits\n    ImPlotDragToolFlags_NoInputs  = 1 << 2, // lock the tool from user inputs\n    ImPlotDragToolFlags_Delayed   = 1 << 3, // tool rendering will be delayed one frame; useful when applying position-constraints\n};\n\n// Flags for ImPlot::PlotBarGroups\nenum ImPlotBarGroupsFlags_ {\n    ImPlotBarGroupsFlags_None     = 0,      // default\n    ImPlotBarGroupsFlags_Stacked  = 1 << 0, // items in a group will be stacked on top of each other\n};\n\n// Represents a condition for SetupAxisLimits etc. (same as ImGuiCond, but we only support a subset of those enums)\nenum ImPlotCond_\n{\n    ImPlotCond_None   = ImGuiCond_None,    // No condition (always set the variable), same as _Always\n    ImPlotCond_Always = ImGuiCond_Always,  // No condition (always set the variable)\n    ImPlotCond_Once   = ImGuiCond_Once,    // Set the variable once per runtime session (only the first call will succeed)\n};\n\n// Plot styling colors.\nenum ImPlotCol_ {\n    // item styling colors\n    ImPlotCol_Line,          // plot line/outline color (defaults to next unused color in current colormap)\n    ImPlotCol_Fill,          // plot fill color for bars (defaults to the current line color)\n    ImPlotCol_MarkerOutline, // marker outline color (defaults to the current line color)\n    ImPlotCol_MarkerFill,    // marker fill color (defaults to the current line color)\n    ImPlotCol_ErrorBar,      // error bar color (defaults to ImGuiCol_Text)\n    // plot styling colors\n    ImPlotCol_FrameBg,       // plot frame background color (defaults to ImGuiCol_FrameBg)\n    ImPlotCol_PlotBg,        // plot area background color (defaults to ImGuiCol_WindowBg)\n    ImPlotCol_PlotBorder,    // plot area border color (defaults to ImGuiCol_Border)\n    ImPlotCol_LegendBg,      // legend background color (defaults to ImGuiCol_PopupBg)\n    ImPlotCol_LegendBorder,  // legend border color (defaults to ImPlotCol_PlotBorder)\n    ImPlotCol_LegendText,    // legend text color (defaults to ImPlotCol_InlayText)\n    ImPlotCol_TitleText,     // plot title text color (defaults to ImGuiCol_Text)\n    ImPlotCol_InlayText,     // color of text appearing inside of plots (defaults to ImGuiCol_Text)\n    ImPlotCol_AxisText,      // axis label and tick lables color (defaults to ImGuiCol_Text)\n    ImPlotCol_AxisGrid,      // axis grid color (defaults to 25% ImPlotCol_AxisText)\n    ImPlotCol_AxisTick,      // axis tick color (defaults to AxisGrid)\n    ImPlotCol_AxisBg,        // background color of axis hover region (defaults to transparent)\n    ImPlotCol_AxisBgHovered, // axis hover color (defaults to ImGuiCol_ButtonHovered)\n    ImPlotCol_AxisBgActive,  // axis active color (defaults to ImGuiCol_ButtonActive)\n    ImPlotCol_Selection,     // box-selection color (defaults to yellow)\n    ImPlotCol_Crosshairs,    // crosshairs color (defaults to ImPlotCol_PlotBorder)\n    ImPlotCol_COUNT\n};\n\n// Plot styling variables.\nenum ImPlotStyleVar_ {\n    // item styling variables\n    ImPlotStyleVar_LineWeight,         // float,  plot item line weight in pixels\n    ImPlotStyleVar_Marker,             // int,    marker specification\n    ImPlotStyleVar_MarkerSize,         // float,  marker size in pixels (roughly the marker's \"radius\")\n    ImPlotStyleVar_MarkerWeight,       // float,  plot outline weight of markers in pixels\n    ImPlotStyleVar_FillAlpha,          // float,  alpha modifier applied to all plot item fills\n    ImPlotStyleVar_ErrorBarSize,       // float,  error bar whisker width in pixels\n    ImPlotStyleVar_ErrorBarWeight,     // float,  error bar whisker weight in pixels\n    ImPlotStyleVar_DigitalBitHeight,   // float,  digital channels bit height (at 1) in pixels\n    ImPlotStyleVar_DigitalBitGap,      // float,  digital channels bit padding gap in pixels\n    // plot styling variables\n    ImPlotStyleVar_PlotBorderSize,     // float,  thickness of border around plot area\n    ImPlotStyleVar_MinorAlpha,         // float,  alpha multiplier applied to minor axis grid lines\n    ImPlotStyleVar_MajorTickLen,       // ImVec2, major tick lengths for X and Y axes\n    ImPlotStyleVar_MinorTickLen,       // ImVec2, minor tick lengths for X and Y axes\n    ImPlotStyleVar_MajorTickSize,      // ImVec2, line thickness of major ticks\n    ImPlotStyleVar_MinorTickSize,      // ImVec2, line thickness of minor ticks\n    ImPlotStyleVar_MajorGridSize,      // ImVec2, line thickness of major grid lines\n    ImPlotStyleVar_MinorGridSize,      // ImVec2, line thickness of minor grid lines\n    ImPlotStyleVar_PlotPadding,        // ImVec2, padding between widget frame and plot area, labels, or outside legends (i.e. main padding)\n    ImPlotStyleVar_LabelPadding,       // ImVec2, padding between axes labels, tick labels, and plot edge\n    ImPlotStyleVar_LegendPadding,      // ImVec2, legend padding from plot edges\n    ImPlotStyleVar_LegendInnerPadding, // ImVec2, legend inner padding from legend edges\n    ImPlotStyleVar_LegendSpacing,      // ImVec2, spacing between legend entries\n    ImPlotStyleVar_MousePosPadding,    // ImVec2, padding between plot edge and interior info text\n    ImPlotStyleVar_AnnotationPadding,  // ImVec2, text padding around annotation labels\n    ImPlotStyleVar_FitPadding,         // ImVec2, additional fit padding as a percentage of the fit extents (e.g. ImVec2(0.1f,0.1f) adds 10% to the fit extents of X and Y)\n    ImPlotStyleVar_PlotDefaultSize,    // ImVec2, default size used when ImVec2(0,0) is passed to BeginPlot\n    ImPlotStyleVar_PlotMinSize,        // ImVec2, minimum size plot frame can be when shrunk\n    ImPlotStyleVar_COUNT\n};\n\n// Marker specifications.\nenum ImPlotMarker_ {\n    ImPlotMarker_None = -1, // no marker\n    ImPlotMarker_Circle,    // a circle marker\n    ImPlotMarker_Square,    // a square maker\n    ImPlotMarker_Diamond,   // a diamond marker\n    ImPlotMarker_Up,        // an upward-pointing triangle marker\n    ImPlotMarker_Down,      // an downward-pointing triangle marker\n    ImPlotMarker_Left,      // an leftward-pointing triangle marker\n    ImPlotMarker_Right,     // an rightward-pointing triangle marker\n    ImPlotMarker_Cross,     // a cross marker (not fillable)\n    ImPlotMarker_Plus,      // a plus marker (not fillable)\n    ImPlotMarker_Asterisk,  // a asterisk marker (not fillable)\n    ImPlotMarker_COUNT\n};\n\n// Built-in colormaps\nenum ImPlotColormap_ {\n    ImPlotColormap_Deep     = 0,   // a.k.a. seaborn deep             (qual=true,  n=10) (default)\n    ImPlotColormap_Dark     = 1,   // a.k.a. matplotlib \"Set1\"        (qual=true,  n=9 )\n    ImPlotColormap_Pastel   = 2,   // a.k.a. matplotlib \"Pastel1\"     (qual=true,  n=9 )\n    ImPlotColormap_Paired   = 3,   // a.k.a. matplotlib \"Paired\"      (qual=true,  n=12)\n    ImPlotColormap_Viridis  = 4,   // a.k.a. matplotlib \"viridis\"     (qual=false, n=11)\n    ImPlotColormap_Plasma   = 5,   // a.k.a. matplotlib \"plasma\"      (qual=false, n=11)\n    ImPlotColormap_Hot      = 6,   // a.k.a. matplotlib/MATLAB \"hot\"  (qual=false, n=11)\n    ImPlotColormap_Cool     = 7,   // a.k.a. matplotlib/MATLAB \"cool\" (qual=false, n=11)\n    ImPlotColormap_Pink     = 8,   // a.k.a. matplotlib/MATLAB \"pink\" (qual=false, n=11)\n    ImPlotColormap_Jet      = 9,   // a.k.a. MATLAB \"jet\"             (qual=false, n=11)\n    ImPlotColormap_Twilight = 10,  // a.k.a. matplotlib \"twilight\"    (qual=false, n=11)\n    ImPlotColormap_RdBu     = 11,  // red/blue, Color Brewer          (qual=false, n=11)\n    ImPlotColormap_BrBG     = 12,  // brown/blue-green, Color Brewer  (qual=false, n=11)\n    ImPlotColormap_PiYG     = 13,  // pink/yellow-green, Color Brewer (qual=false, n=11)\n    ImPlotColormap_Spectral = 14,  // color spectrum, Color Brewer    (qual=false, n=11)\n    ImPlotColormap_Greys    = 15,  // white/black                     (qual=false, n=2 )\n};\n\n// Used to position items on a plot (e.g. legends, labels, etc.)\nenum ImPlotLocation_ {\n    ImPlotLocation_Center    = 0,                                          // center-center\n    ImPlotLocation_North     = 1 << 0,                                     // top-center\n    ImPlotLocation_South     = 1 << 1,                                     // bottom-center\n    ImPlotLocation_West      = 1 << 2,                                     // center-left\n    ImPlotLocation_East      = 1 << 3,                                     // center-right\n    ImPlotLocation_NorthWest = ImPlotLocation_North | ImPlotLocation_West, // top-left\n    ImPlotLocation_NorthEast = ImPlotLocation_North | ImPlotLocation_East, // top-right\n    ImPlotLocation_SouthWest = ImPlotLocation_South | ImPlotLocation_West, // bottom-left\n    ImPlotLocation_SouthEast = ImPlotLocation_South | ImPlotLocation_East  // bottom-right\n};\n\n// Enums for different automatic histogram binning methods (k = bin count or w = bin width)\nenum ImPlotBin_ {\n    ImPlotBin_Sqrt    = -1, // k = sqrt(n)\n    ImPlotBin_Sturges = -2, // k = 1 + log2(n)\n    ImPlotBin_Rice    = -3, // k = 2 * cbrt(n)\n    ImPlotBin_Scott   = -4, // w = 3.49 * sigma / cbrt(n)\n};\n\n// Double precision version of ImVec2 used by ImPlot. Extensible by end users.\nstruct ImPlotPoint {\n    double x, y;\n    ImPlotPoint()                         { x = y = 0.0;      }\n    ImPlotPoint(double _x, double _y)     { x = _x; y = _y;   }\n    ImPlotPoint(const ImVec2& p)          { x = p.x; y = p.y; }\n    double  operator[] (size_t idx) const { return (&x)[idx]; }\n    double& operator[] (size_t idx)       { return (&x)[idx]; }\n#ifdef IMPLOT_POINT_CLASS_EXTRA\n    IMPLOT_POINT_CLASS_EXTRA     // Define additional constructors and implicit cast operators in imconfig.h\n                                 // to convert back and forth between your math types and ImPlotPoint.\n#endif\n};\n\n// Range defined by a min/max value.\nstruct ImPlotRange {\n    double Min, Max;\n    ImPlotRange()                         { Min = 0; Max = 0;                                         }\n    ImPlotRange(double _min, double _max) { Min = _min; Max = _max;                                   }\n    bool Contains(double value) const     { return value >= Min && value <= Max;                      }\n    double Size() const                   { return Max - Min;                                         }\n    double Clamp(double value) const      { return (value < Min) ? Min : (value > Max) ? Max : value; }\n};\n\n// Combination of two range limits for X and Y axes. Also an AABB defined by Min()/Max().\nstruct ImPlotRect {\n    ImPlotRange X, Y;\n    ImPlotRect()                                                       {                                                               }\n    ImPlotRect(double x_min, double x_max, double y_min, double y_max) { X.Min = x_min; X.Max = x_max; Y.Min = y_min; Y.Max = y_max;   }\n    bool Contains(const ImPlotPoint& p) const                          { return Contains(p.x, p.y);                                    }\n    bool Contains(double x, double y) const                            { return X.Contains(x) && Y.Contains(y);                        }\n    ImPlotPoint Size() const                                           { return ImPlotPoint(X.Size(), Y.Size());                       }\n    ImPlotPoint Clamp(const ImPlotPoint& p)                            { return Clamp(p.x, p.y);                                       }\n    ImPlotPoint Clamp(double x, double y)                              { return ImPlotPoint(X.Clamp(x),Y.Clamp(y));                    }\n    ImPlotPoint Min() const                                            { return ImPlotPoint(X.Min, Y.Min);                             }\n    ImPlotPoint Max() const                                            { return ImPlotPoint(X.Max, Y.Max);                             }\n};\n\n// Plot style structure\nstruct ImPlotStyle {\n    // item styling variables\n    float   LineWeight;              // = 1,      item line weight in pixels\n    int     Marker;                  // = ImPlotMarker_None, marker specification\n    float   MarkerSize;              // = 4,      marker size in pixels (roughly the marker's \"radius\")\n    float   MarkerWeight;            // = 1,      outline weight of markers in pixels\n    float   FillAlpha;               // = 1,      alpha modifier applied to plot fills\n    float   ErrorBarSize;            // = 5,      error bar whisker width in pixels\n    float   ErrorBarWeight;          // = 1.5,    error bar whisker weight in pixels\n    float   DigitalBitHeight;        // = 8,      digital channels bit height (at y = 1.0f) in pixels\n    float   DigitalBitGap;           // = 4,      digital channels bit padding gap in pixels\n    // plot styling variables\n    float   PlotBorderSize;          // = 1,      line thickness of border around plot area\n    float   MinorAlpha;              // = 0.25    alpha multiplier applied to minor axis grid lines\n    ImVec2  MajorTickLen;            // = 10,10   major tick lengths for X and Y axes\n    ImVec2  MinorTickLen;            // = 5,5     minor tick lengths for X and Y axes\n    ImVec2  MajorTickSize;           // = 1,1     line thickness of major ticks\n    ImVec2  MinorTickSize;           // = 1,1     line thickness of minor ticks\n    ImVec2  MajorGridSize;           // = 1,1     line thickness of major grid lines\n    ImVec2  MinorGridSize;           // = 1,1     line thickness of minor grid lines\n    ImVec2  PlotPadding;             // = 10,10   padding between widget frame and plot area, labels, or outside legends (i.e. main padding)\n    ImVec2  LabelPadding;            // = 5,5     padding between axes labels, tick labels, and plot edge\n    ImVec2  LegendPadding;           // = 10,10   legend padding from plot edges\n    ImVec2  LegendInnerPadding;      // = 5,5     legend inner padding from legend edges\n    ImVec2  LegendSpacing;           // = 5,0     spacing between legend entries\n    ImVec2  MousePosPadding;         // = 10,10   padding between plot edge and interior mouse location text\n    ImVec2  AnnotationPadding;       // = 2,2     text padding around annotation labels\n    ImVec2  FitPadding;              // = 0,0     additional fit padding as a percentage of the fit extents (e.g. ImVec2(0.1f,0.1f) adds 10% to the fit extents of X and Y)\n    ImVec2  PlotDefaultSize;         // = 400,300 default size used when ImVec2(0,0) is passed to BeginPlot\n    ImVec2  PlotMinSize;             // = 200,150 minimum size plot frame can be when shrunk\n    // style colors\n    ImVec4  Colors[ImPlotCol_COUNT]; // Array of styling colors. Indexable with ImPlotCol_ enums.\n    // colormap\n    ImPlotColormap Colormap;         // The current colormap. Set this to either an ImPlotColormap_ enum or an index returned by AddColormap.\n    // settings/flags\n    bool    AntiAliasedLines;        // = false,  enable global anti-aliasing on plot lines (overrides ImPlotFlags_AntiAliased)\n    bool    UseLocalTime;            // = false,  axis labels will be formatted for your timezone when ImPlotAxisFlag_Time is enabled\n    bool    UseISO8601;              // = false,  dates will be formatted according to ISO 8601 where applicable (e.g. YYYY-MM-DD, YYYY-MM, --MM-DD, etc.)\n    bool    Use24HourClock;          // = false,  times will be formatted using a 24 hour clock\n    IMPLOT_API ImPlotStyle();\n};\n\n// Input mapping structure. Default values listed. See also MapInputDefault, MapInputReverse.\nstruct ImPlotInputMap {\n    ImGuiMouseButton Pan;           // LMB    enables panning when held,\n    ImGuiKeyModFlags PanMod;        // none   optional modifier that must be held for panning/fitting\n    ImGuiMouseButton Fit;           // LMB    initiates fit when double clicked\n    ImGuiMouseButton Select;        // RMB    begins box selection when pressed and confirms selection when released\n    ImGuiMouseButton SelectCancel;  // LMB    cancels active box selection when pressed; cannot be same as Select\n    ImGuiKeyModFlags SelectMod;     // none   optional modifier that must be held for box selection\n    ImGuiKeyModFlags SelectHorzMod; // Alt    expands active box selection horizontally to plot edge when held\n    ImGuiKeyModFlags SelectVertMod; // Shift  expands active box selection vertically to plot edge when held\n    ImGuiMouseButton Menu;          // RMB    opens context menus (if enabled) when clicked\n    ImGuiKeyModFlags OverrideMod;   // Ctrl   when held, all input is ignored; used to enable axis/plots as DND sources\n    ImGuiKeyModFlags ZoomMod;       // none   optional modifier that must be held for scroll wheel zooming\n    float            ZoomRate;      // 0.1f   zoom rate for scroll (e.g. 0.1f = 10% plot range every scroll click); make negative to invert\n    IMPLOT_API ImPlotInputMap();\n};\n\n//-----------------------------------------------------------------------------\n// [SECTION] Callbacks\n//-----------------------------------------------------------------------------\n\n// Callback signature for axis tick label formatter.\ntypedef void (*ImPlotFormatter)(double value, char* buff, int size, void* user_data);\n\n// Callback signature for data getter.\ntypedef ImPlotPoint (*ImPlotGetter)(void* user_data, int idx);\n\nnamespace ImPlot {\n\n//-----------------------------------------------------------------------------\n// [SECTION] Contexts\n//-----------------------------------------------------------------------------\n\n// Creates a new ImPlot context. Call this after ImGui::CreateContext.\nIMPLOT_API ImPlotContext* CreateContext();\n// Destroys an ImPlot context. Call this before ImGui::DestroyContext. NULL = destroy current context.\nIMPLOT_API void DestroyContext(ImPlotContext* ctx = NULL);\n// Returns the current ImPlot context. NULL if no context has ben set.\nIMPLOT_API ImPlotContext* GetCurrentContext();\n// Sets the current ImPlot context.\nIMPLOT_API void SetCurrentContext(ImPlotContext* ctx);\n\n// Sets the current **ImGui** context. This is ONLY necessary if you are compiling\n// ImPlot as a DLL (not recommended) separate from your ImGui compilation. It\n// sets the global variable GImGui, which is not shared across DLL boundaries.\n// See GImGui documentation in imgui.cpp for more details.\nIMPLOT_API void SetImGuiContext(ImGuiContext* ctx);\n\n//-----------------------------------------------------------------------------\n// [SECTION] Begin/End Plot\n//-----------------------------------------------------------------------------\n\n// Starts a 2D plotting context. If this function returns true, EndPlot() MUST\n// be called! You are encouraged to use the following convention:\n//\n// if (BeginPlot(...)) {\n//     PlotLine(...);\n//     ...\n//     EndPlot();\n// }\n//\n// Important notes:\n//\n// - #title_id must be unique to the current ImGui ID scope. If you need to avoid ID\n//   collisions or don't want to display a title in the plot, use double hashes\n//   (e.g. \"MyPlot##HiddenIdText\" or \"##NoTitle\").\n// - #size is the **frame** size of the plot widget, not the plot area. The default\n//   size of plots (i.e. when ImVec2(0,0)) can be modified in your ImPlotStyle.\nIMPLOT_API bool BeginPlot(const char* title_id, const ImVec2& size = ImVec2(-1,0), ImPlotFlags flags = ImPlotFlags_None);\n\n// Only call EndPlot() if BeginPlot() returns true! Typically called at the end\n// of an if statement conditioned on BeginPlot(). See example above.\nIMPLOT_API void EndPlot();\n\n//-----------------------------------------------------------------------------\n// [SECTION] Begin/End Subplots\n//-----------------------------------------------------------------------------\n\n// Starts a subdivided plotting context. If the function returns true,\n// EndSubplots() MUST be called! Call BeginPlot/EndPlot AT MOST [rows*cols]\n// times in  between the begining and end of the subplot context. Plots are\n// added in row major order.\n//\n// Example:\n//\n// if (BeginSubplots(\"My Subplot\",2,3,ImVec2(800,400)) {\n//     for (int i = 0; i < 6; ++i) {\n//         if (BeginPlot(...)) {\n//             ImPlot::PlotLine(...);\n//             ...\n//             EndPlot();\n//         }\n//     }\n//     EndSubplots();\n// }\n//\n// Produces:\n//\n// [0] | [1] | [2]\n// ----|-----|----\n// [3] | [4] | [5]\n//\n// Important notes:\n//\n// - #title_id must be unique to the current ImGui ID scope. If you need to avoid ID\n//   collisions or don't want to display a title in the plot, use double hashes\n//   (e.g. \"MySubplot##HiddenIdText\" or \"##NoTitle\").\n// - #rows and #cols must be greater than 0.\n// - #size is the size of the entire grid of subplots, not the individual plots\n// - #row_ratios and #col_ratios must have AT LEAST #rows and #cols elements,\n//   respectively. These are the sizes of the rows and columns expressed in ratios.\n//   If the user adjusts the dimensions, the arrays are updated with new ratios.\n//\n// Important notes regarding BeginPlot from inside of BeginSubplots:\n//\n// - The #title_id parameter of _BeginPlot_ (see above) does NOT have to be\n//   unique when called inside of a subplot context. Subplot IDs are hashed\n//   for your convenience so you don't have call PushID or generate unique title\n//   strings. Simply pass an empty string to BeginPlot unless you want to title\n//   each subplot.\n// - The #size parameter of _BeginPlot_ (see above) is ignored when inside of a\n//   subplot context. The actual size of the subplot will be based on the\n//   #size value you pass to _BeginSubplots_ and #row/#col_ratios if provided.\n\nIMPLOT_API bool BeginSubplots(const char* title_id,\n                             int rows,\n                             int cols,\n                             const ImVec2& size,\n                             ImPlotSubplotFlags flags = ImPlotSubplotFlags_None,\n                             float* row_ratios        = NULL,\n                             float* col_ratios        = NULL);\n\n// Only call EndSubplots() if BeginSubplots() returns true! Typically called at the end\n// of an if statement conditioned on BeginSublots(). See example above.\nIMPLOT_API void EndSubplots();\n\n//-----------------------------------------------------------------------------\n// [SECTION] Setup\n//-----------------------------------------------------------------------------\n\n// The following API allows you to setup and customize various aspects of the\n// current plot. The functions should be called immediately after BeginPlot\n// and before any other API calls. Typical usage is as follows:\n\n// if (BeginPlot(...)) {                     1) begin a new plot\n//     SetupAxis(ImAxis_X1, \"My X-Axis\");    2) make Setup calls\n//     SetupAxis(ImAxis_Y1, \"My Y-Axis\");\n//     SetupLegend(ImPlotLocation_North);\n//     ...\n//     SetupFinish();                        3) [optional] explicitly finish setup\n//     PlotLine(...);                        4) plot items\n//     ...\n//     EndPlot();                            5) end the plot\n// }\n//\n// Important notes:\n//\n// - Always call Setup code at the top of your BeginPlot conditional statement.\n// - Setup is locked once you start plotting or explicitly call SetupFinish.\n//   Do NOT call Setup code after you begin plotting or after you make\n//   any non-Setup API calls (e.g. utils like PlotToPixels also lock Setup)\n// - Calling SetupFinish is OPTIONAL, but probably good practice. If you do not\n//   call it yourself, then the first subsequent plotting or utility function will\n//   call it for you.\n\n// Enables an axis or sets the label and/or flags for an existing axis. Leave #label = NULL for no label.\nIMPLOT_API void SetupAxis(ImAxis axis, const char* label = NULL, ImPlotAxisFlags flags = ImPlotAxisFlags_None);\n// Sets an axis range limits. If ImPlotCond_Always is used, the axes limits will be locked.\nIMPLOT_API void SetupAxisLimits(ImAxis axis, double v_min, double v_max, ImPlotCond cond = ImPlotCond_Once);\n// Links an axis range limits to external values. Set to NULL for no linkage. The pointer data must remain valid until EndPlot.\nIMPLOT_API void SetupAxisLinks(ImAxis axis, double* link_min, double* link_max);\n// Sets the format of numeric axis labels via formater specifier (default=\"%g\"). Formated values will be double (i.e. use %f).\nIMPLOT_API void SetupAxisFormat(ImAxis axis, const char* fmt);\n// Sets the format of numeric axis labels via formatter callback. Given #value, write a label into #buff. Optionally pass user data.\nIMPLOT_API void SetupAxisFormat(ImAxis axis, ImPlotFormatter formatter, void* data = NULL);\n// Sets an axis' ticks and optionally the labels. To keep the default ticks, set #keep_default=true.\nIMPLOT_API void SetupAxisTicks(ImAxis axis, const double* values, int n_ticks, const char* const labels[] = NULL, bool keep_default = false);\n// Sets an axis' ticks and optionally the labels for the next plot. To keep the default ticks, set #keep_default=true.\nIMPLOT_API void SetupAxisTicks(ImAxis axis, double v_min, double v_max, int n_ticks, const char* const labels[] = NULL, bool keep_default = false);\n\n// Sets the label and/or flags for primary X and Y axes (shorthand for two calls to SetupAxis).\nIMPLOT_API void SetupAxes(const char* x_label, const char* y_label, ImPlotAxisFlags x_flags = ImPlotAxisFlags_None, ImPlotAxisFlags y_flags = ImPlotAxisFlags_None);\n// Sets the primary X and Y axes range limits. If ImPlotCond_Always is used, the axes limits will be locked (shorthand for two calls to SetupAxisLimits).\nIMPLOT_API void SetupAxesLimits(double x_min, double x_max, double y_min, double y_max, ImPlotCond cond = ImPlotCond_Once);\n\n// Sets up the plot legend.\nIMPLOT_API void SetupLegend(ImPlotLocation location, ImPlotLegendFlags flags = ImPlotLegendFlags_None);\n// Set the location of the current plot's mouse position text (default = South|East).\nIMPLOT_API void SetupMouseText(ImPlotLocation location, ImPlotMouseTextFlags flags = ImPlotMouseTextFlags_None);\n\n// Explicitly finalize plot setup. Once you call this, you cannot make anymore Setup calls for the current plot!\n// Note that calling this function is OPTIONAL; it will be called by the first subsequent setup-locking API call.\nIMPLOT_API void SetupFinish();\n\n//-----------------------------------------------------------------------------\n// [SECTION] SetNext\n//-----------------------------------------------------------------------------\n\n// Though you should default to the `Setup` API above, there are some scenarios\n// where (re)configuring a plot or axis before `BeginPlot` is needed (e.g. if\n// using a preceding button or slider widget to change the plot limits). In\n// this case, you can use the `SetNext` API below. While this is not as feature\n// rich as the Setup API, most common needs are provided. These functions can be\n// called anwhere except for inside of `Begin/EndPlot`. For example:\n\n// if (ImGui::Button(\"Center Plot\"))\n//     ImPlot::SetNextPlotLimits(-1,1,-1,1);\n// if (ImPlot::BeginPlot(...)) {\n//     ...\n//     ImPlot::EndPlot();\n// }\n//\n// Important notes:\n//\n// - You must still enable non-default axes with SetupAxis for these functions\n//   to work properly.\n\n// Sets an upcoming axis range limits. If ImPlotCond_Always is used, the axes limits will be locked.\nIMPLOT_API void SetNextAxisLimits(ImAxis axis, double v_min, double v_max, ImPlotCond cond = ImPlotCond_Once);\n// Links an upcoming axis range limits to external values. Set to NULL for no linkage. The pointer data must remain valid until EndPlot!\nIMPLOT_API void SetNextAxisLinks(ImAxis axis, double* link_min, double* link_max);\n// Set an upcoming axis to auto fit to its data.\nIMPLOT_API void SetNextAxisToFit(ImAxis axis);\n\n// Sets the upcoming primary X and Y axes range limits. If ImPlotCond_Always is used, the axes limits will be locked (shorthand for two calls to SetupAxisLimits).\nIMPLOT_API void SetNextAxesLimits(double x_min, double x_max, double y_min, double y_max, ImPlotCond cond = ImPlotCond_Once);\n// Sets all upcoming axes to auto fit to their data.\nIMPLOT_API void SetNextAxesToFit();\n\n//-----------------------------------------------------------------------------\n// [SECTION] Plot Items\n//-----------------------------------------------------------------------------\n\n// The main plotting API is provied below. Call these functions between\n// Begin/EndPlot and after any Setup API calls. Each plots data on the current\n// x and y axes, which can be changed with `SetAxis/Axes`.\n//\n// The templated functions are explicitly instantiated in implot_items.cpp.\n// They are not intended to be used generically with custom types. You will get\n// a linker error if you try! All functions support the following scalar types:\n//\n// float, double, ImS8, ImU8, ImS16, ImU16, ImS32, ImU32, ImS64, ImU64\n//\n//\n// If you need to plot custom or non-homogenous data you have a few options:\n//\n// 1. If your data is a simple struct/class (e.g. Vector2f), you can use striding.\n//    This is the most performant option if applicable.\n//\n//    struct Vector2f { float X, Y; };\n//    ...\n//    Vector2f data[42];\n//    ImPlot::PlotLine(\"line\", &data[0].x, &data[0].y, 42, 0, sizeof(Vector2f)); // or sizeof(float)*2\n//\n// 2. Write a custom getter C function or C++ lambda and pass it and optionally your data to\n//    an ImPlot function post-fixed with a G (e.g. PlotScatterG). This has a slight performance\n//    cost, but probably not enough to worry about unless your data is very large. Examples:\n//\n//    ImPlotPoint MyDataGetter(void* data, int idx) {\n//        MyData* my_data = (MyData*)data;\n//        ImPlotPoint p;\n//        p.x = my_data->GetTime(idx);\n//        p.y = my_data->GetValue(idx);\n//        return p\n//    }\n//    ...\n//    auto my_lambda = [](void*, int idx) {\n//        double t = idx / 999.0;\n//        return ImPlotPoint(t, 0.5+0.5*std::sin(2*PI*10*t));\n//    };\n//    ...\n//    if (ImPlot::BeginPlot(\"MyPlot\")) {\n//        MyData my_data;\n//        ImPlot::PlotScatterG(\"scatter\", MyDataGetter, &my_data, my_data.Size());\n//        ImPlot::PlotLineG(\"line\", my_lambda, nullptr, 1000);\n//        ImPlot::EndPlot();\n//    }\n//\n// NB: All types are converted to double before plotting. You may lose information\n// if you try plotting extremely large 64-bit integral types. Proceed with caution!\n\n// Plots a standard 2D line plot.\nIMPLOT_TMP void PlotLine(const char* label_id, const T* values, int count, double xscale=1, double x0=0, int offset=0, int stride=sizeof(T));\nIMPLOT_TMP void PlotLine(const char* label_id, const T* xs, const T* ys, int count, int offset=0, int stride=sizeof(T));\nIMPLOT_API void PlotLineG(const char* label_id, ImPlotGetter getter, void* data, int count);\n\n// Plots a standard 2D scatter plot. Default marker is ImPlotMarker_Circle.\nIMPLOT_TMP void PlotScatter(const char* label_id, const T* values, int count, double xscale=1, double x0=0, int offset=0, int stride=sizeof(T));\nIMPLOT_TMP void PlotScatter(const char* label_id, const T* xs, const T* ys, int count, int offset=0, int stride=sizeof(T));\nIMPLOT_API void PlotScatterG(const char* label_id, ImPlotGetter getter, void* data, int count);\n\n// Plots a a stairstep graph. The y value is continued constantly from every x position, i.e. the interval [x[i], x[i+1]) has the value y[i].\nIMPLOT_TMP void PlotStairs(const char* label_id, const T* values, int count, double xscale=1, double x0=0, int offset=0, int stride=sizeof(T));\nIMPLOT_TMP void PlotStairs(const char* label_id, const T* xs, const T* ys, int count, int offset=0, int stride=sizeof(T));\nIMPLOT_API void PlotStairsG(const char* label_id, ImPlotGetter getter, void* data, int count);\n\n// Plots a shaded (filled) region between two lines, or a line and a horizontal reference. Set yref to +/-INFINITY for infinite fill extents.\nIMPLOT_TMP void PlotShaded(const char* label_id, const T* values, int count, double yref=0, double xscale=1, double x0=0, int offset=0, int stride=sizeof(T));\nIMPLOT_TMP void PlotShaded(const char* label_id, const T* xs, const T* ys, int count, double yref=0, int offset=0, int stride=sizeof(T));\nIMPLOT_TMP void PlotShaded(const char* label_id, const T* xs, const T* ys1, const T* ys2, int count, int offset=0, int stride=sizeof(T));\nIMPLOT_API void PlotShadedG(const char* label_id, ImPlotGetter getter1, void* data1, ImPlotGetter getter2, void* data2, int count);\n\n// Plots a vertical bar graph. #bar_width and #x0 are in X units.\nIMPLOT_TMP void PlotBars(const char* label_id, const T* values, int count, double bar_width=0.67, double x0=0, int offset=0, int stride=sizeof(T));\nIMPLOT_TMP void PlotBars(const char* label_id, const T* xs, const T* ys, int count, double bar_width, int offset=0, int stride=sizeof(T));\nIMPLOT_API void PlotBarsG(const char* label_id, ImPlotGetter getter, void* data, int count, double bar_width);\n\n// Plots a horizontal bar graph. #bar_height and #y0 are in Y units.\nIMPLOT_TMP void PlotBarsH(const char* label_id, const T* values, int count, double bar_height=0.67, double y0=0, int offset=0, int stride=sizeof(T));\nIMPLOT_TMP void PlotBarsH(const char* label_id, const T* xs, const T* ys, int count, double bar_height, int offset=0, int stride=sizeof(T));\nIMPLOT_API void PlotBarsHG(const char* label_id, ImPlotGetter getter, void* data, int count, double bar_height);\n\n// Plots a group of vertical bars. #values is a row-major matrix with #item_count rows and #group_count cols. #label_ids should have #item_count elements.\nIMPLOT_TMP void PlotBarGroups(const char* const label_ids[], const T* values, int item_count, int group_count, double group_width=0.67, double x0=0, ImPlotBarGroupsFlags flags=ImPlotBarGroupsFlags_None);\n\n// Plots a group of horizontal bars. #values is a row-major matrix with #item_count rows and #group_count cols. #label_ids should have #item_count elements.\nIMPLOT_TMP void PlotBarGroupsH(const char* const label_ids[], const T* values, int item_count, int group_count, double group_height=0.67, double y0=0, ImPlotBarGroupsFlags flags=ImPlotBarGroupsFlags_None);\n\n// Plots vertical error bar. The label_id should be the same as the label_id of the associated line or bar plot.\nIMPLOT_TMP void PlotErrorBars(const char* label_id, const T* xs, const T* ys, const T* err, int count, int offset=0, int stride=sizeof(T));\nIMPLOT_TMP void PlotErrorBars(const char* label_id, const T* xs, const T* ys, const T* neg, const T* pos, int count, int offset=0, int stride=sizeof(T));\n\n// Plots horizontal error bars. The label_id should be the same as the label_id of the associated line or bar plot.\nIMPLOT_TMP void PlotErrorBarsH(const char* label_id, const T* xs, const T* ys, const T* err, int count, int offset=0, int stride=sizeof(T));\nIMPLOT_TMP void PlotErrorBarsH(const char* label_id, const T* xs, const T* ys, const T* neg, const T* pos, int count, int offset=0, int stride=sizeof(T));\n\n/// Plots vertical stems.\nIMPLOT_TMP void PlotStems(const char* label_id, const T* values, int count, double yref=0, double xscale=1, double x0=0, int offset=0, int stride=sizeof(T));\nIMPLOT_TMP void PlotStems(const char* label_id, const T* xs, const T* ys, int count, double yref=0, int offset=0, int stride=sizeof(T));\n\n/// Plots infinite vertical or horizontal lines (e.g. for references or asymptotes).\nIMPLOT_TMP void PlotVLines(const char* label_id, const T* xs, int count, int offset=0, int stride=sizeof(T));\nIMPLOT_TMP void PlotHLines(const char* label_id, const T* ys, int count, int offset=0, int stride=sizeof(T));\n\n// Plots a pie chart. If the sum of values > 1 or normalize is true, each value will be normalized. Center and radius are in plot units. #label_fmt can be set to NULL for no labels.\nIMPLOT_TMP void PlotPieChart(const char* const label_ids[], const T* values, int count, double x, double y, double radius, bool normalize=false, const char* label_fmt=\"%.1f\", double angle0=90);\n\n// Plots a 2D heatmap chart. Values are expected to be in row-major order. Leave #scale_min and scale_max both at 0 for automatic color scaling, or set them to a predefined range. #label_fmt can be set to NULL for no labels.\nIMPLOT_TMP void PlotHeatmap(const char* label_id, const T* values, int rows, int cols, double scale_min=0, double scale_max=0, const char* label_fmt=\"%.1f\", const ImPlotPoint& bounds_min=ImPlotPoint(0,0), const ImPlotPoint& bounds_max=ImPlotPoint(1,1));\n\n// Plots a horizontal histogram. #bins can be a positive integer or an ImPlotBin_ method. If #cumulative is true, each bin contains its count plus the counts of all previous bins.\n// If #density is true, the PDF is visualized. If both are true, the CDF is visualized. If #range is left unspecified, the min/max of #values will be used as the range.\n// If #range is specified, outlier values outside of the range are not binned. However, outliers still count toward normalizing and cumulative counts unless #outliers is false. The largest bin count or density is returned.\nIMPLOT_TMP double PlotHistogram(const char* label_id, const T* values, int count, int bins=ImPlotBin_Sturges, bool cumulative=false, bool density=false, ImPlotRange range=ImPlotRange(), bool outliers=true, double bar_scale=1.0);\n\n// Plots two dimensional, bivariate histogram as a heatmap. #x_bins and #y_bins can be a positive integer or an ImPlotBin. If #density is true, the PDF is visualized.\n// If #bounds is left unspecified, the min/max of #xs an #ys will be used as the ranges. If #bounds is specified, outlier values outside of range are not binned.\n// However, outliers still count toward the normalizing count for density plots unless #outliers is false. The largest bin count or density is returned.\nIMPLOT_TMP double PlotHistogram2D(const char* label_id, const T* xs, const T* ys, int count, int x_bins=ImPlotBin_Sturges, int y_bins=ImPlotBin_Sturges, bool density=false, ImPlotRect range=ImPlotRect(), bool outliers=true);\n\n// Plots digital data. Digital plots do not respond to y drag or zoom, and are always referenced to the bottom of the plot.\nIMPLOT_TMP void PlotDigital(const char* label_id, const T* xs, const T* ys, int count, int offset=0, int stride=sizeof(T));\nIMPLOT_API void PlotDigitalG(const char* label_id, ImPlotGetter getter, void* data, int count);\n\n// Plots an axis-aligned image. #bounds_min/bounds_max are in plot coordinates (y-up) and #uv0/uv1 are in texture coordinates (y-down).\nIMPLOT_API void PlotImage(const char* label_id, ImTextureID user_texture_id, const ImPlotPoint& bounds_min, const ImPlotPoint& bounds_max, const ImVec2& uv0=ImVec2(0,0), const ImVec2& uv1=ImVec2(1,1), const ImVec4& tint_col=ImVec4(1,1,1,1));\n\n// Plots a centered text label at point x,y with an optional pixel offset. Text color can be changed with ImPlot::PushStyleColor(ImPlotCol_InlayText, ...).\nIMPLOT_API void PlotText(const char* text, double x, double y, bool vertical=false, const ImVec2& pix_offset=ImVec2(0,0));\n\n// Plots a dummy item (i.e. adds a legend entry colored by ImPlotCol_Line)\nIMPLOT_API void PlotDummy(const char* label_id);\n\n//-----------------------------------------------------------------------------\n// [SECTION] Plot Tools\n//-----------------------------------------------------------------------------\n\n// The following can be used to render interactive elements and/or annotations.\n// Like the item plotting functions above, they apply to the current x and y\n// axes, which can be changed with `SetAxis/SetAxes`.\n\n// Shows a draggable point at x,y. #col defaults to ImGuiCol_Text.\nIMPLOT_API bool DragPoint(int id, double* x, double* y, const ImVec4& col, float size = 4, ImPlotDragToolFlags flags = ImPlotDragToolFlags_None);\n// Shows a draggable vertical guide line at an x-value. #col defaults to ImGuiCol_Text.\nIMPLOT_API bool DragLineX(int id, double* x, const ImVec4& col, float thickness = 1, ImPlotDragToolFlags flags = ImPlotDragToolFlags_None);\n// Shows a draggable horizontal guide line at a y-value. #col defaults to ImGuiCol_Text.\nIMPLOT_API bool DragLineY(int id, double* y, const ImVec4& col, float thickness = 1, ImPlotDragToolFlags flags = ImPlotDragToolFlags_None);\n// Shows a draggable and resizeable rectangle.\nIMPLOT_API bool DragRect(int id, double* x_min, double* y_min, double* x_max, double* y_max, const ImVec4& col, ImPlotDragToolFlags flags = ImPlotDragToolFlags_None);\n\n// Shows an annotation callout at a chosen point. Clamping keeps annotations in the plot area. Annotations are always rendered on top.\nIMPLOT_API void Annotation(double x, double y, const ImVec4& color, const ImVec2& pix_offset, bool clamp, bool round = false);\nIMPLOT_API void Annotation(double x, double y, const ImVec4& color, const ImVec2& pix_offset, bool clamp, const char* fmt, ...)           IM_FMTARGS(6);\nIMPLOT_API void AnnotationV(double x, double y, const ImVec4& color, const ImVec2& pix_offset, bool clamp, const char* fmt, va_list args) IM_FMTLIST(6);\n\n// Shows a x-axis tag at the specified coordinate value.\nIMPLOT_API void TagX(double x, const ImVec4& color, bool round = false);\nIMPLOT_API void TagX(double x, const ImVec4& color, const char* fmt, ...)           IM_FMTARGS(3);\nIMPLOT_API void TagXV(double x, const ImVec4& color, const char* fmt, va_list args) IM_FMTLIST(3);\n\n// Shows a y-axis tag at the specified coordinate value.\nIMPLOT_API void TagY(double y, const ImVec4& color, bool round = false);\nIMPLOT_API void TagY(double y, const ImVec4& color, const char* fmt, ...)           IM_FMTARGS(3);\nIMPLOT_API void TagYV(double y, const ImVec4& color, const char* fmt, va_list args) IM_FMTLIST(3);\n\n//-----------------------------------------------------------------------------\n// [SECTION] Plot Utils\n//-----------------------------------------------------------------------------\n\n// Select which axis/axes will be used for subsequent plot elements.\nIMPLOT_API void SetAxis(ImAxis axis);\nIMPLOT_API void SetAxes(ImAxis x_axis, ImAxis y_axis);\n\n// Convert pixels to a position in the current plot's coordinate system. Passing IMPLOT_AUTO uses the current axes.\nIMPLOT_API ImPlotPoint PixelsToPlot(const ImVec2& pix, ImAxis x_axis = IMPLOT_AUTO, ImAxis y_axis = IMPLOT_AUTO);\nIMPLOT_API ImPlotPoint PixelsToPlot(float x, float y, ImAxis x_axis = IMPLOT_AUTO, ImAxis y_axis = IMPLOT_AUTO);\n\n// Convert a position in the current plot's coordinate system to pixels. Passing IMPLOT_AUTO uses the current axes.\nIMPLOT_API ImVec2 PlotToPixels(const ImPlotPoint& plt, ImAxis x_axis = IMPLOT_AUTO, ImAxis y_axis = IMPLOT_AUTO);\nIMPLOT_API ImVec2 PlotToPixels(double x, double y, ImAxis x_axis = IMPLOT_AUTO, ImAxis y_axis = IMPLOT_AUTO);\n\n// Get the current Plot position (top-left) in pixels.\nIMPLOT_API ImVec2 GetPlotPos();\n// Get the curent Plot size in pixels.\nIMPLOT_API ImVec2 GetPlotSize();\n\n// Returns the mouse position in x,y coordinates of the current plot. Passing IMPLOT_AUTO uses the current axes.\nIMPLOT_API ImPlotPoint GetPlotMousePos(ImAxis x_axis = IMPLOT_AUTO, ImAxis y_axis = IMPLOT_AUTO);\n// Returns the current plot axis range.\nIMPLOT_API ImPlotRect GetPlotLimits(ImAxis x_axis = IMPLOT_AUTO, ImAxis y_axis = IMPLOT_AUTO);\n\n// Returns true if the plot area in the current plot is hovered.\nIMPLOT_API bool IsPlotHovered();\n// Returns true if the axis label area in the current plot is hovered.\nIMPLOT_API bool IsAxisHovered(ImAxis axis);\n// Returns true if the bounding frame of a subplot is hovered.\nIMPLOT_API bool IsSubplotsHovered();\n\n// Returns true if the current plot is being box selected.\nIMPLOT_API bool IsPlotSelected();\n// Returns the current plot box selection bounds. Passing IMPLOT_AUTO uses the current axes.\nIMPLOT_API ImPlotRect GetPlotSelection(ImAxis x_axis = IMPLOT_AUTO, ImAxis y_axis = IMPLOT_AUTO);\n// Cancels a the current plot box selection.\nIMPLOT_API void CancelPlotSelection();\n\n// Hides or shows the next plot item (i.e. as if it were toggled from the legend).\n// Use ImPlotCond_Always if you need to forcefully set this every frame.\nIMPLOT_API void HideNextItem(bool hidden = true, ImPlotCond cond = ImPlotCond_Once);\n\n// Use the following around calls to Begin/EndPlot to align l/r/t/b padding.\n// Consider using Begin/EndSubplots first. They are more feature rich and\n// accomplish the same behaviour by default. The functions below offer lower\n// level control of plot alignment.\n\n// Align axis padding over multiple plots in a single row or column. #group_id must\n// be unique. If this function returns true, EndAlignedPlots() must be called.\nIMPLOT_API bool BeginAlignedPlots(const char* group_id, bool vertical = true);\n// Only call EndAlignedPlots() if BeginAlignedPlots() returns true!\nIMPLOT_API void EndAlignedPlots();\n\n//-----------------------------------------------------------------------------\n// [SECTION] Legend Utils\n//-----------------------------------------------------------------------------\n\n// Begin a popup for a legend entry.\nIMPLOT_API bool BeginLegendPopup(const char* label_id, ImGuiMouseButton mouse_button = 1);\n// End a popup for a legend entry.\nIMPLOT_API void EndLegendPopup();\n// Returns true if a plot item legend entry is hovered.\nIMPLOT_API bool IsLegendEntryHovered(const char* label_id);\n\n//-----------------------------------------------------------------------------\n// [SECTION] Drag and Drop\n//-----------------------------------------------------------------------------\n\n// Turns the current plot's plotting area into a drag and drop target. Don't forget to call EndDragDropTarget!\nIMPLOT_API bool BeginDragDropTargetPlot();\n// Turns the current plot's X-axis into a drag and drop target. Don't forget to call EndDragDropTarget!\nIMPLOT_API bool BeginDragDropTargetAxis(ImAxis axis);\n// Turns the current plot's legend into a drag and drop target. Don't forget to call EndDragDropTarget!\nIMPLOT_API bool BeginDragDropTargetLegend();\n// Ends a drag and drop target (currently just an alias for ImGui::EndDragDropTarget).\nIMPLOT_API void EndDragDropTarget();\n\n// NB: By default, plot and axes drag and drop *sources* require holding the Ctrl modifier to initiate the drag.\n// You can change the modifier if desired. If ImGuiKeyModFlags_None is provided, the axes will be locked from panning.\n\n// Turns the current plot's plotting area into a drag and drop source. You must hold Ctrl. Don't forget to call EndDragDropSource!\nIMPLOT_API bool BeginDragDropSourcePlot(ImGuiDragDropFlags flags = 0);\n// Turns the current plot's X-axis into a drag and drop source. You must hold Ctrl. Don't forget to call EndDragDropSource!\nIMPLOT_API bool BeginDragDropSourceAxis(ImAxis axis, ImGuiDragDropFlags flags = 0);\n// Turns an item in the current plot's legend into drag and drop source. Don't forget to call EndDragDropSource!\nIMPLOT_API bool BeginDragDropSourceItem(const char* label_id, ImGuiDragDropFlags flags = 0);\n// Ends a drag and drop source (currently just an alias for ImGui::EndDragDropSource).\nIMPLOT_API void EndDragDropSource();\n\n//-----------------------------------------------------------------------------\n// [SECTION] Styling\n//-----------------------------------------------------------------------------\n\n// Styling colors in ImPlot works similarly to styling colors in ImGui, but\n// with one important difference. Like ImGui, all style colors are stored in an\n// indexable array in ImPlotStyle. You can permanently modify these values through\n// GetStyle().Colors, or temporarily modify them with Push/Pop functions below.\n// However, by default all style colors in ImPlot default to a special color\n// IMPLOT_AUTO_COL. The behavior of this color depends upon the style color to\n// which it as applied:\n//\n//     1) For style colors associated with plot items (e.g. ImPlotCol_Line),\n//        IMPLOT_AUTO_COL tells ImPlot to color the item with the next unused\n//        color in the current colormap. Thus, every item will have a different\n//        color up to the number of colors in the colormap, at which point the\n//        colormap will roll over. For most use cases, you should not need to\n//        set these style colors to anything but IMPLOT_COL_AUTO; you are\n//        probably better off changing the current colormap. However, if you\n//        need to explicitly color a particular item you may either Push/Pop\n//        the style color around the item in question, or use the SetNextXXXStyle\n//        API below. If you permanently set one of these style colors to a specific\n//        color, or forget to call Pop, then all subsequent items will be styled\n//        with the color you set.\n//\n//     2) For style colors associated with plot styling (e.g. ImPlotCol_PlotBg),\n//        IMPLOT_AUTO_COL tells ImPlot to set that color from color data in your\n//        **ImGuiStyle**. The ImGuiCol_ that these style colors default to are\n//        detailed above, and in general have been mapped to produce plots visually\n//        consistent with your current ImGui style. Of course, you are free to\n//        manually set these colors to whatever you like, and further can Push/Pop\n//        them around individual plots for plot-specific styling (e.g. coloring axes).\n\n// Provides access to plot style structure for permanant modifications to colors, sizes, etc.\nIMPLOT_API ImPlotStyle& GetStyle();\n\n// Style plot colors for current ImGui style (default).\nIMPLOT_API void StyleColorsAuto(ImPlotStyle* dst = NULL);\n// Style plot colors for ImGui \"Classic\".\nIMPLOT_API void StyleColorsClassic(ImPlotStyle* dst = NULL);\n// Style plot colors for ImGui \"Dark\".\nIMPLOT_API void StyleColorsDark(ImPlotStyle* dst = NULL);\n// Style plot colors for ImGui \"Light\".\nIMPLOT_API void StyleColorsLight(ImPlotStyle* dst = NULL);\n\n// Use PushStyleX to temporarily modify your ImPlotStyle. The modification\n// will last until the matching call to PopStyleX. You MUST call a pop for\n// every push, otherwise you will leak memory! This behaves just like ImGui.\n\n// Temporarily modify a style color. Don't forget to call PopStyleColor!\nIMPLOT_API void PushStyleColor(ImPlotCol idx, ImU32 col);\nIMPLOT_API void PushStyleColor(ImPlotCol idx, const ImVec4& col);\n// Undo temporary style color modification(s). Undo multiple pushes at once by increasing count.\nIMPLOT_API void PopStyleColor(int count = 1);\n\n// Temporarily modify a style variable of float type. Don't forget to call PopStyleVar!\nIMPLOT_API void PushStyleVar(ImPlotStyleVar idx, float val);\n// Temporarily modify a style variable of int type. Don't forget to call PopStyleVar!\nIMPLOT_API void PushStyleVar(ImPlotStyleVar idx, int val);\n// Temporarily modify a style variable of ImVec2 type. Don't forget to call PopStyleVar!\nIMPLOT_API void PushStyleVar(ImPlotStyleVar idx, const ImVec2& val);\n// Undo temporary style variable modification(s). Undo multiple pushes at once by increasing count.\nIMPLOT_API void PopStyleVar(int count = 1);\n\n// The following can be used to modify the style of the next plot item ONLY. They do\n// NOT require calls to PopStyleX. Leave style attributes you don't want modified to\n// IMPLOT_AUTO or IMPLOT_AUTO_COL. Automatic styles will be deduced from the current\n// values in your ImPlotStyle or from Colormap data.\n\n// Set the line color and weight for the next item only.\nIMPLOT_API void SetNextLineStyle(const ImVec4& col = IMPLOT_AUTO_COL, float weight = IMPLOT_AUTO);\n// Set the fill color for the next item only.\nIMPLOT_API void SetNextFillStyle(const ImVec4& col = IMPLOT_AUTO_COL, float alpha_mod = IMPLOT_AUTO);\n// Set the marker style for the next item only.\nIMPLOT_API void SetNextMarkerStyle(ImPlotMarker marker = IMPLOT_AUTO, float size = IMPLOT_AUTO, const ImVec4& fill = IMPLOT_AUTO_COL, float weight = IMPLOT_AUTO, const ImVec4& outline = IMPLOT_AUTO_COL);\n// Set the error bar style for the next item only.\nIMPLOT_API void SetNextErrorBarStyle(const ImVec4& col = IMPLOT_AUTO_COL, float size = IMPLOT_AUTO, float weight = IMPLOT_AUTO);\n\n// Gets the last item primary color (i.e. its legend icon color)\nIMPLOT_API ImVec4 GetLastItemColor();\n\n// Returns the null terminated string name for an ImPlotCol.\nIMPLOT_API const char* GetStyleColorName(ImPlotCol idx);\n// Returns the null terminated string name for an ImPlotMarker.\nIMPLOT_API const char* GetMarkerName(ImPlotMarker idx);\n\n//-----------------------------------------------------------------------------\n// [SECTION] Colormaps\n//-----------------------------------------------------------------------------\n\n// Item styling is based on colormaps when the relevant ImPlotCol_XXX is set to\n// IMPLOT_AUTO_COL (default). Several built-in colormaps are available. You can\n// add and then push/pop your own colormaps as well. To permanently set a colormap,\n// modify the Colormap index member of your ImPlotStyle.\n\n// Colormap data will be ignored and a custom color will be used if you have done one of the following:\n//     1) Modified an item style color in your ImPlotStyle to anything other than IMPLOT_AUTO_COL.\n//     2) Pushed an item style color using PushStyleColor().\n//     3) Set the next item style with a SetNextXXXStyle function.\n\n// Add a new colormap. The color data will be copied. The colormap can be used by pushing either the returned index or the\n// string name with PushColormap. The colormap name must be unique and the size must be greater than 1. You will receive\n// an assert otherwise! By default colormaps are considered to be qualitative (i.e. discrete). If you want to create a\n// continuous colormap, set #qual=false. This will treat the colors you provide as keys, and ImPlot will build a linearly\n// interpolated lookup table. The memory footprint of this table will be exactly ((size-1)*255+1)*4 bytes.\nIMPLOT_API ImPlotColormap AddColormap(const char* name, const ImVec4* cols, int size, bool qual=true);\nIMPLOT_API ImPlotColormap AddColormap(const char* name, const ImU32*  cols, int size, bool qual=true);\n\n// Returns the number of available colormaps (i.e. the built-in + user-added count).\nIMPLOT_API int GetColormapCount();\n// Returns a null terminated string name for a colormap given an index. Returns NULL if index is invalid.\nIMPLOT_API const char* GetColormapName(ImPlotColormap cmap);\n// Returns an index number for a colormap given a valid string name. Returns -1 if name is invalid.\nIMPLOT_API ImPlotColormap GetColormapIndex(const char* name);\n\n// Temporarily switch to one of the built-in (i.e. ImPlotColormap_XXX) or user-added colormaps (i.e. a return value of AddColormap). Don't forget to call PopColormap!\nIMPLOT_API void PushColormap(ImPlotColormap cmap);\n// Push a colormap by string name. Use built-in names such as \"Default\", \"Deep\", \"Jet\", etc. or a string you provided to AddColormap. Don't forget to call PopColormap!\nIMPLOT_API void PushColormap(const char* name);\n// Undo temporary colormap modification(s). Undo multiple pushes at once by increasing count.\nIMPLOT_API void PopColormap(int count = 1);\n\n// Returns the next color from the current colormap and advances the colormap for the current plot.\n// Can also be used with no return value to skip colors if desired. You need to call this between Begin/EndPlot!\nIMPLOT_API ImVec4 NextColormapColor();\n\n// Colormap utils. If cmap = IMPLOT_AUTO (default), the current colormap is assumed.\n// Pass an explicit colormap index (built-in or user-added) to specify otherwise.\n\n// Returns the size of a colormap.\nIMPLOT_API int GetColormapSize(ImPlotColormap cmap = IMPLOT_AUTO);\n// Returns a color from a colormap given an index >= 0 (modulo will be performed).\nIMPLOT_API ImVec4 GetColormapColor(int idx, ImPlotColormap cmap = IMPLOT_AUTO);\n// Sample a color from the current colormap given t between 0 and 1.\nIMPLOT_API ImVec4 SampleColormap(float t, ImPlotColormap cmap = IMPLOT_AUTO);\n\n// Shows a vertical color scale with linear spaced ticks using the specified color map. Use double hashes to hide label (e.g. \"##NoLabel\").\nIMPLOT_API void ColormapScale(const char* label, double scale_min, double scale_max, const ImVec2& size = ImVec2(0,0), ImPlotColormap cmap = IMPLOT_AUTO, const char* format = \"%g\");\n// Shows a horizontal slider with a colormap gradient background. Optionally returns the color sampled at t in [0 1].\nIMPLOT_API bool ColormapSlider(const char* label, float* t, ImVec4* out = NULL, const char* format = \"\", ImPlotColormap cmap = IMPLOT_AUTO);\n// Shows a button with a colormap gradient brackground.\nIMPLOT_API bool ColormapButton(const char* label, const ImVec2& size = ImVec2(0,0), ImPlotColormap cmap = IMPLOT_AUTO);\n\n// When items in a plot sample their color from a colormap, the color is cached and does not change\n// unless explicitly overriden. Therefore, if you change the colormap after the item has already been plotted,\n// item colors will NOT update. If you need item colors to resample the new colormap, then use this\n// function to bust the cached colors. If #plot_title_id is NULL, then every item in EVERY existing plot\n// will be cache busted. Otherwise only the plot specified by #plot_title_id will be busted. For the\n// latter, this function must be called in the same ImGui ID scope that the plot is in. You should rarely if ever\n// need this function, but it is available for applications that require runtime colormap swaps (e.g. Heatmaps demo).\nIMPLOT_API void BustColorCache(const char* plot_title_id = NULL);\n\n//-----------------------------------------------------------------------------\n// [SECTION] Input Mapping\n//-----------------------------------------------------------------------------\n\n// Provides access to input mapping structure for permanant modifications to controls for pan, select, etc.\nIMPLOT_API ImPlotInputMap& GetInputMap();\n\n// Default input mapping: pan = LMB drag, box select = RMB drag, fit = LMB double click, context menu = RMB click, zoom = scroll.\nIMPLOT_API void MapInputDefault(ImPlotInputMap* dst = NULL);\n// Reverse input mapping: pan = RMB drag, box select = LMB drag, fit = LMB double click, context menu = RMB click, zoom = scroll.\nIMPLOT_API void MapInputReverse(ImPlotInputMap* dst = NULL);\n\n//-----------------------------------------------------------------------------\n// [SECTION] Miscellaneous\n//-----------------------------------------------------------------------------\n\n// Render icons similar to those that appear in legends (nifty for data lists).\nIMPLOT_API void ItemIcon(const ImVec4& col);\nIMPLOT_API void ItemIcon(ImU32 col);\nIMPLOT_API void ColormapIcon(ImPlotColormap cmap);\n\n// Get the plot draw list for custom rendering to the current plot area. Call between Begin/EndPlot.\nIMPLOT_API ImDrawList* GetPlotDrawList();\n// Push clip rect for rendering to current plot area. The rect can be expanded or contracted by #expand pixels. Call between Begin/EndPlot.\nIMPLOT_API void PushPlotClipRect(float expand=0);\n// Pop plot clip rect. Call between Begin/EndPlot.\nIMPLOT_API void PopPlotClipRect();\n\n// Shows ImPlot style selector dropdown menu.\nIMPLOT_API bool ShowStyleSelector(const char* label);\n// Shows ImPlot colormap selector dropdown menu.\nIMPLOT_API bool ShowColormapSelector(const char* label);\n// Shows ImPlot input map selector dropdown menu.\nIMPLOT_API bool ShowInputMapSelector(const char* label);\n// Shows ImPlot style editor block (not a window).\nIMPLOT_API void ShowStyleEditor(ImPlotStyle* ref = NULL);\n// Add basic help/info block for end users (not a window).\nIMPLOT_API void ShowUserGuide();\n// Shows ImPlot metrics/debug information window.\nIMPLOT_API void ShowMetricsWindow(bool* p_popen = NULL);\n\n//-----------------------------------------------------------------------------\n// [SECTION] Demo\n//-----------------------------------------------------------------------------\n\n// Shows the ImPlot demo window (add implot_demo.cpp to your sources!)\nIMPLOT_API void ShowDemoWindow(bool* p_open = NULL);\n\n}  // namespace ImPlot\n\n//-----------------------------------------------------------------------------\n// [SECTION] Obsolete API\n//-----------------------------------------------------------------------------\n\n// The following functions will be removed! Keep your copy of implot up to date!\n// Occasionally set '#define IMPLOT_DISABLE_OBSOLETE_FUNCTIONS' to stay ahead.\n// If you absolutely must use these functions and do not want to receive compiler\n// warnings, set '#define IMPLOT_DISABLE_OBSOLETE_WARNINGS'.\n\n#ifndef IMPLOT_DISABLE_OBSOLETE_FUNCTIONS\n\n#ifndef IMPLOT_DISABLE_DEPRECATED_WARNINGS\n#if __cplusplus > 201402L\n#define IMPLOT_DEPRECATED(method) [[deprecated]] method\n#elif defined( __GNUC__ ) && !defined( __INTEL_COMPILER ) && ( __GNUC__ > 3 || ( __GNUC__ == 3 && __GNUC_MINOR__ >= 1 ) )\n#define IMPLOT_DEPRECATED(method) method __attribute__( ( deprecated ) )\n#elif defined( _MSC_VER )\n#define IMPLOT_DEPRECATED(method) __declspec(deprecated) method\n#else\n#define IMPLOT_DEPRECATED(method) method\n#endif\n#else\n#define IMPLOT_DEPRECATED(method) method\n#endif\n\nenum ImPlotFlagsObsolete_ {\n    ImPlotFlags_YAxis2 = 1 << 20,\n    ImPlotFlags_YAxis3 = 1 << 21,\n};\n\nnamespace ImPlot {\n\n// OBSOLETED in v0.13 -> PLANNED REMOVAL in v1.0\nIMPLOT_DEPRECATED( IMPLOT_API bool BeginPlot(const char* title_id,\n                                             const char* x_label,  // = NULL,\n                                             const char* y_label,  // = NULL,\n                                             const ImVec2& size       = ImVec2(-1,0),\n                                             ImPlotFlags flags        = ImPlotFlags_None,\n                                             ImPlotAxisFlags x_flags  = ImPlotAxisFlags_None,\n                                             ImPlotAxisFlags y_flags  = ImPlotAxisFlags_None,\n                                             ImPlotAxisFlags y2_flags = ImPlotAxisFlags_AuxDefault,\n                                             ImPlotAxisFlags y3_flags = ImPlotAxisFlags_AuxDefault,\n                                             const char* y2_label     = NULL,\n                                             const char* y3_label     = NULL) );\n\n} // namespace ImPlot\n\n#endif\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/implot/implot_demo.cpp",
    "content": "// MIT License\n\n// Copyright (c) 2021 Evan Pezent\n\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n// ImPlot v0.13 WIP\n\n// We define this so that the demo does not accidentally use deprecated API\n#define IMPLOT_DISABLE_OBSOLETE_FUNCTIONS\n\n#include \"implot.h\"\n#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\n#ifdef _MSC_VER\n#define sprintf sprintf_s\n#endif\n\n#ifndef PI\n#define PI 3.14159265358979323846\n#endif\n\n// Encapsulates examples for customizing ImPlot.\nnamespace MyImPlot {\n\n// Example for Custom Data and Getters section.\nstruct Vector2f {\n    Vector2f(float _x, float _y) { x = _x; y = _y; }\n    float x, y;\n};\n\n// Example for Custom Data and Getters section.\nstruct WaveData {\n    double X, Amp, Freq, Offset;\n    WaveData(double x, double amp, double freq, double offset) { X = x; Amp = amp; Freq = freq; Offset = offset; }\n};\nImPlotPoint SineWave(void* wave_data, int idx);\nImPlotPoint SawWave(void* wave_data, int idx);\nImPlotPoint Spiral(void*, int idx);\n\n// Example for Tables section.\nvoid Sparkline(const char* id, const float* values, int count, float min_v, float max_v, int offset, const ImVec4& col, const ImVec2& size);\n\n// Example for Custom Plotters and Tooltips section.\nvoid PlotCandlestick(const char* label_id, const double* xs, const double* opens, const double* closes, const double* lows, const double* highs, int count, bool tooltip = true, float width_percent = 0.25f, ImVec4 bullCol = ImVec4(0,1,0,1), ImVec4 bearCol = ImVec4(1,0,0,1));\n\n// Example for Custom Styles section.\nvoid StyleSeaborn();\n\n} // namespace MyImPlot\n\nnamespace ImPlot {\n\nvoid ShowBenchmarkTool();\n\ntemplate <typename T>\ninline T RandomRange(T min, T max) {\n    T scale = rand() / (T) RAND_MAX;\n    return min + scale * ( max - min );\n}\n\nImVec4 RandomColor() {\n    ImVec4 col;\n    col.x = RandomRange(0.0f,1.0f);\n    col.y = RandomRange(0.0f,1.0f);\n    col.z = RandomRange(0.0f,1.0f);\n    col.w = 1.0f;\n    return col;\n}\n\ndouble RandomGauss() {\n\tstatic double V1, V2, S;\n\tstatic int phase = 0;\n\tdouble X;\n\tif(phase == 0) {\n\t\tdo {\n\t\t\tdouble U1 = (double)rand() / RAND_MAX;\n\t\t\tdouble U2 = (double)rand() / RAND_MAX;\n\t\t\tV1 = 2 * U1 - 1;\n\t\t\tV2 = 2 * U2 - 1;\n\t\t\tS = V1 * V1 + V2 * V2;\n\t\t\t} while(S >= 1 || S == 0);\n\n\t\tX = V1 * sqrt(-2 * log(S) / S);\n\t} else\n\t\tX = V2 * sqrt(-2 * log(S) / S);\n\tphase = 1 - phase;\n\treturn X;\n}\n\ntemplate <int N>\nstruct NormalDistribution {\n    NormalDistribution(double mean, double sd) {\n        for (int i = 0; i < N; ++i)\n            Data[i] = RandomGauss()*sd + mean;\n    }\n    double Data[N];\n};\n\n// utility structure for realtime plot\nstruct ScrollingBuffer {\n    int MaxSize;\n    int Offset;\n    ImVector<ImVec2> Data;\n    ScrollingBuffer(int max_size = 2000) {\n        MaxSize = max_size;\n        Offset  = 0;\n        Data.reserve(MaxSize);\n    }\n    void AddPoint(float x, float y) {\n        if (Data.size() < MaxSize)\n            Data.push_back(ImVec2(x,y));\n        else {\n            Data[Offset] = ImVec2(x,y);\n            Offset =  (Offset + 1) % MaxSize;\n        }\n    }\n    void Erase() {\n        if (Data.size() > 0) {\n            Data.shrink(0);\n            Offset  = 0;\n        }\n    }\n};\n\n// utility structure for realtime plot\nstruct RollingBuffer {\n    float Span;\n    ImVector<ImVec2> Data;\n    RollingBuffer() {\n        Span = 10.0f;\n        Data.reserve(2000);\n    }\n    void AddPoint(float x, float y) {\n        float xmod = fmodf(x, Span);\n        if (!Data.empty() && xmod < Data.back().x)\n            Data.shrink(0);\n        Data.push_back(ImVec2(xmod, y));\n    }\n};\n\n// Huge data used by Time Formatting example (~500 MB allocation!)\nstruct HugeTimeData {\n    HugeTimeData(double min) {\n        Ts = new double[Size];\n        Ys = new double[Size];\n        for (int i = 0; i < Size; ++i) {\n            Ts[i] = min + i;\n            Ys[i] = GetY(Ts[i]);\n        }\n    }\n    ~HugeTimeData() { delete[] Ts;  delete[] Ys; }\n    static double GetY(double t) {\n        return 0.5 + 0.25 * sin(t/86400/12) +  0.005 * sin(t/3600);\n    }\n    double* Ts;\n    double* Ys;\n    static const int Size = 60*60*24*366;\n};\n\n//-----------------------------------------------------------------------------\n// [SECTION] Demo Functions\n//-----------------------------------------------------------------------------\n\nvoid ShowDemo_Help() {\n    ImGui::Text(\"ABOUT THIS DEMO:\");\n    ImGui::BulletText(\"Sections below are demonstrating many aspects of the library.\");\n    ImGui::BulletText(\"The \\\"Tools\\\" menu above gives access to: Style Editors (ImPlot/ImGui)\\n\"\n                        \"and Metrics (general purpose Dear ImGui debugging tool).\");\n    ImGui::Separator();\n    ImGui::Text(\"PROGRAMMER GUIDE:\");\n    ImGui::BulletText(\"See the ShowDemoWindow() code in implot_demo.cpp. <- you are here!\");\n    ImGui::BulletText(\"By default, anti-aliased lines are turned OFF.\");\n    ImGui::Indent();\n        ImGui::BulletText(\"Software AA can be enabled globally with ImPlotStyle.AntiAliasedLines.\");\n        ImGui::BulletText(\"Software AA can be enabled per plot with ImPlotFlags_AntiAliased.\");\n        ImGui::BulletText(\"AA for plots can be toggled from the plot's context menu.\");\n        ImGui::BulletText(\"If permitable, you are better off using hardware AA (e.g. MSAA).\");\n    ImGui::Unindent();\n    ImGui::BulletText(\"If you see visual artifacts, do one of the following:\");\n    ImGui::Indent();\n    ImGui::BulletText(\"Handle ImGuiBackendFlags_RendererHasVtxOffset for 16-bit indices in your backend.\");\n    ImGui::BulletText(\"Or, enable 32-bit indices in imconfig.h.\");\n    ImGui::BulletText(\"Your current configuration is:\");\n    ImGui::Indent();\n    ImGui::BulletText(\"ImDrawIdx: %d-bit\", (int)(sizeof(ImDrawIdx) * 8));\n    ImGui::BulletText(\"ImGuiBackendFlags_RendererHasVtxOffset: %s\", (ImGui::GetIO().BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset) ? \"True\" : \"False\");\n    ImGui::Unindent();\n    ImGui::Unindent();\n    ImGui::Separator();\n    ImGui::Text(\"USER GUIDE:\");\n    ShowUserGuide();\n}\n\n//-----------------------------------------------------------------------------\n\nvoid ButtonSelector(const char* label, ImGuiMouseButton* b) {\n    ImGui::PushID(label);\n    if (ImGui::RadioButton(\"LMB\",*b == ImGuiMouseButton_Left))\n        *b = ImGuiMouseButton_Left;\n    ImGui::SameLine();\n    if (ImGui::RadioButton(\"RMB\",*b == ImGuiMouseButton_Right))\n        *b = ImGuiMouseButton_Right;\n    ImGui::SameLine();\n    if (ImGui::RadioButton(\"MMB\",*b == ImGuiMouseButton_Middle))\n        *b = ImGuiMouseButton_Middle;\n    ImGui::PopID();\n}\n\nvoid ModSelector(const char* label, ImGuiKeyModFlags* k) {\n    ImGui::PushID(label);\n    ImGui::CheckboxFlags(\"Ctrl\", (unsigned int*)k, ImGuiKeyModFlags_Ctrl); ImGui::SameLine();\n    ImGui::CheckboxFlags(\"Shift\", (unsigned int*)k, ImGuiKeyModFlags_Shift); ImGui::SameLine();\n    ImGui::CheckboxFlags(\"Alt\", (unsigned int*)k, ImGuiKeyModFlags_Alt); ImGui::SameLine();\n    ImGui::CheckboxFlags(\"Super\", (unsigned int*)k, ImGuiKeyModFlags_Super);\n    ImGui::PopID();\n}\n\nvoid InputMapping(const char* label, ImGuiMouseButton* b, ImGuiKeyModFlags* k) {\n    ImGui::LabelText(\"##\",\"%s\",label);\n    if (b != NULL) {\n        ImGui::SameLine(100);\n        ButtonSelector(label,b);\n    }\n    if (k != NULL) {\n        ImGui::SameLine(300);\n        ModSelector(label,k);\n    }\n}\n\nvoid ShowInputMapping() {\n    ImPlotInputMap& map = ImPlot::GetInputMap();\n    InputMapping(\"Pan\",&map.Pan,&map.PanMod);\n    InputMapping(\"Fit\",&map.Fit,NULL);\n    InputMapping(\"Select\",&map.Select,&map.SelectMod);\n    InputMapping(\"SelectHorzMod\",NULL,&map.SelectHorzMod);\n    InputMapping(\"SelectVertMod\",NULL,&map.SelectVertMod);\n    InputMapping(\"SelectCancel\",&map.SelectCancel,NULL);\n    InputMapping(\"Menu\",&map.Menu,NULL);\n    InputMapping(\"OverrideMod\",NULL,&map.OverrideMod);\n    InputMapping(\"ZoomMod\",NULL,&map.ZoomMod);\n    ImGui::SliderFloat(\"ZoomRate\",&map.ZoomRate,-1,1);\n}\n\nvoid ShowDemo_Config() {\n    ImGui::ShowFontSelector(\"Font\");\n    ImGui::ShowStyleSelector(\"ImGui Style\");\n    ImPlot::ShowStyleSelector(\"ImPlot Style\");\n    ImPlot::ShowColormapSelector(\"ImPlot Colormap\");\n    ImPlot::ShowInputMapSelector(\"Input Map\");\n    ImGui::Separator();\n    ImGui::Checkbox(\"Anti-Aliased Lines\", &ImPlot::GetStyle().AntiAliasedLines);\n    ImGui::Checkbox(\"Use Local Time\", &ImPlot::GetStyle().UseLocalTime);\n    ImGui::Checkbox(\"Use ISO 8601\", &ImPlot::GetStyle().UseISO8601);\n    ImGui::Checkbox(\"Use 24 Hour Clock\", &ImPlot::GetStyle().Use24HourClock);\n    ImGui::Separator();\n    if (ImPlot::BeginPlot(\"Preview\")) {\n        static double now = (double)time(0);\n        ImPlot::SetupAxis(ImAxis_X1,NULL,ImPlotAxisFlags_Time);\n        ImPlot::SetupAxisLimits(ImAxis_X1, now, now + 24*3600);\n        for (int i = 0; i < 10; ++i) {\n            double x[2] = {now, now + 24*3600};\n            double y[2] = {0,i/9.0};\n            ImGui::PushID(i);\n            ImPlot::PlotLine(\"##Line\",x,y,2);\n            ImGui::PopID();\n        }\n        ImPlot::EndPlot();\n    }\n}\n\n//-----------------------------------------------------------------------------\n\nvoid ShowDemo_LinePlots() {\n    static float xs1[1001], ys1[1001];\n    for (int i = 0; i < 1001; ++i) {\n        xs1[i] = i * 0.001f;\n        ys1[i] = 0.5f + 0.5f * sinf(50 * (xs1[i] + (float)ImGui::GetTime() / 10));\n    }\n    static double xs2[11], ys2[11];\n    for (int i = 0; i < 11; ++i) {\n        xs2[i] = i * 0.1f;\n        ys2[i] = xs2[i] * xs2[i];\n    }\n    ImGui::BulletText(\"Anti-aliasing can be enabled from the plot's context menu (see Help).\");\n    if (ImPlot::BeginPlot(\"Line Plot\")) {\n        ImPlot::SetupAxes(\"x\",\"f(x)\");\n        ImPlot::PlotLine(\"sin(x)\", xs1, ys1, 1001);\n        ImPlot::SetNextMarkerStyle(ImPlotMarker_Circle);\n        ImPlot::PlotLine(\"x^2\", xs2, ys2, 11);\n        ImPlot::EndPlot();\n    }\n}\n\n//-----------------------------------------------------------------------------\n\nvoid ShowDemo_FilledLinePlots() {\n    static double xs1[101], ys1[101], ys2[101], ys3[101];\n    srand(0);\n    for (int i = 0; i < 101; ++i) {\n        xs1[i] = (float)i;\n        ys1[i] = RandomRange(400.0,450.0);\n        ys2[i] = RandomRange(275.0,350.0);\n        ys3[i] = RandomRange(150.0,225.0);\n    }\n    static bool show_lines = true;\n    static bool show_fills = true;\n    static float fill_ref = 0;\n    static int shade_mode = 0;\n    ImGui::Checkbox(\"Lines\",&show_lines); ImGui::SameLine();\n    ImGui::Checkbox(\"Fills\",&show_fills);\n    if (show_fills) {\n        ImGui::SameLine();\n        if (ImGui::RadioButton(\"To -INF\",shade_mode == 0))\n            shade_mode = 0;\n        ImGui::SameLine();\n        if (ImGui::RadioButton(\"To +INF\",shade_mode == 1))\n            shade_mode = 1;\n        ImGui::SameLine();\n        if (ImGui::RadioButton(\"To Ref\",shade_mode == 2))\n            shade_mode = 2;\n        if (shade_mode == 2) {\n            ImGui::SameLine();\n            ImGui::SetNextItemWidth(100);\n            ImGui::DragFloat(\"##Ref\",&fill_ref, 1, -100, 500);\n        }\n    }\n\n    if (ImPlot::BeginPlot(\"Stock Prices\")) {\n        ImPlot::SetupAxes(\"Days\",\"Price\");\n        ImPlot::SetupAxesLimits(0,100,0,500);\n        if (show_fills) {\n            ImPlot::PushStyleVar(ImPlotStyleVar_FillAlpha, 0.25f);\n            ImPlot::PlotShaded(\"Stock 1\", xs1, ys1, 101, shade_mode == 0 ? -INFINITY : shade_mode == 1 ? INFINITY : fill_ref);\n            ImPlot::PlotShaded(\"Stock 2\", xs1, ys2, 101, shade_mode == 0 ? -INFINITY : shade_mode == 1 ? INFINITY : fill_ref);\n            ImPlot::PlotShaded(\"Stock 3\", xs1, ys3, 101, shade_mode == 0 ? -INFINITY : shade_mode == 1 ? INFINITY : fill_ref);\n            ImPlot::PopStyleVar();\n        }\n        if (show_lines) {\n            ImPlot::PlotLine(\"Stock 1\", xs1, ys1, 101);\n            ImPlot::PlotLine(\"Stock 2\", xs1, ys2, 101);\n            ImPlot::PlotLine(\"Stock 3\", xs1, ys3, 101);\n        }\n        ImPlot::EndPlot();\n    }\n}\n\n//-----------------------------------------------------------------------------\n\nvoid ShowDemo_ShadedPlots() {\n    static float xs[1001], ys[1001], ys1[1001], ys2[1001], ys3[1001], ys4[1001];\n    srand(0);\n    for (int i = 0; i < 1001; ++i) {\n        xs[i]  = i * 0.001f;\n        ys[i]  = 0.25f + 0.25f * sinf(25 * xs[i]) * sinf(5 * xs[i]) + RandomRange(-0.01f, 0.01f);\n        ys1[i] = ys[i] + RandomRange(0.1f, 0.12f);\n        ys2[i] = ys[i] - RandomRange(0.1f, 0.12f);\n        ys3[i] = 0.75f + 0.2f * sinf(25 * xs[i]);\n        ys4[i] = 0.75f + 0.1f * cosf(25 * xs[i]);\n    }\n    static float alpha = 0.25f;\n    ImGui::DragFloat(\"Alpha\",&alpha,0.01f,0,1);\n\n    if (ImPlot::BeginPlot(\"Shaded Plots\")) {\n        ImPlot::PushStyleVar(ImPlotStyleVar_FillAlpha, alpha);\n        ImPlot::PlotShaded(\"Uncertain Data\",xs,ys1,ys2,1001);\n        ImPlot::PlotLine(\"Uncertain Data\", xs, ys, 1001);\n        ImPlot::PlotShaded(\"Overlapping\",xs,ys3,ys4,1001);\n        ImPlot::PlotLine(\"Overlapping\",xs,ys3,1001);\n        ImPlot::PlotLine(\"Overlapping\",xs,ys4,1001);\n        ImPlot::PopStyleVar();\n        ImPlot::EndPlot();\n    }\n}\n\n//-----------------------------------------------------------------------------\n\nvoid ShowDemo_ScatterPlots() {\n    srand(0);\n    static float xs1[100], ys1[100];\n    for (int i = 0; i < 100; ++i) {\n        xs1[i] = i * 0.01f;\n        ys1[i] = xs1[i] + 0.1f * ((float)rand() / (float)RAND_MAX);\n    }\n    static float xs2[50], ys2[50];\n    for (int i = 0; i < 50; i++) {\n        xs2[i] = 0.25f + 0.2f * ((float)rand() / (float)RAND_MAX);\n        ys2[i] = 0.75f + 0.2f * ((float)rand() / (float)RAND_MAX);\n    }\n\n    if (ImPlot::BeginPlot(\"Scatter Plot\")) {\n        ImPlot::PlotScatter(\"Data 1\", xs1, ys1, 100);\n        ImPlot::PushStyleVar(ImPlotStyleVar_FillAlpha, 0.25f);\n        ImPlot::SetNextMarkerStyle(ImPlotMarker_Square, 6, ImPlot::GetColormapColor(1), IMPLOT_AUTO, ImPlot::GetColormapColor(1));\n        ImPlot::PlotScatter(\"Data 2\", xs2, ys2, 50);\n        ImPlot::PopStyleVar();\n        ImPlot::EndPlot();\n    }\n}\n\n//-----------------------------------------------------------------------------\n\nvoid ShowDemo_StairstepPlots() {\n    static float ys1[101], ys2[101];\n    for (int i = 0; i < 101; ++i) {\n        ys1[i] = 0.5f + 0.4f * sinf(50 * i * 0.01f);\n        ys2[i] = 0.5f + 0.2f * sinf(25 * i * 0.01f);\n    }\n    if (ImPlot::BeginPlot(\"Stairstep Plot\")) {\n        ImPlot::SetupAxes(\"x\",\"f(x)\");\n        ImPlot::PlotStairs(\"Signal 1\", ys1, 101, 0.01f);\n        ImPlot::SetNextMarkerStyle(ImPlotMarker_Square, 2.0f);\n        ImPlot::PlotStairs(\"Signal 2\", ys2, 101, 0.01f);\n        ImPlot::EndPlot();\n    }\n}\n\n//-----------------------------------------------------------------------------\n\nvoid ShowDemo_BarPlots() {\n    static ImS8  data[10] = {1,2,3,4,5,6,7,8,9,10};\n    if (ImPlot::BeginPlot(\"Bar Plot\")) {\n        ImPlot::PlotBars(\"Bars\",data,10,0.7,1);\n        ImPlot::PlotBarsH(\"BarsH\",data,10,0.4,1);\n        ImPlot::EndPlot();\n    }\n}\n\nvoid ShowDemo_BarGroups() {\n    static ImS8  data[30] = {83, 67, 23, 89, 83, 78, 91, 82, 85, 90,  // midterm\n                             80, 62, 56, 99, 55, 78, 88, 78, 90, 100, // final\n                             80, 69, 52, 92, 72, 78, 75, 76, 89, 95}; // course\n\n    static const char*  ilabels[]   = {\"Midterm Exam\",\"Final Exam\",\"Course Grade\"};\n    static const char*  glabels[]   = {\"S1\",\"S2\",\"S3\",\"S4\",\"S5\",\"S6\",\"S7\",\"S8\",\"S9\",\"S10\"};\n    static const double positions[] = {0,1,2,3,4,5,6,7,8,9};\n\n    static int items  = 3;\n    static int groups = 10;\n    static float size = 0.67f;\n\n    static ImPlotBarGroupsFlags flags = 0;\n    static bool horz = false;\n\n    ImGui::CheckboxFlags(\"Stacked\", (unsigned int*)&flags, ImPlotBarGroupsFlags_Stacked);\n    ImGui::SameLine();\n    ImGui::Checkbox(\"Horizontal\",&horz);\n\n    ImGui::SliderInt(\"Items\",&items,1,3);\n    ImGui::SliderFloat(\"Size\",&size,0,1);\n\n    if (ImPlot::BeginPlot(\"Bar Group\")) {\n        ImPlot::SetupLegend(ImPlotLocation_East, ImPlotLegendFlags_Outside);\n        if (horz) {\n            ImPlot::SetupAxes(\"Score\",\"Student\",ImPlotAxisFlags_AutoFit,ImPlotAxisFlags_AutoFit);\n            ImPlot::SetupAxisTicks(ImAxis_Y1,positions, groups, glabels);\n            ImPlot::PlotBarGroupsH(ilabels,data,items,groups,size,0,flags);\n        }\n        else {\n            ImPlot::SetupAxes(\"Student\",\"Score\",ImPlotAxisFlags_AutoFit,ImPlotAxisFlags_AutoFit);\n            ImPlot::SetupAxisTicks(ImAxis_X1,positions, groups, glabels);\n            ImPlot::PlotBarGroups(ilabels,data,items,groups,size,0,flags);\n        }\n        ImPlot::EndPlot();\n    }\n}\n\nvoid ShowDemo_BarStacks() {\n\n    static ImPlotColormap Liars = -1;\n    if (Liars == -1) {\n        static const ImU32 Liars_Data[6] = { 4282515870, 4282609140, 4287357182, 4294630301, 4294945280, 4294921472 };\n        Liars = ImPlot::AddColormap(\"Liars\", Liars_Data, 6);\n    }\n\n    static bool diverging = true;\n    ImGui::Checkbox(\"Diverging\",&diverging);\n\n    static const char* politicians[] = {\"Trump\",\"Bachman\",\"Cruz\",\"Gingrich\",\"Palin\",\"Santorum\",\"Walker\",\"Perry\",\"Ryan\",\"McCain\",\"Rubio\",\"Romney\",\"Rand Paul\",\"Christie\",\"Biden\",\"Kasich\",\"Sanders\",\"J Bush\",\"H Clinton\",\"Obama\"};\n    static int data_reg[] = {18,26,7,14,10,8,6,11,4,4,3,8,6,8,6,5,0,3,1,2,                // Pants on Fire\n                             43,36,30,21,30,27,25,17,11,22,15,16,16,17,12,12,14,6,13,12,  // False\n                             16,13,28,22,15,21,15,18,30,17,24,18,13,10,14,15,17,22,14,12, // Mostly False\n                             17,10,13,25,12,22,19,26,23,17,22,27,20,26,29,17,18,22,21,27, // Half True\n                             5,7,16,10,10,12,23,13,17,20,22,16,23,19,20,26,36,29,27,26,   // Mostly True\n                             1,8,6,8,23,10,12,15,15,20,14,15,22,20,19,25,15,18,24,21};    // True\n    static const char* labels_reg[] = {\"Pants on Fire\",\"False\",\"Mostly False\",\"Half True\",\"Mostly True\",\"True\"};\n\n\n    static int data_div[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,                                         // Pants on Fire (dummy, to order legend logically)\n                             0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,                                         // False         (dummy, to order legend logically)\n                             0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,                                         // Mostly False  (dummy, to order legend logically)\n                             -16,-13,-28,-22,-15,-21,-15,-18,-30,-17,-24,-18,-13,-10,-14,-15,-17,-22,-14,-12, // Mostly False\n                             -43,-36,-30,-21,-30,-27,-25,-17,-11,-22,-15,-16,-16,-17,-12,-12,-14,-6,-13,-12,  // False\n                             -18,-26,-7,-14,-10,-8,-6,-11,-4,-4,-3,-8,-6,-8,-6,-5,0,-3,-1,-2,                 // Pants on Fire\n                             17,10,13,25,12,22,19,26,23,17,22,27,20,26,29,17,18,22,21,27,                     // Half True\n                             5,7,16,10,10,12,23,13,17,20,22,16,23,19,20,26,36,29,27,26,                       // Mostly True\n                             1,8,6,8,23,10,12,15,15,20,14,15,22,20,19,25,15,18,24,21};                        // True\n    static const char* labels_div[] = {\"Pants on Fire\",\"False\",\"Mostly False\",\"Mostly False\",\"False\",\"Pants on Fire\",\"Half True\",\"Mostly True\",\"True\"};\n\n    ImPlot::PushColormap(Liars);\n    if (ImPlot::BeginPlot(\"PolitiFact: Who Lies More?\",ImVec2(-1,400),ImPlotFlags_NoMouseText)) {\n        ImPlot::SetupLegend(ImPlotLocation_South, ImPlotLegendFlags_Outside|ImPlotLegendFlags_Horizontal);\n        ImPlot::SetupAxes(NULL,NULL,ImPlotAxisFlags_AutoFit|ImPlotAxisFlags_NoDecorations,ImPlotAxisFlags_AutoFit|ImPlotAxisFlags_Invert);\n        ImPlot::SetupAxisTicks(ImAxis_Y1,0,19,20,politicians,false);\n        if (diverging)\n            ImPlot::PlotBarGroupsH(labels_div,data_div,9,20,0.75,0,ImPlotBarGroupsFlags_Stacked);\n        else\n            ImPlot::PlotBarGroupsH(labels_reg,data_reg,6,20,0.75,0,ImPlotBarGroupsFlags_Stacked);\n        ImPlot::EndPlot();\n    }\n    ImPlot::PopColormap();\n}\n\n//-----------------------------------------------------------------------------\n\nvoid ShowDemo_ErrorBars() {\n    static float xs[5]    = {1,2,3,4,5};\n    static float bar[5]   = {1,2,5,3,4};\n    static float lin1[5]  = {8,8,9,7,8};\n    static float lin2[5]  = {6,7,6,9,6};\n    static float err1[5]  = {0.2f, 0.4f, 0.2f, 0.6f, 0.4f};\n    static float err2[5]  = {0.4f, 0.2f, 0.4f, 0.8f, 0.6f};\n    static float err3[5]  = {0.09f, 0.14f, 0.09f, 0.12f, 0.16f};\n    static float err4[5]  = {0.02f, 0.08f, 0.15f, 0.05f, 0.2f};\n\n\n    if (ImPlot::BeginPlot(\"##ErrorBars\")) {\n        ImPlot::SetupAxesLimits(0, 6, 0, 10);\n        ImPlot::PlotBars(\"Bar\", xs, bar, 5, 0.5f);\n        ImPlot::PlotErrorBars(\"Bar\", xs, bar, err1, 5);\n        ImPlot::SetNextErrorBarStyle(ImPlot::GetColormapColor(1), 0);\n        ImPlot::PlotErrorBars(\"Line\", xs, lin1, err1, err2, 5);\n        ImPlot::SetNextMarkerStyle(ImPlotMarker_Circle);\n        ImPlot::PlotLine(\"Line\", xs, lin1, 5);\n        ImPlot::PushStyleColor(ImPlotCol_ErrorBar, ImPlot::GetColormapColor(2));\n        ImPlot::PlotErrorBars(\"Scatter\", xs, lin2, err2, 5);\n        ImPlot::PlotErrorBarsH(\"Scatter\", xs, lin2,  err3, err4, 5);\n        ImPlot::PopStyleColor();\n        ImPlot::PlotScatter(\"Scatter\", xs, lin2, 5);\n        ImPlot::EndPlot();\n    }\n}\n\nvoid ShowDemo_StemPlots() {\n    static double xs[51], ys1[51], ys2[51];\n    for (int i = 0; i < 51; ++i) {\n        xs[i] = i * 0.02;\n        ys1[i] = 1.0 + 0.5 * sin(25*xs[i])*cos(2*xs[i]);\n        ys2[i] = 0.5 + 0.25  * sin(10*xs[i]) * sin(xs[i]);\n    }\n    if (ImPlot::BeginPlot(\"Stem Plots\")) {\n        ImPlot::SetupAxisLimits(ImAxis_X1,0,1.0);\n        ImPlot::SetupAxisLimits(ImAxis_Y1,0,1.6);\n        ImPlot::PlotStems(\"Stems 1\",xs,ys1,51);\n        ImPlot::SetNextMarkerStyle(ImPlotMarker_Square,5);\n        ImPlot::PlotStems(\"Stems 2\", xs, ys2,51);\n        ImPlot::EndPlot();\n    }\n}\n\nvoid ShowDemo_InfiniteLines() {\n    static double vals[] = {0.25, 0.5, 0.75};\n    if (ImPlot::BeginPlot(\"##Infinite\")) {\n        ImPlot::SetupAxes(NULL,NULL,ImPlotAxisFlags_NoInitialFit,ImPlotAxisFlags_NoInitialFit);\n        ImPlot::PlotVLines(\"VLines\",vals,3);\n        ImPlot::PlotHLines(\"HLines\",vals,3);\n        ImPlot::EndPlot();\n    }\n}\n\nvoid ShowDemo_PieCharts() {\n    static const char* labels1[]   = {\"Frogs\",\"Hogs\",\"Dogs\",\"Logs\"};\n    static float data1[]           = {0.15f,  0.30f,  0.2f, 0.05f};\n    static bool normalize          = false;\n    ImGui::SetNextItemWidth(250);\n    ImGui::DragFloat4(\"Values\", data1, 0.01f, 0, 1);\n    if ((data1[0] + data1[1] + data1[2] + data1[3]) < 1) {\n        ImGui::SameLine();\n        ImGui::Checkbox(\"Normalize\", &normalize);\n    }\n\n    if (ImPlot::BeginPlot(\"##Pie1\", ImVec2(250,250), ImPlotFlags_Equal | ImPlotFlags_NoMouseText)) {\n        ImPlot::SetupAxes(NULL, NULL, ImPlotAxisFlags_NoDecorations, ImPlotAxisFlags_NoDecorations);\n        ImPlot::SetupAxesLimits(0, 1, 0, 1);\n        ImPlot::PlotPieChart(labels1, data1, 4, 0.5, 0.5, 0.4, normalize, \"%.2f\");\n        ImPlot::EndPlot();\n    }\n\n    ImGui::SameLine();\n\n    static const char* labels2[]   = {\"A\",\"B\",\"C\",\"D\",\"E\"};\n    static int data2[]             = {1,1,2,3,5};\n\n    ImPlot::PushColormap(ImPlotColormap_Pastel);\n    if (ImPlot::BeginPlot(\"##Pie2\", ImVec2(250,250), ImPlotFlags_Equal | ImPlotFlags_NoMouseText)) {\n        ImPlot::SetupAxes(NULL, NULL, ImPlotAxisFlags_NoDecorations, ImPlotAxisFlags_NoDecorations);\n        ImPlot::SetupAxesLimits(0, 1, 0, 1);\n        ImPlot::PlotPieChart(labels2, data2, 5, 0.5, 0.5, 0.4, true, \"%.0f\", 180);\n        ImPlot::EndPlot();\n    }\n    ImPlot::PopColormap();\n}\n\nvoid ShowDemo_Heatmaps() {\n    static float values1[7][7]  = {{0.8f, 2.4f, 2.5f, 3.9f, 0.0f, 4.0f, 0.0f},\n                                    {2.4f, 0.0f, 4.0f, 1.0f, 2.7f, 0.0f, 0.0f},\n                                    {1.1f, 2.4f, 0.8f, 4.3f, 1.9f, 4.4f, 0.0f},\n                                    {0.6f, 0.0f, 0.3f, 0.0f, 3.1f, 0.0f, 0.0f},\n                                    {0.7f, 1.7f, 0.6f, 2.6f, 2.2f, 6.2f, 0.0f},\n                                    {1.3f, 1.2f, 0.0f, 0.0f, 0.0f, 3.2f, 5.1f},\n                                    {0.1f, 2.0f, 0.0f, 1.4f, 0.0f, 1.9f, 6.3f}};\n    static float scale_min       = 0;\n    static float scale_max       = 6.3f;\n    static const char* xlabels[] = {\"C1\",\"C2\",\"C3\",\"C4\",\"C5\",\"C6\",\"C7\"};\n    static const char* ylabels[] = {\"R1\",\"R2\",\"R3\",\"R4\",\"R5\",\"R6\",\"R7\"};\n\n    static ImPlotColormap map = ImPlotColormap_Viridis;\n    if (ImPlot::ColormapButton(ImPlot::GetColormapName(map),ImVec2(225,0),map)) {\n        map = (map + 1) % ImPlot::GetColormapCount();\n        // We bust the color cache of our plots so that item colors will\n        // resample the new colormap in the event that they have already\n        // been created. See documentation in implot.h.\n        BustColorCache(\"##Heatmap1\");\n        BustColorCache(\"##Heatmap2\");\n    }\n\n    ImGui::SameLine();\n    ImGui::LabelText(\"##Colormap Index\", \"%s\", \"Change Colormap\");\n    ImGui::SetNextItemWidth(225);\n    ImGui::DragFloatRange2(\"Min / Max\",&scale_min, &scale_max, 0.01f, -20, 20);\n    static ImPlotAxisFlags axes_flags = ImPlotAxisFlags_Lock | ImPlotAxisFlags_NoGridLines | ImPlotAxisFlags_NoTickMarks;\n\n    ImPlot::PushColormap(map);\n\n    if (ImPlot::BeginPlot(\"##Heatmap1\",ImVec2(225,225),ImPlotFlags_NoLegend|ImPlotFlags_NoMouseText)) {\n        ImPlot::SetupAxes(NULL, NULL, axes_flags, axes_flags);\n        ImPlot::SetupAxisTicks(ImAxis_X1,0 + 1.0/14.0, 1 - 1.0/14.0, 7, xlabels);\n        ImPlot::SetupAxisTicks(ImAxis_Y1,1 - 1.0/14.0, 0 + 1.0/14.0, 7, ylabels);\n        ImPlot::PlotHeatmap(\"heat\",values1[0],7,7,scale_min,scale_max);\n        ImPlot::EndPlot();\n    }\n    ImGui::SameLine();\n    ImPlot::ColormapScale(\"##HeatScale\",scale_min, scale_max, ImVec2(60,225));\n\n    ImGui::SameLine();\n\n    const int size = 200;\n    static double values2[size*size];\n    srand((unsigned int)(ImGui::GetTime()*1000000));\n    for (int i = 0; i < size*size; ++i)\n        values2[i] = RandomRange(0.0,1.0);\n\n    if (ImPlot::BeginPlot(\"##Heatmap2\",ImVec2(225,225))) {\n        ImPlot::SetupAxes(NULL, NULL, ImPlotAxisFlags_NoDecorations, ImPlotAxisFlags_NoDecorations);\n        ImPlot::SetupAxesLimits(-1,1,-1,1);\n        ImPlot::PlotHeatmap(\"heat1\",values2,size,size,0,1,NULL);\n        ImPlot::PlotHeatmap(\"heat2\",values2,size,size,0,1,NULL, ImPlotPoint(-1,-1), ImPlotPoint(0,0));\n        ImPlot::EndPlot();\n    }\n    ImPlot::PopColormap();\n\n}\n\nvoid ShowDemo_Histogram() {\n    static int  bins       = 50;\n    static bool cumulative = false;\n    static bool density    = true;\n    static bool outliers   = true;\n    static double mu       = 5;\n    static double sigma    = 2;\n\n    ImGui::SetNextItemWidth(200);\n    if (ImGui::RadioButton(\"Sqrt\",bins==ImPlotBin_Sqrt))       { bins = ImPlotBin_Sqrt;    } ImGui::SameLine();\n    if (ImGui::RadioButton(\"Sturges\",bins==ImPlotBin_Sturges)) { bins = ImPlotBin_Sturges; } ImGui::SameLine();\n    if (ImGui::RadioButton(\"Rice\",bins==ImPlotBin_Rice))       { bins = ImPlotBin_Rice;    } ImGui::SameLine();\n    if (ImGui::RadioButton(\"Scott\",bins==ImPlotBin_Scott))     { bins = ImPlotBin_Scott;   } ImGui::SameLine();\n    if (ImGui::RadioButton(\"N Bins\",bins>=0))                       bins = 50;\n    if (bins>=0) {\n        ImGui::SameLine();\n        ImGui::SetNextItemWidth(200);\n        ImGui::SliderInt(\"##Bins\", &bins, 1, 100);\n    }\n    if (ImGui::Checkbox(\"Density\", &density))\n    {\n        ImPlot::SetNextAxisToFit(ImAxis_X1);\n        ImPlot::SetNextAxisToFit(ImAxis_Y1);\n    }\n    ImGui::SameLine();\n    if (ImGui::Checkbox(\"Cumulative\", &cumulative))\n    {\n        ImPlot::SetNextAxisToFit(ImAxis_X1);\n        ImPlot::SetNextAxisToFit(ImAxis_Y1);\n    }\n    ImGui::SameLine();\n    static bool range = false;\n    ImGui::Checkbox(\"Range\", &range);\n    static float rmin = -3;\n    static float rmax = 13;\n    if (range) {\n        ImGui::SameLine();\n        ImGui::SetNextItemWidth(200);\n        ImGui::DragFloat2(\"##Range\",&rmin,0.1f,-3,13);\n        ImGui::SameLine();\n        ImGui::Checkbox(\"Outliers\",&outliers);\n    }\n\n    static NormalDistribution<10000> dist(mu, sigma);\n    static double x[100];\n    static double y[100];\n    if (density) {\n        for (int i = 0; i < 100; ++i) {\n            x[i] = -3 + 16 * (double)i/99.0;\n            y[i] = exp( - (x[i]-mu)*(x[i]-mu) / (2*sigma*sigma)) / (sigma * sqrt(2*3.141592653589793238));\n        }\n        if (cumulative) {\n            for (int i = 1; i < 100; ++i)\n                y[i] += y[i-1];\n            for (int i = 0; i < 100; ++i)\n                y[i] /= y[99];\n        }\n    }\n\n    if (ImPlot::BeginPlot(\"##Histograms\")) {\n        ImPlot::SetNextFillStyle(IMPLOT_AUTO_COL, 0.5f);\n        ImPlot::PlotHistogram(\"Empirical\", dist.Data, 10000, bins, cumulative, density, range ? ImPlotRange(rmin,rmax) : ImPlotRange(), outliers);\n        if (density && outliers)\n            ImPlot::PlotLine(\"Theoretical\",x,y,100);\n        ImPlot::EndPlot();\n    }\n}\n\nvoid ShowDemo_Histogram2D() {\n    static int count     = 500000;\n    static int xybins[2] = {200,200};\n    static bool density2 = false;\n    ImGui::SliderInt(\"Count\",&count,100,500000);\n    ImGui::SliderInt2(\"Bins\",xybins,1,500);\n    ImGui::SameLine();\n    ImGui::Checkbox(\"Density##2\",&density2);\n    static NormalDistribution<500000> dist1(1, 2);\n    static NormalDistribution<500000> dist2(1, 1);\n    double max_count = 0;\n    ImPlotAxisFlags flags = ImPlotAxisFlags_AutoFit|ImPlotAxisFlags_Foreground;\n    ImPlot::PushColormap(\"Hot\");\n    if (ImPlot::BeginPlot(\"##Hist2D\",ImVec2(ImGui::GetContentRegionAvail().x-100-ImGui::GetStyle().ItemSpacing.x,0))) {\n        ImPlot::SetupAxes(NULL, NULL, flags, flags);\n        ImPlot::SetupAxesLimits(-6,6,-6,6);\n        max_count = ImPlot::PlotHistogram2D(\"Hist2D\",dist1.Data,dist2.Data,count,xybins[0],xybins[1],density2,ImPlotRect(-6,6,-6,6));\n        ImPlot::EndPlot();\n    }\n    ImGui::SameLine();\n    ImPlot::ColormapScale(density2 ? \"Density\" : \"Count\",0,max_count,ImVec2(100,0));\n    ImPlot::PopColormap();\n}\n\nvoid ShowDemo_DigitalPlots() {\n    ImGui::BulletText(\"Digital plots do not respond to Y drag and zoom, so that\");\n    ImGui::Indent();\n    ImGui::Text(\"you can drag analog plots over the rising/falling digital edge.\");\n    ImGui::Unindent();\n\n    static bool paused = false;\n    static ScrollingBuffer dataDigital[2];\n    static ScrollingBuffer dataAnalog[2];\n    static bool showDigital[2] = {true, false};\n    static bool showAnalog[2] = {true, false};\n\n    char label[32];\n    ImGui::Checkbox(\"digital_0\", &showDigital[0]); ImGui::SameLine();\n    ImGui::Checkbox(\"digital_1\", &showDigital[1]); ImGui::SameLine();\n    ImGui::Checkbox(\"analog_0\",  &showAnalog[0]);  ImGui::SameLine();\n    ImGui::Checkbox(\"analog_1\",  &showAnalog[1]);\n\n    static float t = 0;\n    if (!paused) {\n        t += ImGui::GetIO().DeltaTime;\n        //digital signal values\n        if (showDigital[0])\n            dataDigital[0].AddPoint(t, sinf(2*t) > 0.45);\n        if (showDigital[1])\n            dataDigital[1].AddPoint(t, sinf(2*t) < 0.45);\n        //Analog signal values\n        if (showAnalog[0])\n            dataAnalog[0].AddPoint(t, sinf(2*t));\n        if (showAnalog[1])\n            dataAnalog[1].AddPoint(t, cosf(2*t));\n    }\n    if (ImPlot::BeginPlot(\"##Digital\")) {\n        ImPlot::SetupAxisLimits(ImAxis_X1, t - 10.0, t, paused ? ImGuiCond_Once : ImGuiCond_Always);\n        ImPlot::SetupAxisLimits(ImAxis_Y1, -1, 1);\n        for (int i = 0; i < 2; ++i) {\n            if (showDigital[i] && dataDigital[i].Data.size() > 0) {\n                sprintf(label, \"digital_%d\", i);\n                ImPlot::PlotDigital(label, &dataDigital[i].Data[0].x, &dataDigital[i].Data[0].y, dataDigital[i].Data.size(), dataDigital[i].Offset, 2 * sizeof(float));\n            }\n        }\n        for (int i = 0; i < 2; ++i) {\n            if (showAnalog[i]) {\n                sprintf(label, \"analog_%d\", i);\n                if (dataAnalog[i].Data.size() > 0)\n                    ImPlot::PlotLine(label, &dataAnalog[i].Data[0].x, &dataAnalog[i].Data[0].y, dataAnalog[i].Data.size(), dataAnalog[i].Offset, 2 * sizeof(float));\n            }\n        }\n        ImPlot::EndPlot();\n    }\n}\n\nvoid ShowDemo_Images() {\n    ImGui::BulletText(\"Below we are displaying the font texture, which is the only texture we have\\naccess to in this demo.\");\n    ImGui::BulletText(\"Use the 'ImTextureID' type as storage to pass pointers or identifiers to your\\nown texture data.\");\n    ImGui::BulletText(\"See ImGui Wiki page 'Image Loading and Displaying Examples'.\");\n    static ImVec2 bmin(0,0);\n    static ImVec2 bmax(1,1);\n    static ImVec2 uv0(0,0);\n    static ImVec2 uv1(1,1);\n    static ImVec4 tint(1,1,1,1);\n    ImGui::SliderFloat2(\"Min\", &bmin.x, -2, 2, \"%.1f\");\n    ImGui::SliderFloat2(\"Max\", &bmax.x, -2, 2, \"%.1f\");\n    ImGui::SliderFloat2(\"UV0\", &uv0.x, -2, 2, \"%.1f\");\n    ImGui::SliderFloat2(\"UV1\", &uv1.x, -2, 2, \"%.1f\");\n    ImGui::ColorEdit4(\"Tint\",&tint.x);\n    if (ImPlot::BeginPlot(\"##image\")) {\n        ImPlot::PlotImage(\"my image\",ImGui::GetIO().Fonts->TexID, bmin, bmax, uv0, uv1, tint);\n        ImPlot::EndPlot();\n    }\n}\n\nvoid ShowDemo_RealtimePlots() {\n    ImGui::BulletText(\"Move your mouse to change the data!\");\n    ImGui::BulletText(\"This example assumes 60 FPS. Higher FPS requires larger buffer size.\");\n    static ScrollingBuffer sdata1, sdata2;\n    static RollingBuffer   rdata1, rdata2;\n    ImVec2 mouse = ImGui::GetMousePos();\n    static float t = 0;\n    t += ImGui::GetIO().DeltaTime;\n    sdata1.AddPoint(t, mouse.x * 0.0005f);\n    rdata1.AddPoint(t, mouse.x * 0.0005f);\n    sdata2.AddPoint(t, mouse.y * 0.0005f);\n    rdata2.AddPoint(t, mouse.y * 0.0005f);\n\n    static float history = 10.0f;\n    ImGui::SliderFloat(\"History\",&history,1,30,\"%.1f s\");\n    rdata1.Span = history;\n    rdata2.Span = history;\n\n    static ImPlotAxisFlags flags = ImPlotAxisFlags_NoTickLabels;\n\n    if (ImPlot::BeginPlot(\"##Scrolling\", ImVec2(-1,150))) {\n        ImPlot::SetupAxes(NULL, NULL, flags, flags);\n        ImPlot::SetupAxisLimits(ImAxis_X1,t - history, t, ImGuiCond_Always);\n        ImPlot::SetupAxisLimits(ImAxis_Y1,0,1);\n        ImPlot::SetNextFillStyle(IMPLOT_AUTO_COL,0.5f);\n        ImPlot::PlotShaded(\"Mouse X\", &sdata1.Data[0].x, &sdata1.Data[0].y, sdata1.Data.size(), -INFINITY, sdata1.Offset, 2 * sizeof(float));\n        ImPlot::PlotLine(\"Mouse Y\", &sdata2.Data[0].x, &sdata2.Data[0].y, sdata2.Data.size(), sdata2.Offset, 2*sizeof(float));\n        ImPlot::EndPlot();\n    }\n    if (ImPlot::BeginPlot(\"##Rolling\", ImVec2(-1,150))) {\n        ImPlot::SetupAxes(NULL, NULL, flags, flags);\n        ImPlot::SetupAxisLimits(ImAxis_X1,0,history, ImGuiCond_Always);\n        ImPlot::SetupAxisLimits(ImAxis_Y1,0,1);\n        ImPlot::PlotLine(\"Mouse X\", &rdata1.Data[0].x, &rdata1.Data[0].y, rdata1.Data.size(), 0, 2 * sizeof(float));\n        ImPlot::PlotLine(\"Mouse Y\", &rdata2.Data[0].x, &rdata2.Data[0].y, rdata2.Data.size(), 0, 2 * sizeof(float));\n        ImPlot::EndPlot();\n    }\n}\n\nvoid ShowDemo_MarkersAndText() {\n    static float mk_size = ImPlot::GetStyle().MarkerSize;\n    static float mk_weight = ImPlot::GetStyle().MarkerWeight;\n    ImGui::DragFloat(\"Marker Size\",&mk_size,0.1f,2.0f,10.0f,\"%.2f px\");\n    ImGui::DragFloat(\"Marker Weight\", &mk_weight,0.05f,0.5f,3.0f,\"%.2f px\");\n\n    if (ImPlot::BeginPlot(\"##MarkerStyles\", ImVec2(-1,0), ImPlotFlags_CanvasOnly)) {\n\n        ImPlot::SetupAxes(NULL, NULL, ImPlotAxisFlags_NoDecorations, ImPlotAxisFlags_NoDecorations);\n        ImPlot::SetupAxesLimits(0, 10, 0, 12);\n\n        ImS8 xs[2] = {1,4};\n        ImS8 ys[2] = {10,11};\n\n        // filled markers\n        for (int m = 0; m < ImPlotMarker_COUNT; ++m) {\n            ImGui::PushID(m);\n            ImPlot::SetNextMarkerStyle(m, mk_size, IMPLOT_AUTO_COL, mk_weight);\n            ImPlot::PlotLine(\"##Filled\", xs, ys, 2);\n            ImGui::PopID();\n            ys[0]--; ys[1]--;\n        }\n        xs[0] = 6; xs[1] = 9; ys[0] = 10; ys[1] = 11;\n        // open markers\n        for (int m = 0; m < ImPlotMarker_COUNT; ++m) {\n            ImGui::PushID(m);\n            ImPlot::SetNextMarkerStyle(m, mk_size, ImVec4(0,0,0,0), mk_weight);\n            ImPlot::PlotLine(\"##Open\", xs, ys, 2);\n            ImGui::PopID();\n            ys[0]--; ys[1]--;\n        }\n\n        ImPlot::PlotText(\"Filled Markers\", 2.5f, 6.0f);\n        ImPlot::PlotText(\"Open Markers\",   7.5f, 6.0f);\n\n        ImPlot::PushStyleColor(ImPlotCol_InlayText, ImVec4(1,0,1,1));\n        ImPlot::PlotText(\"Vertical Text\", 5.0f, 6.0f, true);\n        ImPlot::PopStyleColor();\n\n        ImPlot::EndPlot();\n    }\n}\n\nvoid ShowDemo_LogAxes() {\n    static double xs[1001], ys1[1001], ys2[1001], ys3[1001];\n    for (int i = 0; i < 1001; ++i) {\n        xs[i]  = i*0.1f;\n        ys1[i] = sin(xs[i]) + 1;\n        ys2[i] = log(xs[i]);\n        ys3[i] = pow(10.0, xs[i]);\n    }\n    ImGui::BulletText(\"Open the plot context menu (right click) to change scales.\");\n\n    if (ImPlot::BeginPlot(\"Log Plot\", ImVec2(-1,0))) {\n        ImPlot::SetupAxis(ImAxis_X1, NULL, ImPlotAxisFlags_LogScale);\n        ImPlot::SetupAxesLimits(0.1, 100, 0, 10);\n        ImPlot::PlotLine(\"f(x) = x\",        xs, xs,  1001);\n        ImPlot::PlotLine(\"f(x) = sin(x)+1\", xs, ys1, 1001);\n        ImPlot::PlotLine(\"f(x) = log(x)\",   xs, ys2, 1001);\n        ImPlot::PlotLine(\"f(x) = 10^x\",     xs, ys3, 21);\n        ImPlot::EndPlot();\n    }\n}\n\nvoid ShowDemo_TimeAxes() {\n\n    static double t_min = 1609459200; // 01/01/2021 @ 12:00:00am (UTC)\n    static double t_max = 1640995200; // 01/01/2022 @ 12:00:00am (UTC)\n\n    ImGui::BulletText(\"When ImPlotAxisFlags_Time is enabled on the X-Axis, values are interpreted as\\n\"\n                        \"UNIX timestamps in seconds and axis labels are formated as date/time.\");\n    ImGui::BulletText(\"By default, labels are in UTC time but can be set to use local time instead.\");\n\n    ImGui::Checkbox(\"Local Time\",&ImPlot::GetStyle().UseLocalTime);\n    ImGui::SameLine();\n    ImGui::Checkbox(\"ISO 8601\",&ImPlot::GetStyle().UseISO8601);\n    ImGui::SameLine();\n    ImGui::Checkbox(\"24 Hour Clock\",&ImPlot::GetStyle().Use24HourClock);\n\n    static HugeTimeData* data = NULL;\n    if (data == NULL) {\n        ImGui::SameLine();\n        if (ImGui::Button(\"Generate Huge Data (~500MB!)\")) {\n            static HugeTimeData sdata(t_min);\n            data = &sdata;\n        }\n    }\n\n    if (ImPlot::BeginPlot(\"##Time\", ImVec2(-1,0))) {\n        ImPlot::SetupAxis(ImAxis_X1, NULL, ImPlotAxisFlags_Time);\n        ImPlot::SetupAxesLimits(t_min,t_max,0,1);\n        if (data != NULL) {\n            // downsample our data\n            int downsample = (int)ImPlot::GetPlotLimits().X.Size() / 1000 + 1;\n            int start = (int)(ImPlot::GetPlotLimits().X.Min - t_min);\n            start = start < 0 ? 0 : start > HugeTimeData::Size - 1 ? HugeTimeData::Size - 1 : start;\n            int end = (int)(ImPlot::GetPlotLimits().X.Max - t_min) + 1000;\n            end = end < 0 ? 0 : end > HugeTimeData::Size - 1 ? HugeTimeData::Size - 1 : end;\n            int size = (end - start)/downsample;\n            // plot it\n            ImPlot::PlotLine(\"Time Series\", &data->Ts[start], &data->Ys[start], size, 0, sizeof(double)*downsample);\n        }\n        // plot time now\n        double t_now = (double)time(0);\n        double y_now = HugeTimeData::GetY(t_now);\n        ImPlot::PlotScatter(\"Now\",&t_now,&y_now,1);\n        ImPlot::Annotation(t_now,y_now,ImPlot::GetLastItemColor(),ImVec2(10,10),false,\"Now\");\n        ImPlot::EndPlot();\n    }\n}\n\nvoid ShowDemo_MultipleAxes() {\n    static float xs[1001], xs2[1001], ys1[1001], ys2[1001], ys3[1001];\n    for (int i = 0; i < 1001; ++i) {\n        xs[i]  = (i*0.1f);\n        xs2[i] = xs[i] + 10.0f;\n        ys1[i] = sinf(xs[i]) * 3 + 1;\n        ys2[i] = cosf(xs[i]) * 0.2f + 0.5f;\n        ys3[i] = sinf(xs[i]+0.5f) * 100 + 200;\n    }\n\n    static bool x2_axis = true;\n    static bool y2_axis = true;\n    static bool y3_axis = true;\n\n    ImGui::Checkbox(\"X-Axis 2\", &x2_axis);\n    ImGui::SameLine();\n    ImGui::Checkbox(\"Y-Axis 2\", &y2_axis);\n    ImGui::SameLine();\n    ImGui::Checkbox(\"Y-Axis 3\", &y3_axis);\n\n    ImGui::BulletText(\"You can drag axes to the opposite side of the plot.\");\n    ImGui::BulletText(\"Hover over legend items to see which axis they are plotted on.\");\n\n    if (ImPlot::BeginPlot(\"Multi-Axis Plot\", ImVec2(-1,0))) {\n        ImPlot::SetupAxes(\"X-Axis 1\", \"Y-Axis 1\");\n        ImPlot::SetupAxesLimits(0, 100, 0, 10);\n        if (x2_axis) {\n            ImPlot::SetupAxis(ImAxis_X2, \"X-Axis 2\",ImPlotAxisFlags_AuxDefault);\n            ImPlot::SetupAxisLimits(ImAxis_X2, 0, 100);\n        }\n        if (y2_axis) {\n            ImPlot::SetupAxis(ImAxis_Y2, \"Y-Axis 2\",ImPlotAxisFlags_AuxDefault);\n            ImPlot::SetupAxisLimits(ImAxis_Y2, 0, 1);\n        }\n        if (y3_axis) {\n            ImPlot::SetupAxis(ImAxis_Y3, \"Y-Axis 3\",ImPlotAxisFlags_AuxDefault);\n            ImPlot::SetupAxisLimits(ImAxis_Y3, 0, 300);\n        }\n\n        ImPlot::PlotLine(\"f(x) = x\", xs, xs, 1001);\n        if (x2_axis) {\n            ImPlot::SetAxes(ImAxis_X2, ImAxis_Y1);\n            ImPlot::PlotLine(\"f(x) = sin(x)*3+1\", xs2, ys1, 1001);\n        }\n        if (y2_axis) {\n            ImPlot::SetAxes(ImAxis_X1, ImAxis_Y2);\n            ImPlot::PlotLine(\"f(x) = cos(x)*.2+.5\", xs, ys2, 1001);\n        }\n        if (y3_axis) {\n            ImPlot::SetAxes(ImAxis_X2, ImAxis_Y3);\n            ImPlot::PlotLine(\"f(x) = sin(x+.5)*100+200 \", xs2, ys3, 1001);\n        }\n        ImPlot::EndPlot();\n    }\n}\n\nvoid ShowDemo_LinkedAxes() {\n    static ImPlotRect lims(0,1,0,1);\n    static bool linkx = true, linky = true;\n    int data[2] = {0,1};\n    ImGui::Checkbox(\"Link X\", &linkx);\n    ImGui::SameLine();\n    ImGui::Checkbox(\"Link Y\", &linky);\n\n    ImGui::DragScalarN(\"Limits\",ImGuiDataType_Double,&lims.X.Min,4,0.01f);\n\n    if (BeginAlignedPlots(\"AlignedGroup\")) {\n        if (ImPlot::BeginPlot(\"Plot A\")) {\n            ImPlot::SetupAxisLinks(ImAxis_X1, linkx ? &lims.X.Min : NULL, linkx ? &lims.X.Max : NULL);\n            ImPlot::SetupAxisLinks(ImAxis_Y1, linky ? &lims.Y.Min : NULL, linky ? &lims.Y.Max : NULL);\n            ImPlot::PlotLine(\"Line\",data,2);\n            ImPlot::EndPlot();\n        }\n        if (ImPlot::BeginPlot(\"Plot B\")) {\n            ImPlot::SetupAxisLinks(ImAxis_X1, linkx ? &lims.X.Min : NULL, linkx ? &lims.X.Max : NULL);\n            ImPlot::SetupAxisLinks(ImAxis_Y1, linky ? &lims.Y.Min : NULL, linky ? &lims.Y.Max : NULL);\n            ImPlot::PlotLine(\"Line\",data,2);\n            ImPlot::EndPlot();\n        }\n        ImPlot::EndAlignedPlots();\n    }\n}\n\nvoid ShowDemo_EqualAxes() {\n    ImGui::BulletText(\"Equal constraint applies to axis pairs (e.g ImAxis_X1/Y1, ImAxis_X2/Y2\");\n    static double xs1[360], ys1[360];\n    for (int i = 0; i < 360; ++i) {\n        double angle = i * 2 * PI / 359.0;\n        xs1[i] = cos(angle); ys1[i] = sin(angle);\n    }\n    float xs2[] = {-1,0,1,0,-1};\n    float ys2[] = {0,1,0,-1,0};\n    if (ImPlot::BeginPlot(\"##EqualAxes\",ImVec2(-1,0),ImPlotFlags_Equal)) {\n        ImPlot::SetupAxis(ImAxis_X2, NULL, ImPlotAxisFlags_AuxDefault);\n        ImPlot::SetupAxis(ImAxis_Y2, NULL, ImPlotAxisFlags_AuxDefault);\n        ImPlot::PlotLine(\"Circle\",xs1,ys1,360);\n        ImPlot::SetAxes(ImAxis_X2, ImAxis_Y2);\n        ImPlot::PlotLine(\"Diamond\",xs2,ys2,5);\n        ImPlot::EndPlot();\n    }\n}\n\nvoid ShowDemo_AutoFittingData() {\n    ImGui::BulletText(\"The Y-axis has been configured to auto-fit to only the data visible in X-axis range.\");\n    ImGui::BulletText(\"Zoom and pan the X-axis. Disable Stems to see a difference in fit.\");\n    ImGui::BulletText(\"If ImPlotAxisFlags_RangeFit is disabled, the axis will fit ALL data.\");\n\n    static ImPlotAxisFlags xflags = ImPlotAxisFlags_None;\n    static ImPlotAxisFlags yflags = ImPlotAxisFlags_AutoFit|ImPlotAxisFlags_RangeFit;\n\n    ImGui::TextUnformatted(\"X: \"); ImGui::SameLine();\n    ImGui::CheckboxFlags(\"ImPlotAxisFlags_AutoFit##X\", (unsigned int*)&xflags, ImPlotAxisFlags_AutoFit); ImGui::SameLine();\n    ImGui::CheckboxFlags(\"ImPlotAxisFlags_RangeFit##X\", (unsigned int*)&xflags, ImPlotAxisFlags_RangeFit);\n\n    ImGui::TextUnformatted(\"Y: \"); ImGui::SameLine();\n    ImGui::CheckboxFlags(\"ImPlotAxisFlags_AutoFit##Y\", (unsigned int*)&yflags, ImPlotAxisFlags_AutoFit); ImGui::SameLine();\n    ImGui::CheckboxFlags(\"ImPlotAxisFlags_RangeFit##Y\", (unsigned int*)&yflags, ImPlotAxisFlags_RangeFit);\n\n    static double data[101];\n    srand(0);\n    for (int i = 0; i < 101; ++i)\n        data[i] = 1 + sin(i/10.0f);\n\n    if (ImPlot::BeginPlot(\"##DataFitting\")) {\n        ImPlot::SetupAxes(\"X\",\"Y\",xflags,yflags);\n        ImPlot::PlotLine(\"Line\",data,101);\n        ImPlot::PlotStems(\"Stems\",data,101);\n        ImPlot::EndPlot();\n    };\n}\n\nImPlotPoint SinewaveGetter(void* data, int i) {\n    float f = *(float*)data;\n    return ImPlotPoint(i,sinf(f*i));\n}\n\nvoid ShowDemo_SubplotsSizing() {\n\n    static ImPlotSubplotFlags flags = ImPlotSubplotFlags_None;\n    ImGui::CheckboxFlags(\"ImPlotSubplotFlags_NoResize\", (unsigned int*)&flags, ImPlotSubplotFlags_NoResize);\n    ImGui::CheckboxFlags(\"ImPlotSubplotFlags_NoTitle\", (unsigned int*)&flags, ImPlotSubplotFlags_NoTitle);\n\n    static int rows = 3;\n    static int cols = 3;\n    ImGui::SliderInt(\"Rows\",&rows,1,5);\n    ImGui::SliderInt(\"Cols\",&cols,1,5);\n    static float rratios[] = {5,1,1,1,1,1};\n    static float cratios[] = {5,1,1,1,1,1};\n    ImGui::DragScalarN(\"Row Ratios\",ImGuiDataType_Float,rratios,rows,0.01f,0);\n    ImGui::DragScalarN(\"Col Ratios\",ImGuiDataType_Float,cratios,cols,0.01f,0);\n    if (ImPlot::BeginSubplots(\"My Subplots\", rows, cols, ImVec2(-1,400), flags, rratios, cratios)) {\n        for (int i = 0; i < rows*cols; ++i) {\n            if (ImPlot::BeginPlot(\"\",ImVec2(),ImPlotFlags_NoLegend)) {\n                ImPlot::SetupAxes(NULL,NULL,ImPlotAxisFlags_NoDecorations,ImPlotAxisFlags_NoDecorations);\n                float fi = 0.01f * (i+1);\n                ImPlot::SetNextLineStyle(SampleColormap((float)i/(float)(rows*cols-1),ImPlotColormap_Jet));\n                ImPlot::PlotLineG(\"data\",SinewaveGetter,&fi,1000);\n                ImPlot::EndPlot();\n            }\n        }\n        ImPlot::EndSubplots();\n    }\n}\n\nvoid ShowDemo_SubplotItemSharing() {\n    static ImPlotSubplotFlags flags = ImPlotSubplotFlags_ShareItems;\n    ImGui::CheckboxFlags(\"ImPlotSubplotFlags_ShareItems\", (unsigned int*)&flags, ImPlotSubplotFlags_ShareItems);\n    ImGui::CheckboxFlags(\"ImPlotSubplotFlags_ColMajor\", (unsigned int*)&flags, ImPlotSubplotFlags_ColMajor);\n    ImGui::BulletText(\"Drag and drop items from the legend onto plots (except for 'common')\");\n    static int rows = 2;\n    static int cols = 3;\n    static int id[] = {0,1,2,3,4,5};\n    static int curj = -1;\n    if (ImPlot::BeginSubplots(\"##ItemSharing\", rows, cols, ImVec2(-1,400), flags)) {\n        for (int i = 0; i < rows*cols; ++i) {\n            if (ImPlot::BeginPlot(\"\")) {\n                float fc = 0.01f;\n                ImPlot::PlotLineG(\"common\",SinewaveGetter,&fc,1000);\n                for (int j = 0; j < 6; ++j) {\n                    if (id[j] == i) {\n                        char label[8];\n                        float fj = 0.01f * (j+2);\n                        sprintf(label, \"data%d\", j);\n                        ImPlot::PlotLineG(label,SinewaveGetter,&fj,1000);\n                        if (ImPlot::BeginDragDropSourceItem(label)) {\n                            curj = j;\n                            ImGui::SetDragDropPayload(\"MY_DND\",NULL,0);\n                            ImPlot::ItemIcon(GetLastItemColor()); ImGui::SameLine();\n                            ImGui::TextUnformatted(label);\n                            ImPlot::EndDragDropSource();\n                        }\n                    }\n                }\n                if (ImPlot::BeginDragDropTargetPlot()) {\n                    if (ImGui::AcceptDragDropPayload(\"MY_DND\"))\n                        id[curj] = i;\n                    ImPlot::EndDragDropTarget();\n                }\n                ImPlot::EndPlot();\n            }\n        }\n        ImPlot::EndSubplots();\n    }\n}\n\nvoid ShowDemo_SubplotAxisLinking() {\n    static ImPlotSubplotFlags flags = ImPlotSubplotFlags_LinkRows | ImPlotSubplotFlags_LinkCols;\n    ImGui::CheckboxFlags(\"ImPlotSubplotFlags_LinkRows\", (unsigned int*)&flags, ImPlotSubplotFlags_LinkRows);\n    ImGui::CheckboxFlags(\"ImPlotSubplotFlags_LinkCols\", (unsigned int*)&flags, ImPlotSubplotFlags_LinkCols);\n    ImGui::CheckboxFlags(\"ImPlotSubplotFlags_LinkAllX\", (unsigned int*)&flags, ImPlotSubplotFlags_LinkAllX);\n    ImGui::CheckboxFlags(\"ImPlotSubplotFlags_LinkAllY\", (unsigned int*)&flags, ImPlotSubplotFlags_LinkAllY);\n\n    static int rows = 2;\n    static int cols = 2;\n    if (ImPlot::BeginSubplots(\"##AxisLinking\", rows, cols, ImVec2(-1,400), flags)) {\n        for (int i = 0; i < rows*cols; ++i) {\n            if (ImPlot::BeginPlot(\"\")) {\n                ImPlot::SetupAxesLimits(0,1000,-1,1);\n                float fc = 0.01f;\n                ImPlot::PlotLineG(\"common\",SinewaveGetter,&fc,1000);\n                ImPlot::EndPlot();\n            }\n        }\n        ImPlot::EndSubplots();\n    }\n}\n\n\nvoid ShowDemo_LegendOptions() {\n    static ImPlotLocation loc = ImPlotLocation_East;\n    static bool h = false; static bool o = true;\n    ImGui::CheckboxFlags(\"North\", (unsigned int*)&loc, ImPlotLocation_North); ImGui::SameLine();\n    ImGui::CheckboxFlags(\"South\", (unsigned int*)&loc, ImPlotLocation_South); ImGui::SameLine();\n    ImGui::CheckboxFlags(\"West\",  (unsigned int*)&loc, ImPlotLocation_West);  ImGui::SameLine();\n    ImGui::CheckboxFlags(\"East\",  (unsigned int*)&loc, ImPlotLocation_East);  ImGui::SameLine();\n    ImGui::Checkbox(\"Horizontal##2\", &h); ImGui::SameLine();\n    ImGui::Checkbox(\"Outside\", &o);\n\n    ImGui::SliderFloat2(\"LegendPadding\", (float*)&GetStyle().LegendPadding, 0.0f, 20.0f, \"%.0f\");\n    ImGui::SliderFloat2(\"LegendInnerPadding\", (float*)&GetStyle().LegendInnerPadding, 0.0f, 10.0f, \"%.0f\");\n    ImGui::SliderFloat2(\"LegendSpacing\", (float*)&GetStyle().LegendSpacing, 0.0f, 5.0f, \"%.0f\");\n\n    if (ImPlot::BeginPlot(\"##Legend\",ImVec2(-1,0))) {\n        ImPlotLegendFlags flags = ImPlotLegendFlags_None;\n        if (h) flags |= ImPlotLegendFlags_Horizontal;\n        if (o) flags |= ImPlotLegendFlags_Outside;\n        ImPlot::SetupLegend(loc, flags);\n        static MyImPlot::WaveData data1(0.001, 0.2, 2, 0.75);\n        static MyImPlot::WaveData data2(0.001, 0.2, 4, 0.25);\n        static MyImPlot::WaveData data3(0.001, 0.2, 6, 0.5);\n        ImPlot::PlotLineG(\"Item 1\", MyImPlot::SineWave, &data1, 1000);         // \"Item 1\" added to legend\n        ImPlot::PlotLineG(\"Item 2##IDText\", MyImPlot::SawWave, &data2, 1000);  // \"Item 2\" added to legend, text after ## used for ID only\n        ImPlot::PlotLineG(\"##NotListed\", MyImPlot::SawWave, &data3, 1000);     // plotted, but not added to legend\n        ImPlot::PlotLineG(\"Item 3\", MyImPlot::SineWave, &data1, 1000);         // \"Item 3\" added to legend\n        ImPlot::PlotLineG(\"Item 3\", MyImPlot::SawWave,  &data2, 1000);         // combined with previous \"Item 3\"\n        ImPlot::EndPlot();\n    }\n}\n\nvoid ShowDemo_DragPoints() {\n    ImGui::BulletText(\"Click and drag each point.\");\n    static ImPlotDragToolFlags flags = ImPlotDragToolFlags_None;\n    ImGui::CheckboxFlags(\"NoCursors\", (unsigned int*)&flags, ImPlotDragToolFlags_NoCursors); ImGui::SameLine();\n    ImGui::CheckboxFlags(\"NoFit\", (unsigned int*)&flags, ImPlotDragToolFlags_NoFit); ImGui::SameLine();\n    ImGui::CheckboxFlags(\"NoInput\", (unsigned int*)&flags, ImPlotDragToolFlags_NoInputs);\n    ImPlotAxisFlags ax_flags = ImPlotAxisFlags_NoTickLabels | ImPlotAxisFlags_NoTickMarks;\n    if (ImPlot::BeginPlot(\"##Bezier\",ImVec2(-1,0),ImPlotFlags_CanvasOnly)) {\n        ImPlot::SetupAxes(0,0,ax_flags,ax_flags);\n        ImPlot::SetupAxesLimits(0,1,0,1);\n        static ImPlotPoint P[] = {ImPlotPoint(.05f,.05f), ImPlotPoint(0.2,0.4),  ImPlotPoint(0.8,0.6),  ImPlotPoint(.95f,.95f)};\n\n        ImPlot::DragPoint(0,&P[0].x,&P[0].y, ImVec4(0,0.9f,0,1),4,flags);\n        ImPlot::DragPoint(1,&P[1].x,&P[1].y, ImVec4(1,0.5f,1,1),4,flags);\n        ImPlot::DragPoint(2,&P[2].x,&P[2].y, ImVec4(0,0.5f,1,1),4,flags);\n        ImPlot::DragPoint(3,&P[3].x,&P[3].y, ImVec4(0,0.9f,0,1),4,flags);\n\n        static ImPlotPoint B[100];\n        for (int i = 0; i < 100; ++i) {\n            double t  = i / 99.0;\n            double u  = 1 - t;\n            double w1 = u*u*u;\n            double w2 = 3*u*u*t;\n            double w3 = 3*u*t*t;\n            double w4 = t*t*t;\n            B[i] = ImPlotPoint(w1*P[0].x + w2*P[1].x + w3*P[2].x + w4*P[3].x, w1*P[0].y + w2*P[1].y + w3*P[2].y + w4*P[3].y);\n        }\n\n\n        ImPlot::SetNextLineStyle(ImVec4(1,0.5f,1,1));\n        ImPlot::PlotLine(\"##h1\",&P[0].x, &P[0].y, 2, 0, sizeof(ImPlotPoint));\n        ImPlot::SetNextLineStyle(ImVec4(0,0.5f,1,1));\n        ImPlot::PlotLine(\"##h2\",&P[2].x, &P[2].y, 2, 0, sizeof(ImPlotPoint));\n        ImPlot::SetNextLineStyle(ImVec4(0,0.9f,0,1), 2);\n        ImPlot::PlotLine(\"##bez\",&B[0].x, &B[0].y, 100, 0, sizeof(ImPlotPoint));\n\n        ImPlot::EndPlot();\n    }\n}\n\nvoid ShowDemo_DragLines() {\n    ImGui::BulletText(\"Click and drag the horizontal and vertical lines.\");\n    static double x1 = 0.2;\n    static double x2 = 0.8;\n    static double y1 = 0.25;\n    static double y2 = 0.75;\n    static double f = 0.1;\n    static ImPlotDragToolFlags flags = ImPlotDragToolFlags_None;\n    ImGui::CheckboxFlags(\"NoCursors\", (unsigned int*)&flags, ImPlotDragToolFlags_NoCursors); ImGui::SameLine();\n    ImGui::CheckboxFlags(\"NoFit\", (unsigned int*)&flags, ImPlotDragToolFlags_NoFit); ImGui::SameLine();\n    ImGui::CheckboxFlags(\"NoInput\", (unsigned int*)&flags, ImPlotDragToolFlags_NoInputs);\n    if (ImPlot::BeginPlot(\"##lines\",ImVec2(-1,0))) {\n        ImPlot::SetupAxesLimits(0,1,0,1);\n        ImPlot::DragLineX(0,&x1,ImVec4(1,1,1,1),1,flags);\n        ImPlot::DragLineX(1,&x2,ImVec4(1,1,1,1),1,flags);\n        ImPlot::DragLineY(2,&y1,ImVec4(1,1,1,1),1,flags);\n        ImPlot::DragLineY(3,&y2,ImVec4(1,1,1,1),1,flags);\n        double xs[1000], ys[1000];\n        for (int i = 0; i < 1000; ++i) {\n            xs[i] = (x2+x1)/2+fabs(x2-x1)*(i/1000.0f - 0.5f);\n            ys[i] = (y1+y2)/2+fabs(y2-y1)/2*sin(f*i/10);\n        }\n        ImPlot::PlotLine(\"Interactive Data\", xs, ys, 1000);\n        ImPlot::DragLineY(120482,&f,ImVec4(1,0.5f,1,1),1,flags);\n        ImPlot::EndPlot();\n    }\n}\n\nvoid ShowDemo_DragRects() {\n\n    static float x_data[512];\n    static float y_data1[512];\n    static float y_data2[512];\n    static float y_data3[512];\n    static float sampling_freq = 44100;\n    static float freq = 500;\n    for (size_t i = 0; i < 512; ++i) {\n        const float t = i / sampling_freq;\n        x_data[i] = t;\n        const float arg = 2 * 3.14f * freq * t;\n        y_data1[i] = sinf(arg);\n        y_data2[i] = y_data1[i] * -0.6f + sinf(2 * arg) * 0.4f;\n        y_data3[i] = y_data2[i] * -0.6f + sinf(3 * arg) * 0.4f;\n    }\n    ImGui::BulletText(\"Click and drag the edges, corners, and center of the rect.\");\n    static ImPlotRect rect(0.0025,0.0045,0,0.5);\n    static ImPlotDragToolFlags flags = ImPlotDragToolFlags_None;\n    ImGui::CheckboxFlags(\"NoCursors\", (unsigned int*)&flags, ImPlotDragToolFlags_NoCursors); ImGui::SameLine();\n    ImGui::CheckboxFlags(\"NoFit\", (unsigned int*)&flags, ImPlotDragToolFlags_NoFit); ImGui::SameLine();\n    ImGui::CheckboxFlags(\"NoInput\", (unsigned int*)&flags, ImPlotDragToolFlags_NoInputs);\n\n    if (ImPlot::BeginPlot(\"##Main\",ImVec2(-1,150))) {\n        ImPlot::SetupAxes(NULL,NULL,ImPlotAxisFlags_NoTickLabels,ImPlotAxisFlags_NoTickLabels);\n        ImPlot::SetupAxesLimits(0,0.01,-1,1);\n        ImPlot::PlotLine(\"Signal 1\", x_data, y_data1, 512);\n        ImPlot::PlotLine(\"Signal 2\", x_data, y_data2, 512);\n        ImPlot::PlotLine(\"Signal 3\", x_data, y_data3, 512);\n        ImPlot::DragRect(0,&rect.X.Min,&rect.Y.Min,&rect.X.Max,&rect.Y.Max,ImVec4(1,0,1,1),flags);\n        ImPlot::EndPlot();\n    }\n    if (ImPlot::BeginPlot(\"##rect\",ImVec2(-1,150), ImPlotFlags_CanvasOnly)) {\n        ImPlot::SetupAxes(NULL,NULL,ImPlotAxisFlags_NoDecorations,ImPlotAxisFlags_NoDecorations);\n        ImPlot::SetupAxesLimits(rect.X.Min, rect.X.Max, rect.Y.Min, rect.Y.Max, ImGuiCond_Always);\n        ImPlot::PlotLine(\"Signal 1\", x_data, y_data1, 512);\n        ImPlot::PlotLine(\"Signal 2\", x_data, y_data2, 512);\n        ImPlot::PlotLine(\"Signal 3\", x_data, y_data3, 512);\n        ImPlot::EndPlot();\n    }\n}\n\nImPlotPoint FindCentroid(const ImVector<ImPlotPoint>& data, ImPlotRect& bounds, int& cnt) {\n    cnt = 0;\n    ImPlotPoint avg;\n    for (int i = 0; i < data.size(); ++i) {\n        if (bounds.Contains(data[i].x, data[i].y)) {\n            avg.x += data[i].x;\n            avg.y += data[i].y;\n            cnt++;\n        }\n    }\n    if (cnt > 0) {\n        avg.x = avg.x / cnt;\n        avg.y = avg.y / cnt;\n    }\n    return avg;\n}\n\nvoid ShowDemo_Querying() {\n    static ImVector<ImPlotPoint> data;\n    static ImVector<ImPlotRect> rects;\n    static ImPlotRect limits, select;\n    static bool init = true;\n    if (init) {\n        for (int i = 0; i < 50; ++i)\n        {\n            double x = RandomRange(0.1, 0.9);\n            double y = RandomRange(0.1, 0.9);\n            data.push_back(ImPlotPoint(x,y));\n        }\n        init = false;\n    }\n\n    ImGui::BulletText(\"Box select and left click mouse to create a new query rect.\");\n    ImGui::BulletText(\"Ctrl + click in the plot area to draw points.\");\n\n    if (ImGui::Button(\"Clear Queries\"))\n        rects.shrink(0);\n\n    if (ImPlot::BeginPlot(\"##Centroid\")) {\n        ImPlot::SetupAxesLimits(0,1,0,1);\n        if (ImPlot::IsPlotHovered() && ImGui::IsMouseClicked(0) && ImGui::GetIO().KeyCtrl) {\n            ImPlotPoint pt = ImPlot::GetPlotMousePos();\n            data.push_back(pt);\n        }\n        ImPlot::PlotScatter(\"Points\", &data[0].x, &data[0].y, data.size(), 0, 2 * sizeof(double));\n        if (ImPlot::IsPlotSelected()) {\n            select = ImPlot::GetPlotSelection();\n            int cnt;\n            ImPlotPoint centroid = FindCentroid(data,select,cnt);\n            if (cnt > 0) {\n                ImPlot::SetNextMarkerStyle(ImPlotMarker_Square,6);\n                ImPlot::PlotScatter(\"Centroid\", &centroid.x, &centroid.y, 1);\n            }\n            if (ImGui::IsMouseClicked(ImPlot::GetInputMap().SelectCancel)) {\n                CancelPlotSelection();\n                rects.push_back(select);\n            }\n        }\n        for (int i = 0; i < rects.size(); ++i) {\n            int cnt;\n            ImPlotPoint centroid = FindCentroid(data,rects[i],cnt);\n            if (cnt > 0) {\n                ImPlot::SetNextMarkerStyle(ImPlotMarker_Square,6);\n                ImPlot::PlotScatter(\"Centroid\", &centroid.x, &centroid.y, 1);\n            }\n            ImPlot::DragRect(i,&rects[i].X.Min,&rects[i].Y.Min,&rects[i].X.Max,&rects[i].Y.Max,ImVec4(1,0,1,1));\n        }\n        limits  = ImPlot::GetPlotLimits();\n        ImPlot::EndPlot();\n    }\n}\n\nvoid ShowDemo_Annotations() {\n    static bool clamp = false;\n    ImGui::Checkbox(\"Clamp\",&clamp);\n    if (ImPlot::BeginPlot(\"##Annotations\")) {\n        ImPlot::SetupAxesLimits(0,2,0,1);\n        static float p[] = {0.25f, 0.25f, 0.75f, 0.75f, 0.25f};\n        ImPlot::PlotScatter(\"##Points\",&p[0],&p[1],4);\n        ImVec4 col = GetLastItemColor();\n        ImPlot::Annotation(0.25,0.25,col,ImVec2(-15,15),clamp,\"BL\");\n        ImPlot::Annotation(0.75,0.25,col,ImVec2(15,15),clamp,\"BR\");\n        ImPlot::Annotation(0.75,0.75,col,ImVec2(15,-15),clamp,\"TR\");\n        ImPlot::Annotation(0.25,0.75,col,ImVec2(-15,-15),clamp,\"TL\");\n        ImPlot::Annotation(0.5,0.5,col,ImVec2(0,0),clamp,\"Center\");\n\n        ImPlot::Annotation(1.25,0.75,ImVec4(0,1,0,1),ImVec2(0,0),clamp);\n\n        float bx[] = {1.2f,1.5f,1.8f};\n        float by[] = {0.25f, 0.5f, 0.75f};\n        ImPlot::PlotBars(\"##Bars\",bx,by,3,0.2);\n        for (int i = 0; i < 3; ++i)\n            ImPlot::Annotation(bx[i],by[i],ImVec4(0,0,0,0),ImVec2(0,-5),clamp,\"B[%d]=%.2f\",i,by[i]);\n        ImPlot::EndPlot();\n    }\n}\n\nvoid ShowDemo_Tags() {\n    static bool show = true;\n    ImGui::Checkbox(\"Show Tags\",&show);\n    if (ImPlot::BeginPlot(\"##Tags\")) {\n        ImPlot::SetupAxis(ImAxis_X2);\n        ImPlot::SetupAxis(ImAxis_Y2);\n        if (show) {\n            ImPlot::TagX(0.25, ImVec4(1,1,0,1));\n            ImPlot::TagY(0.75, ImVec4(1,1,0,1));\n            static double drag_tag = 0.25;\n            ImPlot::DragLineY(0,&drag_tag,ImVec4(1,0,0,1),1,ImPlotDragToolFlags_NoFit);\n            ImPlot::TagY(drag_tag, ImVec4(1,0,0,1), \"Drag\");\n            SetAxes(ImAxis_X2, ImAxis_Y2);\n            ImPlot::TagX(0.5, ImVec4(0,1,1,1), \"%s\", \"MyTag\");\n            ImPlot::TagY(0.5, ImVec4(0,1,1,1), \"Tag: %d\", 42);\n        }\n        ImPlot::EndPlot();\n    }\n}\n\nvoid ShowDemo_DragAndDrop() {\n    ImGui::BulletText(\"Drag/drop items from the left column.\");\n    ImGui::BulletText(\"Drag/drop items between plots.\");\n    ImGui::Indent();\n    ImGui::BulletText(\"Plot 1 Targets: Plot, Y-Axes, Legend\");\n    ImGui::BulletText(\"Plot 1 Sources: Legend Item Labels\");\n    ImGui::BulletText(\"Plot 2 Targets: Plot, X-Axis, Y-Axis\");\n    ImGui::BulletText(\"Plot 2 Sources: Plot, X-Axis, Y-Axis (hold Ctrl)\");\n    ImGui::Unindent();\n\n    // convenience struct to manage DND items; do this however you like\n    struct MyDndItem {\n        int              Idx;\n        int              Plt;\n        ImAxis           Yax;\n        char             Label[16];\n        ImVector<ImVec2> Data;\n        ImVec4           Color;\n        MyDndItem()        {\n            static int i = 0;\n            Idx = i++;\n            Plt = 0;\n            Yax = ImAxis_Y1;\n            sprintf(Label, \"%02d Hz\", Idx+1);\n            Color = RandomColor();\n            Data.reserve(1001);\n            for (int k = 0; k < 1001; ++k) {\n                float t = k * 1.0f / 999;\n                Data.push_back(ImVec2(t, 0.5f + 0.5f * sinf(2*3.14f*t*(Idx+1))));\n            }\n        }\n        void Reset() { Plt = 0; Yax = ImAxis_Y1; }\n    };\n\n    const int         k_dnd = 20;\n    static MyDndItem  dnd[k_dnd];\n    static MyDndItem* dndx = NULL; // for plot 2\n    static MyDndItem* dndy = NULL; // for plot 2\n\n    // child window to serve as initial source for our DND items\n    ImGui::BeginChild(\"DND_LEFT\",ImVec2(100,400));\n    if (ImGui::Button(\"Reset Data\")) {\n        for (int k = 0; k < k_dnd; ++k)\n            dnd[k].Reset();\n        dndx = dndy = NULL;\n    }\n    for (int k = 0; k < k_dnd; ++k) {\n        if (dnd[k].Plt > 0)\n            continue;\n        ImPlot::ItemIcon(dnd[k].Color); ImGui::SameLine();\n        ImGui::Selectable(dnd[k].Label, false, 0, ImVec2(100, 0));\n        if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_None)) {\n            ImGui::SetDragDropPayload(\"MY_DND\", &k, sizeof(int));\n            ImPlot::ItemIcon(dnd[k].Color); ImGui::SameLine();\n            ImGui::TextUnformatted(dnd[k].Label);\n            ImGui::EndDragDropSource();\n        }\n    }\n    ImGui::EndChild();\n    if (ImGui::BeginDragDropTarget()) {\n        if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload(\"MY_DND\")) {\n            int i = *(int*)payload->Data; dnd[i].Reset();\n        }\n        ImGui::EndDragDropTarget();\n    }\n\n    ImGui::SameLine();\n    ImGui::BeginChild(\"DND_RIGHT\",ImVec2(-1,400));\n    // plot 1 (time series)\n    ImPlotAxisFlags flags = ImPlotAxisFlags_NoTickLabels | ImPlotAxisFlags_NoGridLines;\n    if (ImPlot::BeginPlot(\"##DND1\", ImVec2(-1,195))) {\n        ImPlot::SetupAxis(ImAxis_X1, NULL, flags|ImPlotAxisFlags_Lock);\n        ImPlot::SetupAxis(ImAxis_Y1, \"[drop here]\", flags);\n        ImPlot::SetupAxis(ImAxis_Y2, \"[drop here]\", flags|ImPlotAxisFlags_Opposite);\n        ImPlot::SetupAxis(ImAxis_Y3, \"[drop here]\", flags|ImPlotAxisFlags_Opposite);\n\n        for (int k = 0; k < k_dnd; ++k) {\n            if (dnd[k].Plt == 1 && dnd[k].Data.size() > 0) {\n                ImPlot::SetAxis(dnd[k].Yax);\n                ImPlot::SetNextLineStyle(dnd[k].Color);\n                ImPlot::PlotLine(dnd[k].Label, &dnd[k].Data[0].x, &dnd[k].Data[0].y, dnd[k].Data.size(), 0, 2 * sizeof(float));\n                // allow legend item labels to be DND sources\n                if (ImPlot::BeginDragDropSourceItem(dnd[k].Label)) {\n                    ImGui::SetDragDropPayload(\"MY_DND\", &k, sizeof(int));\n                    ImPlot::ItemIcon(dnd[k].Color); ImGui::SameLine();\n                    ImGui::TextUnformatted(dnd[k].Label);\n                    ImPlot::EndDragDropSource();\n                }\n            }\n        }\n        // allow the main plot area to be a DND target\n        if (ImPlot::BeginDragDropTargetPlot()) {\n            if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload(\"MY_DND\")) {\n                int i = *(int*)payload->Data; dnd[i].Plt = 1; dnd[i].Yax = ImAxis_Y1;\n            }\n            ImPlot::EndDragDropTarget();\n        }\n        // allow each y-axis to be a DND target\n        for (int y = ImAxis_Y1; y <= ImAxis_Y3; ++y) {\n            if (ImPlot::BeginDragDropTargetAxis(y)) {\n                if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload(\"MY_DND\")) {\n                    int i = *(int*)payload->Data; dnd[i].Plt = 1; dnd[i].Yax = y;\n                }\n                ImPlot::EndDragDropTarget();\n            }\n        }\n        // allow the legend to be a DND target\n        if (ImPlot::BeginDragDropTargetLegend()) {\n            if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload(\"MY_DND\")) {\n                int i = *(int*)payload->Data; dnd[i].Plt = 1; dnd[i].Yax = ImAxis_Y1;\n            }\n            ImPlot::EndDragDropTarget();\n        }\n        ImPlot::EndPlot();\n    }\n    // plot 2 (Lissajous)\n    if (ImPlot::BeginPlot(\"##DND2\", ImVec2(-1,195))) {\n        ImPlot::PushStyleColor(ImPlotCol_AxisBg, dndx != NULL ? dndx->Color : ImPlot::GetStyle().Colors[ImPlotCol_AxisBg]);\n        ImPlot::SetupAxis(ImAxis_X1, dndx == NULL ? \"[drop here]\" : dndx->Label, flags);\n        ImPlot::PushStyleColor(ImPlotCol_AxisBg, dndy != NULL ? dndy->Color : ImPlot::GetStyle().Colors[ImPlotCol_AxisBg]);\n        ImPlot::SetupAxis(ImAxis_Y1, dndy == NULL ? \"[drop here]\" : dndy->Label, flags);\n        ImPlot::PopStyleColor(2);\n        if (dndx != NULL && dndy != NULL) {\n            ImVec4 mixed((dndx->Color.x + dndy->Color.x)/2,(dndx->Color.y + dndy->Color.y)/2,(dndx->Color.z + dndy->Color.z)/2,(dndx->Color.w + dndy->Color.w)/2);\n            ImPlot::SetNextLineStyle(mixed);\n            ImPlot::PlotLine(\"##dndxy\", &dndx->Data[0].y, &dndy->Data[0].y, dndx->Data.size(), 0, 2 * sizeof(float));\n        }\n        // allow the x-axis to be a DND target\n        if (ImPlot::BeginDragDropTargetAxis(ImAxis_X1)) {\n            if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload(\"MY_DND\")) {\n                int i = *(int*)payload->Data; dndx = &dnd[i];\n            }\n            ImPlot::EndDragDropTarget();\n        }\n        // allow the x-axis to be a DND source\n        if (dndx != NULL && ImPlot::BeginDragDropSourceAxis(ImAxis_X1)) {\n            ImGui::SetDragDropPayload(\"MY_DND\", &dndx->Idx, sizeof(int));\n            ImPlot::ItemIcon(dndx->Color); ImGui::SameLine();\n            ImGui::TextUnformatted(dndx->Label);\n            ImPlot::EndDragDropSource();\n        }\n        // allow the y-axis to be a DND target\n        if (ImPlot::BeginDragDropTargetAxis(ImAxis_Y1)) {\n            if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload(\"MY_DND\")) {\n                int i = *(int*)payload->Data; dndy = &dnd[i];\n            }\n            ImPlot::EndDragDropTarget();\n        }\n        // allow the y-axis to be a DND source\n        if (dndy != NULL && ImPlot::BeginDragDropSourceAxis(ImAxis_Y1)) {\n            ImGui::SetDragDropPayload(\"MY_DND\", &dndy->Idx, sizeof(int));\n            ImPlot::ItemIcon(dndy->Color); ImGui::SameLine();\n            ImGui::TextUnformatted(dndy->Label);\n            ImPlot::EndDragDropSource();\n        }\n        // allow the plot area to be a DND target\n        if (ImPlot::BeginDragDropTargetPlot()) {\n            if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload(\"MY_DND\")) {\n                int i = *(int*)payload->Data; dndx = dndy = &dnd[i];\n            }\n        }\n        // allow the plot area to be a DND source\n        if (ImPlot::BeginDragDropSourcePlot()) {\n            ImGui::TextUnformatted(\"Yes, you can\\ndrag this!\");\n            ImPlot::EndDragDropSource();\n        }\n        ImPlot::EndPlot();\n    }\n    ImGui::EndChild();\n}\n\nvoid ShowDemo_Tables() {\n#ifdef IMGUI_HAS_TABLE\n    static ImGuiTableFlags flags = ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV |\n                                   ImGuiTableFlags_RowBg | ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable;\n    static bool anim = true;\n    static int offset = 0;\n    ImGui::BulletText(\"Plots can be used inside of ImGui tables as another means of creating subplots.\");\n    ImGui::Checkbox(\"Animate\",&anim);\n    if (anim)\n        offset = (offset + 1) % 100;\n    if (ImGui::BeginTable(\"##table\", 3, flags, ImVec2(-1,0))) {\n        ImGui::TableSetupColumn(\"Electrode\", ImGuiTableColumnFlags_WidthFixed, 75.0f);\n        ImGui::TableSetupColumn(\"Voltage\", ImGuiTableColumnFlags_WidthFixed, 75.0f);\n        ImGui::TableSetupColumn(\"EMG Signal\");\n        ImGui::TableHeadersRow();\n        ImPlot::PushColormap(ImPlotColormap_Cool);\n        for (int row = 0; row < 10; row++) {\n            ImGui::TableNextRow();\n            static float data[100];\n            srand(row);\n            for (int i = 0; i < 100; ++i)\n                data[i] = RandomRange(0.0f,10.0f);\n            ImGui::TableSetColumnIndex(0);\n            ImGui::Text(\"EMG %d\", row);\n            ImGui::TableSetColumnIndex(1);\n            ImGui::Text(\"%.3f V\", data[offset]);\n            ImGui::TableSetColumnIndex(2);\n            ImGui::PushID(row);\n            MyImPlot::Sparkline(\"##spark\",data,100,0,11.0f,offset,ImPlot::GetColormapColor(row),ImVec2(-1, 35));\n            ImGui::PopID();\n        }\n        ImPlot::PopColormap();\n        ImGui::EndTable();\n    }\n#else\n    ImGui::BulletText(\"You need to merge the ImGui 'tables' branch for this section.\");\n#endif\n}\n\nvoid ShowDemo_OffsetAndStride() {\n    static const int k_circles    = 11;\n    static const int k_points_per = 50;\n    static const int k_size       = 2 * k_points_per * k_circles;\n    static double interleaved_data[k_size];\n    for (int p = 0; p < k_points_per; ++p) {\n        for (int c = 0; c < k_circles; ++c) {\n            double r = (double)c / (k_circles - 1) * 0.2 + 0.2;\n            interleaved_data[p*2*k_circles + 2*c + 0] = 0.5 + r * cos((double)p/k_points_per * 6.28);\n            interleaved_data[p*2*k_circles + 2*c + 1] = 0.5 + r * sin((double)p/k_points_per * 6.28);\n        }\n    }\n    static int offset = 0;\n    ImGui::BulletText(\"Offsetting is useful for realtime plots (see above) and circular buffers.\");\n    ImGui::BulletText(\"Striding is useful for interleaved data (e.g. audio) or plotting structs.\");\n    ImGui::BulletText(\"Here, all circle data is stored in a single interleaved buffer:\");\n    ImGui::BulletText(\"[c0.x0 c0.y0 ... cn.x0 cn.y0 c0.x1 c0.y1 ... cn.x1 cn.y1 ... cn.xm cn.ym]\");\n    ImGui::BulletText(\"The offset value indicates which circle point index is considered the first.\");\n    ImGui::BulletText(\"Offsets can be negative and/or larger than the actual data count.\");\n    ImGui::SliderInt(\"Offset\", &offset, -2*k_points_per, 2*k_points_per);\n    if (ImPlot::BeginPlot(\"##strideoffset\",ImVec2(-1,0),ImPlotFlags_Equal)) {\n        ImPlot::PushColormap(ImPlotColormap_Jet);\n        char buff[16];\n        for (int c = 0; c < k_circles; ++c) {\n            sprintf(buff, \"Circle %d\", c);\n            ImPlot::PlotLine(buff, &interleaved_data[c*2 + 0], &interleaved_data[c*2 + 1], k_points_per, offset, 2*k_circles*sizeof(double));\n        }\n        ImPlot::EndPlot();\n        ImPlot::PopColormap();\n    }\n    // offset++; uncomment for animation!\n}\n\nvoid ShowDemo_CustomDataAndGetters() {\n    ImGui::BulletText(\"You can plot custom structs using the stride feature.\");\n    ImGui::BulletText(\"Most plotters can also be passed a function pointer for getting data.\");\n    ImGui::Indent();\n        ImGui::BulletText(\"You can optionally pass user data to be given to your getter function.\");\n        ImGui::BulletText(\"C++ lambdas can be passed as function pointers as well!\");\n    ImGui::Unindent();\n\n    MyImPlot::Vector2f vec2_data[2] = { MyImPlot::Vector2f(0,0), MyImPlot::Vector2f(1,1) };\n\n    if (ImPlot::BeginPlot(\"##Custom Data\")) {\n\n        // custom structs using stride example:\n        ImPlot::PlotLine(\"Vector2f\", &vec2_data[0].x, &vec2_data[0].y, 2, 0, sizeof(MyImPlot::Vector2f) /* or sizeof(float) * 2 */);\n\n        // custom getter example 1:\n        ImPlot::PlotLineG(\"Spiral\", MyImPlot::Spiral, NULL, 1000);\n\n        // custom getter example 2:\n        static MyImPlot::WaveData data1(0.001, 0.2, 2, 0.75);\n        static MyImPlot::WaveData data2(0.001, 0.2, 4, 0.25);\n        ImPlot::PlotLineG(\"Waves\", MyImPlot::SineWave, &data1, 1000);\n        ImPlot::PlotLineG(\"Waves\", MyImPlot::SawWave, &data2, 1000);\n        ImPlot::PushStyleVar(ImPlotStyleVar_FillAlpha, 0.25f);\n        ImPlot::PlotShadedG(\"Waves\", MyImPlot::SineWave, &data1, MyImPlot::SawWave, &data2, 1000);\n        ImPlot::PopStyleVar();\n\n        // you can also pass C++ lambdas:\n        // auto lamda = [](void* data, int idx) { ... return ImPlotPoint(x,y); };\n        // ImPlot::PlotLine(\"My Lambda\", lambda, data, 1000);\n\n        ImPlot::EndPlot();\n    }\n}\n\nvoid MetricFormatter(double value, char* buff, int size, void* data) {\n    const char* unit = (const char*)data;\n    static double v[]      = {1000000000,1000000,1000,1,0.001,0.000001,0.000000001};\n    static const char* p[] = {\"G\",\"M\",\"k\",\"\",\"m\",\"u\",\"n\"};\n    if (value == 0) {\n        snprintf(buff,size,\"0 %s\", unit);\n        return;\n    }\n    for (int i = 0; i < 7; ++i) {\n        if (fabs(value) >= v[i]) {\n            snprintf(buff,size,\"%g %s%s\",value/v[i],p[i],unit);\n            return;\n        }\n    }\n    snprintf(buff,size,\"%g %s%s\",value/v[6],p[6],unit);\n}\n\nvoid ShowDemo_TickLabels()  {\n    static bool custom_fmt    = true;\n    static bool custom_ticks  = false;\n    static bool custom_labels = true;\n    ImGui::Checkbox(\"Show Custom Format\", &custom_fmt);\n    ImGui::SameLine();\n    ImGui::Checkbox(\"Show Custom Ticks\", &custom_ticks);\n    if (custom_ticks) {\n        ImGui::SameLine();\n        ImGui::Checkbox(\"Show Custom Labels\", &custom_labels);\n    }\n    const double pi = 3.14;\n    const char* pi_str[] = {\"PI\"};\n    static double yticks[] = {100,300,700,900};\n    static const char*  ylabels[] = {\"One\",\"Three\",\"Seven\",\"Nine\"};\n    static double yticks_aux[] = {0.2,0.4,0.6};\n    static const char* ylabels_aux[] = {\"A\",\"B\",\"C\",\"D\",\"E\",\"F\"};\n\n    if (ImPlot::BeginPlot(\"##Ticks\")) {\n        ImPlot::SetupAxesLimits(2.5,5,0,1000);\n        ImPlot::SetupAxis(ImAxis_Y2, NULL, ImPlotAxisFlags_AuxDefault);\n        ImPlot::SetupAxis(ImAxis_Y3, NULL, ImPlotAxisFlags_AuxDefault);\n        if (custom_fmt) {\n            ImPlot::SetupAxisFormat(ImAxis_X1, \"%g ms\");\n            ImPlot::SetupAxisFormat(ImAxis_Y1, MetricFormatter, (void*)\"Hz\");\n            ImPlot::SetupAxisFormat(ImAxis_Y2, \"%g dB\");\n            ImPlot::SetupAxisFormat(ImAxis_Y3, MetricFormatter, (void*)\"m\");\n        }\n        if (custom_ticks) {\n            ImPlot::SetupAxisTicks(ImAxis_X1, &pi,1,custom_labels ? pi_str : NULL, true);\n            ImPlot::SetupAxisTicks(ImAxis_Y1, yticks, 4, custom_labels ? ylabels : NULL, false);\n            ImPlot::SetupAxisTicks(ImAxis_Y2, yticks_aux, 3, custom_labels ? ylabels_aux : NULL, false);\n            ImPlot::SetupAxisTicks(ImAxis_Y3, 0, 1, 6, custom_labels ? ylabels_aux : NULL, false);\n        }\n        ImPlot::EndPlot();\n    }\n}\n\nvoid ShowDemo_CustomStyles() {\n    ImPlot::PushColormap(ImPlotColormap_Deep);\n    // normally you wouldn't change the entire style each frame\n    ImPlotStyle backup = ImPlot::GetStyle();\n    MyImPlot::StyleSeaborn();\n    if (ImPlot::BeginPlot(\"seaborn style\")) {\n        ImPlot::SetupAxes( \"x-axis\", \"y-axis\");\n        ImPlot::SetupAxesLimits(-0.5f, 9.5f, 0, 10);\n        unsigned int lin[10] = {8,8,9,7,8,8,8,9,7,8};\n        unsigned int bar[10] = {1,2,5,3,4,1,2,5,3,4};\n        unsigned int dot[10] = {7,6,6,7,8,5,6,5,8,7};\n        ImPlot::PlotBars(\"Bars\", bar, 10, 0.5f);\n        ImPlot::PlotLine(\"Line\", lin, 10);\n        ImPlot::NextColormapColor(); // skip green\n        ImPlot::PlotScatter(\"Scatter\", dot, 10);\n        ImPlot::EndPlot();\n    }\n    ImPlot::GetStyle() = backup;\n    ImPlot::PopColormap();\n}\n\nvoid ShowDemo_CustomRendering() {\n    if (ImPlot::BeginPlot(\"##CustomRend\")) {\n        ImVec2 cntr = ImPlot::PlotToPixels(ImPlotPoint(0.5f,  0.5f));\n        ImVec2 rmin = ImPlot::PlotToPixels(ImPlotPoint(0.25f, 0.75f));\n        ImVec2 rmax = ImPlot::PlotToPixels(ImPlotPoint(0.75f, 0.25f));\n        ImPlot::PushPlotClipRect();\n        ImPlot::GetPlotDrawList()->AddCircleFilled(cntr,20,IM_COL32(255,255,0,255),20);\n        ImPlot::GetPlotDrawList()->AddRect(rmin, rmax, IM_COL32(128,0,255,255));\n        ImPlot::PopPlotClipRect();\n        ImPlot::EndPlot();\n    }\n}\n\nvoid ShowDemo_LegendPopups() {\n    ImGui::BulletText(\"You can implement legend context menus to inject per-item controls and widgets.\");\n    ImGui::BulletText(\"Right click the legend label/icon to edit custom item attributes.\");\n\n    static float  frequency = 0.1f;\n    static float  amplitude = 0.5f;\n    static ImVec4 color     = ImVec4(1,1,0,1);\n    static float  alpha     = 1.0f;\n    static bool   line      = false;\n    static float  thickness = 1;\n    static bool   markers   = false;\n    static bool   shaded    = false;\n\n    static float vals[101];\n    for (int i = 0; i < 101; ++i)\n        vals[i] = amplitude * sinf(frequency * i);\n\n    if (ImPlot::BeginPlot(\"Right Click the Legend\")) {\n        ImPlot::SetupAxesLimits(0,100,-1,1);\n        // rendering logic\n        ImPlot::PushStyleVar(ImPlotStyleVar_FillAlpha, alpha);\n        if (!line) {\n            ImPlot::SetNextFillStyle(color);\n            ImPlot::PlotBars(\"Right Click Me\", vals, 101);\n        }\n        else {\n            if (markers) ImPlot::SetNextMarkerStyle(ImPlotMarker_Circle);\n            ImPlot::SetNextLineStyle(color, thickness);\n            ImPlot::PlotLine(\"Right Click Me\", vals, 101);\n            if (shaded) ImPlot::PlotShaded(\"Right Click Me\",vals,101);\n        }\n        ImPlot::PopStyleVar();\n        // custom legend context menu\n        if (ImPlot::BeginLegendPopup(\"Right Click Me\")) {\n            ImGui::SliderFloat(\"Frequency\",&frequency,0,1,\"%0.2f\");\n            ImGui::SliderFloat(\"Amplitude\",&amplitude,0,1,\"%0.2f\");\n            ImGui::Separator();\n            ImGui::ColorEdit3(\"Color\",&color.x);\n            ImGui::SliderFloat(\"Transparency\",&alpha,0,1,\"%.2f\");\n            ImGui::Checkbox(\"Line Plot\", &line);\n            if (line) {\n                ImGui::SliderFloat(\"Thickness\", &thickness, 0, 5);\n                ImGui::Checkbox(\"Markers\", &markers);\n                ImGui::Checkbox(\"Shaded\",&shaded);\n            }\n            ImPlot::EndLegendPopup();\n        }\n        ImPlot::EndPlot();\n    }\n}\n\nvoid ShowDemo_ColormapTools() {\n    static int cmap = 0;\n    if (ImPlot::ColormapButton(\"Colormap Button\",ImVec2(0,0),cmap)) {\n        cmap = (cmap + 1) % ImPlot::GetColormapCount();\n    }\n    ImPlot::ColormapIcon(cmap); ImGui::SameLine(); ImGui::Text(\"Colormap Icon\");\n    ImPlot::ColormapScale(\"Colormap Scale\",0,1,ImVec2(0,0),cmap);\n}\n\nvoid ShowDemo_CustomPlottersAndTooltips()  {\n    ImGui::BulletText(\"You can create custom plotters or extend ImPlot using implot_internal.h.\");\n    double dates[]  = {1546300800,1546387200,1546473600,1546560000,1546819200,1546905600,1546992000,1547078400,1547164800,1547424000,1547510400,1547596800,1547683200,1547769600,1547942400,1548028800,1548115200,1548201600,1548288000,1548374400,1548633600,1548720000,1548806400,1548892800,1548979200,1549238400,1549324800,1549411200,1549497600,1549584000,1549843200,1549929600,1550016000,1550102400,1550188800,1550361600,1550448000,1550534400,1550620800,1550707200,1550793600,1551052800,1551139200,1551225600,1551312000,1551398400,1551657600,1551744000,1551830400,1551916800,1552003200,1552262400,1552348800,1552435200,1552521600,1552608000,1552867200,1552953600,1553040000,1553126400,1553212800,1553472000,1553558400,1553644800,1553731200,1553817600,1554076800,1554163200,1554249600,1554336000,1554422400,1554681600,1554768000,1554854400,1554940800,1555027200,1555286400,1555372800,1555459200,1555545600,1555632000,1555891200,1555977600,1556064000,1556150400,1556236800,1556496000,1556582400,1556668800,1556755200,1556841600,1557100800,1557187200,1557273600,1557360000,1557446400,1557705600,1557792000,1557878400,1557964800,1558051200,1558310400,1558396800,1558483200,1558569600,1558656000,1558828800,1558915200,1559001600,1559088000,1559174400,1559260800,1559520000,1559606400,1559692800,1559779200,1559865600,1560124800,1560211200,1560297600,1560384000,1560470400,1560729600,1560816000,1560902400,1560988800,1561075200,1561334400,1561420800,1561507200,1561593600,1561680000,1561939200,1562025600,1562112000,1562198400,1562284800,1562544000,1562630400,1562716800,1562803200,1562889600,1563148800,1563235200,1563321600,1563408000,1563494400,1563753600,1563840000,1563926400,1564012800,1564099200,1564358400,1564444800,1564531200,1564617600,1564704000,1564963200,1565049600,1565136000,1565222400,1565308800,1565568000,1565654400,1565740800,1565827200,1565913600,1566172800,1566259200,1566345600,1566432000,1566518400,1566777600,1566864000,1566950400,1567036800,1567123200,1567296000,1567382400,1567468800,1567555200,1567641600,1567728000,1567987200,1568073600,1568160000,1568246400,1568332800,1568592000,1568678400,1568764800,1568851200,1568937600,1569196800,1569283200,1569369600,1569456000,1569542400,1569801600,1569888000,1569974400,1570060800,1570147200,1570406400,1570492800,1570579200,1570665600,1570752000,1571011200,1571097600,1571184000,1571270400,1571356800,1571616000,1571702400,1571788800,1571875200,1571961600};\n    double opens[]  = {1284.7,1319.9,1318.7,1328,1317.6,1321.6,1314.3,1325,1319.3,1323.1,1324.7,1321.3,1323.5,1322,1281.3,1281.95,1311.1,1315,1314,1313.1,1331.9,1334.2,1341.3,1350.6,1349.8,1346.4,1343.4,1344.9,1335.6,1337.9,1342.5,1337,1338.6,1337,1340.4,1324.65,1324.35,1349.5,1371.3,1367.9,1351.3,1357.8,1356.1,1356,1347.6,1339.1,1320.6,1311.8,1314,1312.4,1312.3,1323.5,1319.1,1327.2,1332.1,1320.3,1323.1,1328,1330.9,1338,1333,1335.3,1345.2,1341.1,1332.5,1314,1314.4,1310.7,1314,1313.1,1315,1313.7,1320,1326.5,1329.2,1314.2,1312.3,1309.5,1297.4,1293.7,1277.9,1295.8,1295.2,1290.3,1294.2,1298,1306.4,1299.8,1302.3,1297,1289.6,1302,1300.7,1303.5,1300.5,1303.2,1306,1318.7,1315,1314.5,1304.1,1294.7,1293.7,1291.2,1290.2,1300.4,1284.2,1284.25,1301.8,1295.9,1296.2,1304.4,1323.1,1340.9,1341,1348,1351.4,1351.4,1343.5,1342.3,1349,1357.6,1357.1,1354.7,1361.4,1375.2,1403.5,1414.7,1433.2,1438,1423.6,1424.4,1418,1399.5,1435.5,1421.25,1434.1,1412.4,1409.8,1412.2,1433.4,1418.4,1429,1428.8,1420.6,1441,1460.4,1441.7,1438.4,1431,1439.3,1427.4,1431.9,1439.5,1443.7,1425.6,1457.5,1451.2,1481.1,1486.7,1512.1,1515.9,1509.2,1522.3,1513,1526.6,1533.9,1523,1506.3,1518.4,1512.4,1508.8,1545.4,1537.3,1551.8,1549.4,1536.9,1535.25,1537.95,1535.2,1556,1561.4,1525.6,1516.4,1507,1493.9,1504.9,1506.5,1513.1,1506.5,1509.7,1502,1506.8,1521.5,1529.8,1539.8,1510.9,1511.8,1501.7,1478,1485.4,1505.6,1511.6,1518.6,1498.7,1510.9,1510.8,1498.3,1492,1497.7,1484.8,1494.2,1495.6,1495.6,1487.5,1491.1,1495.1,1506.4};\n    double highs[]  = {1284.75,1320.6,1327,1330.8,1326.8,1321.6,1326,1328,1325.8,1327.1,1326,1326,1323.5,1322.1,1282.7,1282.95,1315.8,1316.3,1314,1333.2,1334.7,1341.7,1353.2,1354.6,1352.2,1346.4,1345.7,1344.9,1340.7,1344.2,1342.7,1342.1,1345.2,1342,1350,1324.95,1330.75,1369.6,1374.3,1368.4,1359.8,1359,1357,1356,1353.4,1340.6,1322.3,1314.1,1316.1,1312.9,1325.7,1323.5,1326.3,1336,1332.1,1330.1,1330.4,1334.7,1341.1,1344.2,1338.8,1348.4,1345.6,1342.8,1334.7,1322.3,1319.3,1314.7,1316.6,1316.4,1315,1325.4,1328.3,1332.2,1329.2,1316.9,1312.3,1309.5,1299.6,1296.9,1277.9,1299.5,1296.2,1298.4,1302.5,1308.7,1306.4,1305.9,1307,1297.2,1301.7,1305,1305.3,1310.2,1307,1308,1319.8,1321.7,1318.7,1316.2,1305.9,1295.8,1293.8,1293.7,1304.2,1302,1285.15,1286.85,1304,1302,1305.2,1323,1344.1,1345.2,1360.1,1355.3,1363.8,1353,1344.7,1353.6,1358,1373.6,1358.2,1369.6,1377.6,1408.9,1425.5,1435.9,1453.7,1438,1426,1439.1,1418,1435,1452.6,1426.65,1437.5,1421.5,1414.1,1433.3,1441.3,1431.4,1433.9,1432.4,1440.8,1462.3,1467,1443.5,1444,1442.9,1447,1437.6,1440.8,1445.7,1447.8,1458.2,1461.9,1481.8,1486.8,1522.7,1521.3,1521.1,1531.5,1546.1,1534.9,1537.7,1538.6,1523.6,1518.8,1518.4,1514.6,1540.3,1565,1554.5,1556.6,1559.8,1541.9,1542.9,1540.05,1558.9,1566.2,1561.9,1536.2,1523.8,1509.1,1506.2,1532.2,1516.6,1519.7,1515,1519.5,1512.1,1524.5,1534.4,1543.3,1543.3,1542.8,1519.5,1507.2,1493.5,1511.4,1525.8,1522.2,1518.8,1515.3,1518,1522.3,1508,1501.5,1503,1495.5,1501.1,1497.9,1498.7,1492.1,1499.4,1506.9,1520.9};\n    double lows[]   = {1282.85,1315,1318.7,1309.6,1317.6,1312.9,1312.4,1319.1,1319,1321,1318.1,1321.3,1319.9,1312,1280.5,1276.15,1308,1309.9,1308.5,1312.3,1329.3,1333.1,1340.2,1347,1345.9,1338,1340.8,1335,1332,1337.9,1333,1336.8,1333.2,1329.9,1340.4,1323.85,1324.05,1349,1366.3,1351.2,1349.1,1352.4,1350.7,1344.3,1338.9,1316.3,1308.4,1306.9,1309.6,1306.7,1312.3,1315.4,1319,1327.2,1317.2,1320,1323,1328,1323,1327.8,1331.7,1335.3,1336.6,1331.8,1311.4,1310,1309.5,1308,1310.6,1302.8,1306.6,1313.7,1320,1322.8,1311,1312.1,1303.6,1293.9,1293.5,1291,1277.9,1294.1,1286,1289.1,1293.5,1296.9,1298,1299.6,1292.9,1285.1,1288.5,1296.3,1297.2,1298.4,1298.6,1302,1300.3,1312,1310.8,1301.9,1292,1291.1,1286.3,1289.2,1289.9,1297.4,1283.65,1283.25,1292.9,1295.9,1290.8,1304.2,1322.7,1336.1,1341,1343.5,1345.8,1340.3,1335.1,1341.5,1347.6,1352.8,1348.2,1353.7,1356.5,1373.3,1398,1414.7,1427,1416.4,1412.7,1420.1,1396.4,1398.8,1426.6,1412.85,1400.7,1406,1399.8,1404.4,1415.5,1417.2,1421.9,1415,1413.7,1428.1,1434,1435.7,1427.5,1429.4,1423.9,1425.6,1427.5,1434.8,1422.3,1412.1,1442.5,1448.8,1468.2,1484.3,1501.6,1506.2,1498.6,1488.9,1504.5,1518.3,1513.9,1503.3,1503,1506.5,1502.1,1503,1534.8,1535.3,1541.4,1528.6,1525.6,1535.25,1528.15,1528,1542.6,1514.3,1510.7,1505.5,1492.1,1492.9,1496.8,1493.1,1503.4,1500.9,1490.7,1496.3,1505.3,1505.3,1517.9,1507.4,1507.1,1493.3,1470.5,1465,1480.5,1501.7,1501.4,1493.3,1492.1,1505.1,1495.7,1478,1487.1,1480.8,1480.6,1487,1488.3,1484.8,1484,1490.7,1490.4,1503.1};\n    double closes[] = {1283.35,1315.3,1326.1,1317.4,1321.5,1317.4,1323.5,1319.2,1321.3,1323.3,1319.7,1325.1,1323.6,1313.8,1282.05,1279.05,1314.2,1315.2,1310.8,1329.1,1334.5,1340.2,1340.5,1350,1347.1,1344.3,1344.6,1339.7,1339.4,1343.7,1337,1338.9,1340.1,1338.7,1346.8,1324.25,1329.55,1369.6,1372.5,1352.4,1357.6,1354.2,1353.4,1346,1341,1323.8,1311.9,1309.1,1312.2,1310.7,1324.3,1315.7,1322.4,1333.8,1319.4,1327.1,1325.8,1330.9,1325.8,1331.6,1336.5,1346.7,1339.2,1334.7,1313.3,1316.5,1312.4,1313.4,1313.3,1312.2,1313.7,1319.9,1326.3,1331.9,1311.3,1313.4,1309.4,1295.2,1294.7,1294.1,1277.9,1295.8,1291.2,1297.4,1297.7,1306.8,1299.4,1303.6,1302.2,1289.9,1299.2,1301.8,1303.6,1299.5,1303.2,1305.3,1319.5,1313.6,1315.1,1303.5,1293,1294.6,1290.4,1291.4,1302.7,1301,1284.15,1284.95,1294.3,1297.9,1304.1,1322.6,1339.3,1340.1,1344.9,1354,1357.4,1340.7,1342.7,1348.2,1355.1,1355.9,1354.2,1362.1,1360.1,1408.3,1411.2,1429.5,1430.1,1426.8,1423.4,1425.1,1400.8,1419.8,1432.9,1423.55,1412.1,1412.2,1412.8,1424.9,1419.3,1424.8,1426.1,1423.6,1435.9,1440.8,1439.4,1439.7,1434.5,1436.5,1427.5,1432.2,1433.3,1441.8,1437.8,1432.4,1457.5,1476.5,1484.2,1519.6,1509.5,1508.5,1517.2,1514.1,1527.8,1531.2,1523.6,1511.6,1515.7,1515.7,1508.5,1537.6,1537.2,1551.8,1549.1,1536.9,1529.4,1538.05,1535.15,1555.9,1560.4,1525.5,1515.5,1511.1,1499.2,1503.2,1507.4,1499.5,1511.5,1513.4,1515.8,1506.2,1515.1,1531.5,1540.2,1512.3,1515.2,1506.4,1472.9,1489,1507.9,1513.8,1512.9,1504.4,1503.9,1512.8,1500.9,1488.7,1497.6,1483.5,1494,1498.3,1494.1,1488.1,1487.5,1495.7,1504.7,1505.3};\n    static bool tooltip = true;\n    ImGui::Checkbox(\"Show Tooltip\", &tooltip);\n    ImGui::SameLine();\n    static ImVec4 bullCol = ImVec4(0.000f, 1.000f, 0.441f, 1.000f);\n    static ImVec4 bearCol = ImVec4(0.853f, 0.050f, 0.310f, 1.000f);\n    ImGui::SameLine(); ImGui::ColorEdit4(\"##Bull\", &bullCol.x, ImGuiColorEditFlags_NoInputs);\n    ImGui::SameLine(); ImGui::ColorEdit4(\"##Bear\", &bearCol.x, ImGuiColorEditFlags_NoInputs);\n    ImPlot::GetStyle().UseLocalTime = false;\n\n    if (ImPlot::BeginPlot(\"Candlestick Chart\",ImVec2(-1,0))) {\n        ImPlot::SetupAxes(NULL,NULL,ImPlotAxisFlags_Time,ImPlotAxisFlags_AutoFit|ImPlotAxisFlags_RangeFit);\n        ImPlot::SetupAxesLimits(1546300800, 1571961600, 1250, 1600);\n        ImPlot::SetupAxisFormat(ImAxis_Y1, \"$%.0f\");\n        MyImPlot::PlotCandlestick(\"GOOGL\",dates, opens, closes, lows, highs, 218, tooltip, 0.25f, bullCol, bearCol);\n        ImPlot::EndPlot();\n    }\n    }\n\n//-----------------------------------------------------------------------------\n// DEMO WINDOW\n//-----------------------------------------------------------------------------\n\nvoid ShowDemoWindow(bool* p_open) {\n    static bool show_imgui_metrics       = false;\n    static bool show_implot_metrics      = false;\n    static bool show_imgui_style_editor  = false;\n    static bool show_implot_style_editor = false;\n    static bool show_implot_benchmark    = false;\n    if (show_imgui_metrics) {\n        ImGui::ShowMetricsWindow(&show_imgui_metrics);\n    }\n    if (show_implot_metrics) {\n        ImPlot::ShowMetricsWindow(&show_implot_metrics);\n    }\n    if (show_imgui_style_editor) {\n        ImGui::Begin(\"Style Editor (ImGui)\", &show_imgui_style_editor);\n        ImGui::ShowStyleEditor();\n        ImGui::End();\n    }\n    if (show_implot_style_editor) {\n        ImGui::SetNextWindowSize(ImVec2(415,762), ImGuiCond_Appearing);\n        ImGui::Begin(\"Style Editor (ImPlot)\", &show_implot_style_editor);\n        ImPlot::ShowStyleEditor();\n        ImGui::End();\n    }\n    if (show_implot_benchmark) {\n        ImGui::SetNextWindowSize(ImVec2(530,740), ImGuiCond_Appearing);\n        ImGui::Begin(\"ImPlot Benchmark Tool\", &show_implot_benchmark);\n        ImPlot::ShowBenchmarkTool();\n        ImGui::End();\n        return;\n    }\n    ImGui::SetNextWindowPos(ImVec2(50, 50), ImGuiCond_FirstUseEver);\n    ImGui::SetNextWindowSize(ImVec2(600, 750), ImGuiCond_FirstUseEver);\n    ImGui::Begin(\"ImPlot Demo\", p_open, ImGuiWindowFlags_MenuBar);\n    if (ImGui::BeginMenuBar()) {\n        if (ImGui::BeginMenu(\"Tools\")) {\n            ImGui::MenuItem(\"Metrics (ImGui)\",       NULL, &show_imgui_metrics);\n            ImGui::MenuItem(\"Metrics (ImPlot)\",      NULL, &show_implot_metrics);\n            ImGui::MenuItem(\"Style Editor (ImGui)\",  NULL, &show_imgui_style_editor);\n            ImGui::MenuItem(\"Style Editor (ImPlot)\", NULL, &show_implot_style_editor);\n            ImGui::MenuItem(\"Benchmark\",             NULL, &show_implot_benchmark);\n            ImGui::EndMenu();\n        }\n        ImGui::EndMenuBar();\n    }\n    //-------------------------------------------------------------------------\n    ImGui::Text(\"ImPlot says hello. (%s)\", IMPLOT_VERSION);\n    // display warning about 16-bit indices\n    static bool showWarning = sizeof(ImDrawIdx)*8 == 16 && (ImGui::GetIO().BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset) == false;\n    if (showWarning) {\n        ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1,1,0,1));\n        ImGui::TextWrapped(\"WARNING: ImDrawIdx is 16-bit and ImGuiBackendFlags_RendererHasVtxOffset is false. Expect visual glitches and artifacts! See README for more information.\");\n        ImGui::PopStyleColor();\n    }\n\n    ImGui::Spacing();\n\n    if (ImGui::BeginTabBar(\"ImPlotDemoTabs\")) {\n        if (ImGui::BeginTabItem(\"Plots\")) {\n            if (ImGui::CollapsingHeader(\"Line Plots\"))\n                ShowDemo_LinePlots();\n            if (ImGui::CollapsingHeader(\"Filled Line Plots\"))\n                ShowDemo_FilledLinePlots();\n            if (ImGui::CollapsingHeader(\"Shaded Plots##\"))\n                ShowDemo_ShadedPlots();\n            if (ImGui::CollapsingHeader(\"Scatter Plots\"))\n                ShowDemo_ScatterPlots();\n            if (ImGui::CollapsingHeader(\"Realtime Plots\"))\n                ShowDemo_RealtimePlots();\n            if (ImGui::CollapsingHeader(\"Stairstep Plots\"))\n                ShowDemo_StairstepPlots();\n            if (ImGui::CollapsingHeader(\"Bar Plots\"))\n                ShowDemo_BarPlots();\n            if (ImGui::CollapsingHeader(\"Bar Groups\"))\n                ShowDemo_BarGroups();\n            if (ImGui::CollapsingHeader(\"Bar Stacks\"))\n                ShowDemo_BarStacks();\n            if (ImGui::CollapsingHeader(\"Error Bars\"))\n                ShowDemo_ErrorBars();\n            if (ImGui::CollapsingHeader(\"Stem Plots##\"))\n                ShowDemo_StemPlots();\n            if (ImGui::CollapsingHeader(\"Infinite Lines\"))\n                ShowDemo_InfiniteLines();\n            if (ImGui::CollapsingHeader(\"Pie Charts\"))\n                ShowDemo_PieCharts();\n            if (ImGui::CollapsingHeader(\"Heatmaps\"))\n                ShowDemo_Heatmaps();\n            if (ImGui::CollapsingHeader(\"Histogram\"))\n                ShowDemo_Histogram();\n            if (ImGui::CollapsingHeader(\"Histogram 2D\"))\n                ShowDemo_Histogram2D();\n            if (ImGui::CollapsingHeader(\"Digital Plots\"))\n                ShowDemo_DigitalPlots();\n            if (ImGui::CollapsingHeader(\"Images\"))\n                ShowDemo_Images();\n            if (ImGui::CollapsingHeader(\"Markers and Text\"))\n                ShowDemo_MarkersAndText();\n            ImGui::EndTabItem();\n        }\n        if (ImGui::BeginTabItem(\"Subplots\")) {\n            if (ImGui::CollapsingHeader(\"Sizing\"))\n                ShowDemo_SubplotsSizing();\n            if (ImGui::CollapsingHeader(\"Item Sharing\"))\n                ShowDemo_SubplotItemSharing();\n            if (ImGui::CollapsingHeader(\"Axis Linking\"))\n                ShowDemo_SubplotAxisLinking();\n            if (ImGui::CollapsingHeader(\"Tables\"))\n                ShowDemo_Tables();\n            ImGui::EndTabItem();\n        }\n        if (ImGui::BeginTabItem(\"Axes\")) {\n            if (ImGui::CollapsingHeader(\"Log Axes\"))\n                ShowDemo_LogAxes();\n            if (ImGui::CollapsingHeader(\"Time Axes\"))\n                ShowDemo_TimeAxes();\n            if (ImGui::CollapsingHeader(\"Multiple Axes\"))\n                ShowDemo_MultipleAxes();\n            if (ImGui::CollapsingHeader(\"Tick Labels\"))\n                ShowDemo_TickLabels();\n            if (ImGui::CollapsingHeader(\"Linked Axes\"))\n                ShowDemo_LinkedAxes();\n            if (ImGui::CollapsingHeader(\"Equal Axes\"))\n                ShowDemo_EqualAxes();\n            if (ImGui::CollapsingHeader(\"Auto-Fitting Data\"))\n                ShowDemo_AutoFittingData();\n            ImGui::EndTabItem();\n        }\n        if (ImGui::BeginTabItem(\"Tools\")) {\n            if (ImGui::CollapsingHeader(\"Offset and Stride\"))\n                ShowDemo_OffsetAndStride();\n            if (ImGui::CollapsingHeader(\"Drag Points\"))\n                ShowDemo_DragPoints();\n            if (ImGui::CollapsingHeader(\"Drag Lines\"))\n                ShowDemo_DragLines();\n            if (ImGui::CollapsingHeader(\"Drag Rects\"))\n                ShowDemo_DragRects();\n            if (ImGui::CollapsingHeader(\"Querying\"))\n                ShowDemo_Querying();\n            if (ImGui::CollapsingHeader(\"Annotations\"))\n                ShowDemo_Annotations();\n            if (ImGui::CollapsingHeader(\"Tags\"))\n                ShowDemo_Tags();\n            if (ImGui::CollapsingHeader(\"Drag and Drop\"))\n                ShowDemo_DragAndDrop();\n            if (ImGui::CollapsingHeader(\"Legend Options\"))\n                ShowDemo_LegendOptions();\n            if (ImGui::CollapsingHeader(\"Legend Popups\"))\n                ShowDemo_LegendPopups();\n            if (ImGui::CollapsingHeader(\"Colormap Tools\"))\n                ShowDemo_ColormapTools();\n            ImGui::EndTabItem();\n        }\n        if (ImGui::BeginTabItem(\"Custom\")) {\n            if (ImGui::CollapsingHeader(\"Custom Styles\"))\n                ShowDemo_CustomStyles();\n            if (ImGui::CollapsingHeader(\"Custom Data and Getters\"))\n                ShowDemo_CustomDataAndGetters();\n            if (ImGui::CollapsingHeader(\"Custom Rendering\"))\n                ShowDemo_CustomRendering();\n            if (ImGui::CollapsingHeader(\"Custom Plotters and Tooltips\"))\n                ShowDemo_CustomPlottersAndTooltips();\n            ImGui::EndTabItem();\n        }\n        if (ImGui::BeginTabItem(\"Config\")) {\n            ShowDemo_Config();\n            ImGui::EndTabItem();\n        }\n        if (ImGui::BeginTabItem(\"Help\")) {\n            ShowDemo_Help();\n            ImGui::EndTabItem();\n        }\n        ImGui::EndTabBar();\n    }\n    ImGui::End();\n}\n\n} // namespace ImPlot\n\nnamespace MyImPlot {\n\nImPlotPoint SineWave(void* data , int idx) {\n    WaveData* wd = (WaveData*)data;\n    double x = idx * wd->X;\n    return ImPlotPoint(x, wd->Offset + wd->Amp * sin(2 * 3.14 * wd->Freq * x));\n}\n\nImPlotPoint SawWave(void* data, int idx) {\n    WaveData* wd = (WaveData*)data;\n    double x = idx * wd->X;\n    return ImPlotPoint(x, wd->Offset + wd->Amp * (-2 / 3.14 * atan(cos(3.14 * wd->Freq * x) / sin(3.14 * wd->Freq * x))));\n}\n\nImPlotPoint Spiral(void*, int idx) {\n    float r = 0.9f;            // outer radius\n    float a = 0;               // inner radius\n    float b = 0.05f;           // increment per rev\n    float n = (r - a) / b;     // number  of revolutions\n    double th = 2 * n * 3.14;  // angle\n    float Th = float(th * idx / (1000 - 1));\n    return ImPlotPoint(0.5f+(a + b*Th / (2.0f * (float) 3.14))*cos(Th),\n                       0.5f + (a + b*Th / (2.0f * (float)3.14))*sin(Th));\n}\n\nvoid Sparkline(const char* id, const float* values, int count, float min_v, float max_v, int offset, const ImVec4& col, const ImVec2& size) {\n    ImPlot::PushStyleVar(ImPlotStyleVar_PlotPadding, ImVec2(0,0));\n    if (ImPlot::BeginPlot(id,size,ImPlotFlags_CanvasOnly|ImPlotFlags_NoChild)) {\n        ImPlot::SetupAxes(0,0,ImPlotAxisFlags_NoDecorations,ImPlotAxisFlags_NoDecorations);\n        ImPlot::SetupAxesLimits(0, count - 1, min_v, max_v, ImGuiCond_Always);\n        ImPlot::PushStyleColor(ImPlotCol_Line, col);\n        ImPlot::PlotLine(id, values, count, 1, 0, offset);\n        ImPlot::PushStyleVar(ImPlotStyleVar_FillAlpha, 0.25f);\n        ImPlot::PlotShaded(id, values, count, 0, 1, 0, offset);\n        ImPlot::PopStyleVar();\n        ImPlot::PopStyleColor();\n        ImPlot::EndPlot();\n    }\n    ImPlot::PopStyleVar();\n}\n\nvoid StyleSeaborn() {\n\n    ImPlotStyle& style              = ImPlot::GetStyle();\n\n    ImVec4* colors                  = style.Colors;\n    colors[ImPlotCol_Line]          = IMPLOT_AUTO_COL;\n    colors[ImPlotCol_Fill]          = IMPLOT_AUTO_COL;\n    colors[ImPlotCol_MarkerOutline] = IMPLOT_AUTO_COL;\n    colors[ImPlotCol_MarkerFill]    = IMPLOT_AUTO_COL;\n    colors[ImPlotCol_ErrorBar]      = ImVec4(0.00f, 0.00f, 0.00f, 1.00f);\n    colors[ImPlotCol_FrameBg]       = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);\n    colors[ImPlotCol_PlotBg]        = ImVec4(0.92f, 0.92f, 0.95f, 1.00f);\n    colors[ImPlotCol_PlotBorder]    = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);\n    colors[ImPlotCol_LegendBg]      = ImVec4(0.92f, 0.92f, 0.95f, 1.00f);\n    colors[ImPlotCol_LegendBorder]  = ImVec4(0.80f, 0.81f, 0.85f, 1.00f);\n    colors[ImPlotCol_LegendText]    = ImVec4(0.00f, 0.00f, 0.00f, 1.00f);\n    colors[ImPlotCol_TitleText]     = ImVec4(0.00f, 0.00f, 0.00f, 1.00f);\n    colors[ImPlotCol_InlayText]     = ImVec4(0.00f, 0.00f, 0.00f, 1.00f);\n    colors[ImPlotCol_AxisText]      = ImVec4(0.00f, 0.00f, 0.00f, 1.00f);\n    colors[ImPlotCol_AxisGrid]      = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);\n    colors[ImPlotCol_AxisBgHovered]   = ImVec4(0.92f, 0.92f, 0.95f, 1.00f);\n    colors[ImPlotCol_AxisBgActive]    = ImVec4(0.92f, 0.92f, 0.95f, 0.75f);\n    colors[ImPlotCol_Selection]     = ImVec4(1.00f, 0.65f, 0.00f, 1.00f);\n    colors[ImPlotCol_Crosshairs]    = ImVec4(0.23f, 0.10f, 0.64f, 0.50f);\n\n    style.LineWeight       = 1.5;\n    style.Marker           = ImPlotMarker_None;\n    style.MarkerSize       = 4;\n    style.MarkerWeight     = 1;\n    style.FillAlpha        = 1.0f;\n    style.ErrorBarSize     = 5;\n    style.ErrorBarWeight   = 1.5f;\n    style.DigitalBitHeight = 8;\n    style.DigitalBitGap    = 4;\n    style.PlotBorderSize   = 0;\n    style.MinorAlpha       = 1.0f;\n    style.MajorTickLen     = ImVec2(0,0);\n    style.MinorTickLen     = ImVec2(0,0);\n    style.MajorTickSize    = ImVec2(0,0);\n    style.MinorTickSize    = ImVec2(0,0);\n    style.MajorGridSize    = ImVec2(1.2f,1.2f);\n    style.MinorGridSize    = ImVec2(1.2f,1.2f);\n    style.PlotPadding      = ImVec2(12,12);\n    style.LabelPadding     = ImVec2(5,5);\n    style.LegendPadding    = ImVec2(5,5);\n    style.MousePosPadding  = ImVec2(5,5);\n    style.PlotMinSize      = ImVec2(300,225);\n}\n\n} // namespaece MyImPlot\n\n// WARNING:\n//\n// You can use \"implot_internal.h\" to build custom plotting fuctions or extend ImPlot.\n// However, note that forward compatibility of this file is not guaranteed and the\n// internal API is subject to change. At some point we hope to bring more of this\n// into the public API and expose the necessary building blocks to fully support\n// custom plotters. For now, proceed at your own risk!\n\n#include \"implot_internal.h\"\n\nnamespace MyImPlot {\n\ntemplate <typename T>\nint BinarySearch(const T* arr, int l, int r, T x) {\n    if (r >= l) {\n        int mid = l + (r - l) / 2;\n        if (arr[mid] == x)\n            return mid;\n        if (arr[mid] > x)\n            return BinarySearch(arr, l, mid - 1, x);\n        return BinarySearch(arr, mid + 1, r, x);\n    }\n    return -1;\n}\n\nvoid PlotCandlestick(const char* label_id, const double* xs, const double* opens, const double* closes, const double* lows, const double* highs, int count, bool tooltip, float width_percent, ImVec4 bullCol, ImVec4 bearCol) {\n\n    // get ImGui window DrawList\n    ImDrawList* draw_list = ImPlot::GetPlotDrawList();\n    // calc real value width\n    double half_width = count > 1 ? (xs[1] - xs[0]) * width_percent : width_percent;\n\n    // custom tool\n    if (ImPlot::IsPlotHovered() && tooltip) {\n        ImPlotPoint mouse   = ImPlot::GetPlotMousePos();\n        mouse.x             = ImPlot::RoundTime(ImPlotTime::FromDouble(mouse.x), ImPlotTimeUnit_Day).ToDouble();\n        float  tool_l       = ImPlot::PlotToPixels(mouse.x - half_width * 1.5, mouse.y).x;\n        float  tool_r       = ImPlot::PlotToPixels(mouse.x + half_width * 1.5, mouse.y).x;\n        float  tool_t       = ImPlot::GetPlotPos().y;\n        float  tool_b       = tool_t + ImPlot::GetPlotSize().y;\n        ImPlot::PushPlotClipRect();\n        draw_list->AddRectFilled(ImVec2(tool_l, tool_t), ImVec2(tool_r, tool_b), IM_COL32(128,128,128,64));\n        ImPlot::PopPlotClipRect();\n        // find mouse location index\n        int idx = BinarySearch(xs, 0, count - 1, mouse.x);\n        // render tool tip (won't be affected by plot clip rect)\n        if (idx != -1) {\n            ImGui::BeginTooltip();\n            char buff[32];\n            ImPlot::FormatDate(ImPlotTime::FromDouble(xs[idx]),buff,32,ImPlotDateFmt_DayMoYr,ImPlot::GetStyle().UseISO8601);\n            ImGui::Text(\"Day:   %s\",  buff);\n            ImGui::Text(\"Open:  $%.2f\", opens[idx]);\n            ImGui::Text(\"Close: $%.2f\", closes[idx]);\n            ImGui::Text(\"Low:   $%.2f\", lows[idx]);\n            ImGui::Text(\"High:  $%.2f\", highs[idx]);\n            ImGui::EndTooltip();\n        }\n    }\n\n    // begin plot item\n    if (ImPlot::BeginItem(label_id)) {\n        // override legend icon color\n        ImPlot::GetCurrentItem()->Color = IM_COL32(64,64,64,255);\n        // fit data if requested\n        if (ImPlot::FitThisFrame()) {\n            for (int i = 0; i < count; ++i) {\n                ImPlot::FitPoint(ImPlotPoint(xs[i], lows[i]));\n                ImPlot::FitPoint(ImPlotPoint(xs[i], highs[i]));\n            }\n        }\n        // render data\n        for (int i = 0; i < count; ++i) {\n            ImVec2 open_pos  = ImPlot::PlotToPixels(xs[i] - half_width, opens[i]);\n            ImVec2 close_pos = ImPlot::PlotToPixels(xs[i] + half_width, closes[i]);\n            ImVec2 low_pos   = ImPlot::PlotToPixels(xs[i], lows[i]);\n            ImVec2 high_pos  = ImPlot::PlotToPixels(xs[i], highs[i]);\n            ImU32 color      = ImGui::GetColorU32(opens[i] > closes[i] ? bearCol : bullCol);\n            draw_list->AddLine(low_pos, high_pos, color);\n            draw_list->AddRectFilled(open_pos, close_pos, color);\n        }\n\n        // end plot item\n        ImPlot::EndItem();\n    }\n}\n\n} // namespace MyImplot\n\nnamespace ImPlot {\n\n//-----------------------------------------------------------------------------\n// BENCHMARK\n//-----------------------------------------------------------------------------\n\nstruct BenchData {\n    BenchData() {\n        float y = RandomRange(0.0f,1.0f);\n        Data = new float[1000];\n        for (int i = 0; i < 1000; ++i) {\n            Data[i] = y + RandomRange(-0.01f,0.01f);\n        }\n        Col = ImVec4(RandomRange(0.0f,1.0f),RandomRange(0.0f,1.0f),RandomRange(0.0f,1.0f),0.5f);\n    }\n    ~BenchData() { delete[] Data; }\n    float* Data;\n    ImVec4 Col;\n};\n\nenum BenchMode {\n    Line = 0,\n    LineG = 1,\n    Shaded = 2,\n    Scatter = 3,\n    Bars = 4\n};\n\nstruct BenchRecord {\n    int Mode;\n    bool AA;\n    ImVector<ImPlotPoint> Data;\n};\n\nImPlotPoint BenchmarkGetter(void* data, int idx) {\n    float* values = (float*)data;\n    return ImPlotPoint(idx, values[idx]);\n}\n\nvoid ShowBenchmarkTool() {\n    static const int max_items = 500;\n    static BenchData items[max_items];\n    static bool running = false;\n    static int frames   = 60;\n    static int L        = 0;\n    static int F        = 0;\n    static double t1, t2;\n    static int mode     = BenchMode::Line;\n    const char* names[] = {\"Line\",\"LineG\",\"Shaded\",\"Scatter\",\"Bars\"};\n\n    static ImVector<BenchRecord> records;\n\n    if (running) {\n        F++;\n        if (F == frames) {\n            t2 = ImGui::GetTime();\n            records.back().Data.push_back(ImPlotPoint(L, frames / (t2 - t1)));\n            L  += 5;\n            F  = 0;\n            t1 = ImGui::GetTime();\n        }\n        if (L > max_items) {\n            running = false;\n            L = max_items;\n        }\n    }\n\n    ImGui::Text(\"ImDrawIdx: %d-bit\", (int)(sizeof(ImDrawIdx) * 8));\n    ImGui::Text(\"ImGuiBackendFlags_RendererHasVtxOffset: %s\", (ImGui::GetIO().BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset) ? \"True\" : \"False\");\n    ImGui::Text(\"%.2f FPS\", ImGui::GetIO().Framerate);\n\n    ImGui::Separator();\n\n    bool was_running = running;\n    if (was_running) {\n        ImGui::PushItemFlag(ImGuiItemFlags_Disabled, true);\n        ImGui::PushStyleVar(ImGuiStyleVar_Alpha, ImGui::GetStyle().Alpha * 0.25f);\n    }\n    if (ImGui::Button(\"Benchmark\")) {\n        running = true;\n        L = F = 0;\n        records.push_back(BenchRecord());\n        records.back().Data.reserve(max_items+1);\n        records.back().Mode = mode;\n        records.back().AA   = ImPlot::GetStyle().AntiAliasedLines;\n        t1 = ImGui::GetTime();\n    }\n    ImGui::SameLine();\n    ImGui::SetNextItemWidth(200);\n    ImGui::Combo(\"##Mode\",&mode,names,4);\n    ImGui::SameLine();\n\n    ImGui::Checkbox(\"Anti-Aliased Lines\", &ImPlot::GetStyle().AntiAliasedLines);\n    if (was_running) { ImGui::PopItemFlag(); ImGui::PopStyleVar(); }\n\n    ImGui::ProgressBar((float)L / (float)(max_items - 1));\n\n    if (ImPlot::BeginPlot(\"##Bench\",ImVec2(-1,0),ImPlotFlags_NoChild | ImPlotFlags_CanvasOnly)) {\n        ImPlot::SetupAxes(NULL,NULL,ImPlotAxisFlags_NoDecorations,ImPlotAxisFlags_NoDecorations);\n        ImPlot::SetupAxesLimits(0,1000,0,1,ImGuiCond_Always);\n        if (running) {\n            if (mode == BenchMode::Line) {\n                for (int i = 0; i < L; ++i) {\n                    ImGui::PushID(i);\n                    ImPlot::SetNextLineStyle(items[i].Col);\n                    ImPlot::PlotLine(\"##item\", items[i].Data, 1000);\n                    ImGui::PopID();\n                }\n            }\n            else if (mode == BenchMode::LineG) {\n                for (int i = 0; i < L; ++i) {\n                    ImGui::PushID(i);\n                    ImPlot::SetNextLineStyle(items[i].Col);\n                    ImPlot::PlotLineG(\"##item\",BenchmarkGetter,items[i].Data,1000);\n                    ImGui::PopID();\n                }\n            }\n            else if (mode == BenchMode::Shaded) {\n                for (int i = 0; i < L; ++i) {\n                    ImGui::PushID(i);\n                    ImPlot::SetNextFillStyle(items[i].Col,0.5f);\n                    ImPlot::PlotShaded(\"##item\", items[i].Data, 1000);\n                    ImGui::PopID();\n                }\n            }\n            else if (mode == BenchMode::Scatter) {\n                for (int i = 0; i < L; ++i) {\n                    ImGui::PushID(i);\n                    ImPlot::SetNextLineStyle(items[i].Col);\n                    ImPlot::PlotScatter(\"##item\", items[i].Data, 1000);\n                    ImGui::PopID();\n                }\n            }\n            else if (mode == BenchMode::Bars) {\n                for (int i = 0; i < L; ++i) {\n                    ImGui::PushID(i);\n                    ImPlot::SetNextFillStyle(items[i].Col,0.5f);\n                    ImPlot::PlotBars(\"##item\", items[i].Data, 1000);\n                    ImGui::PopID();\n                }\n            }\n        }\n        ImPlot::EndPlot();\n    }\n    static char buffer[64];\n    if (ImPlot::BeginPlot(\"##Stats\", ImVec2(-1,0), ImPlotFlags_NoChild)) {\n        ImPlot::SetupAxes(\"Items (1,000 pts each)\", \"Framerate (Hz)\");\n        ImPlot::SetupAxesLimits(0,500,0,500,ImGuiCond_Always);\n        for (int run = 0; run < records.size(); ++run) {\n            if (records[run].Data.Size > 1) {\n                sprintf(buffer, \"B%d-%s%s\", run + 1, names[records[run].Mode], records[run].AA ? \"-AA\" : \"\");\n                ImVector<ImPlotPoint>& d = records[run].Data;\n                ImPlot::PlotLine(buffer, &d[0].x, &d[0].y, d.Size, 0, 2*sizeof(double));\n            }\n        }\n        ImPlot::EndPlot();\n    }\n}\n\n}\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/implot/implot_internal.h",
    "content": "// MIT License\n\n// Copyright (c) 2021 Evan Pezent\n\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n// ImPlot v0.13 WIP\n\n// You may use this file to debug, understand or extend ImPlot features but we\n// don't provide any guarantee of forward compatibility!\n\n//-----------------------------------------------------------------------------\n// [SECTION] Header Mess\n//-----------------------------------------------------------------------------\n\n#pragma once\n\n#ifndef IMGUI_DEFINE_MATH_OPERATORS\n#define IMGUI_DEFINE_MATH_OPERATORS\n#endif\n\n#include <time.h>\n#include \"imgui_internal.h\"\n\n#ifndef IMPLOT_VERSION\n#error Must include implot.h before implot_internal.h\n#endif\n\n\n// Support for pre-1.84 versions. ImPool's GetSize() -> GetBufSize()\n#if (IMGUI_VERSION_NUM < 18303)\n#define GetBufSize GetSize\n#endif\n\n//-----------------------------------------------------------------------------\n// [SECTION] Constants\n//-----------------------------------------------------------------------------\n\n// Constants can be changed unless stated otherwise. We may move some of these\n// to ImPlotStyleVar_ over time.\n\n// Mimimum allowable timestamp value 01/01/1970 @ 12:00am (UTC) (DO NOT DECREASE THIS)\n#define IMPLOT_MIN_TIME  0\n// Maximum allowable timestamp value 01/01/3000 @ 12:00am (UTC) (DO NOT INCREASE THIS)\n#define IMPLOT_MAX_TIME  32503680000\n// Default label format for axis labels\n#define IMPLOT_LABEL_FORMAT \"%g\"\n// Max character size for tick labels\n#define IMPLOT_LABEL_MAX_SIZE 32\n// Plot values less than or equal to 0 will be replaced with this on log scale axes\n#define IMPLOT_LOG_ZERO DBL_MIN\n\n//-----------------------------------------------------------------------------\n// [SECTION] Macros\n//-----------------------------------------------------------------------------\n\n#define IMPLOT_NUM_X_AXES ImAxis_Y1\n#define IMPLOT_NUM_Y_AXES (ImAxis_COUNT - IMPLOT_NUM_X_AXES)\n\n// Split ImU32 color into RGB components [0 255]\n#define IM_COL32_SPLIT_RGB(col,r,g,b) \\\n    ImU32 r = ((col >> IM_COL32_R_SHIFT) & 0xFF); \\\n    ImU32 g = ((col >> IM_COL32_G_SHIFT) & 0xFF); \\\n    ImU32 b = ((col >> IM_COL32_B_SHIFT) & 0xFF);\n\n//-----------------------------------------------------------------------------\n// [SECTION] Forward Declarations\n//-----------------------------------------------------------------------------\n\nstruct ImPlotTick;\nstruct ImPlotAxis;\nstruct ImPlotAxisColor;\nstruct ImPlotItem;\nstruct ImPlotLegend;\nstruct ImPlotPlot;\nstruct ImPlotNextPlotData;\n\n//-----------------------------------------------------------------------------\n// [SECTION] Context Pointer\n//-----------------------------------------------------------------------------\n\n#ifndef GImPlot\nextern IMPLOT_API ImPlotContext* GImPlot; // Current implicit context pointer\n#endif\n\n//-----------------------------------------------------------------------------\n// [SECTION] Generic Helpers\n//-----------------------------------------------------------------------------\n\n// Computes the common (base-10) logarithm\nstatic inline float  ImLog10(float x)  { return log10f(x); }\nstatic inline double ImLog10(double x) { return log10(x);  }\n// Returns true if a flag is set\ntemplate <typename TSet, typename TFlag>\nstatic inline bool ImHasFlag(TSet set, TFlag flag) { return (set & flag) == flag; }\n// Flips a flag in a flagset\ntemplate <typename TSet, typename TFlag>\nstatic inline void ImFlipFlag(TSet& set, TFlag flag) { ImHasFlag(set, flag) ? set &= ~flag : set |= flag; }\n// Linearly remaps x from [x0 x1] to [y0 y1].\ntemplate <typename T>\nstatic inline T ImRemap(T x, T x0, T x1, T y0, T y1) { return y0 + (x - x0) * (y1 - y0) / (x1 - x0); }\n// Linear rempas x from [x0 x1] to [0 1]\ntemplate <typename T>\nstatic inline T ImRemap01(T x, T x0, T x1) { return (x - x0) / (x1 - x0); }\n// Returns always positive modulo (assumes r != 0)\nstatic inline int ImPosMod(int l, int r) { return (l % r + r) % r; }\n// Returns true if val is NAN or INFINITY\nstatic inline bool ImNanOrInf(double val) { return !(val >= -DBL_MAX && val <= DBL_MAX) || isnan(val); }\n// Turns NANs to 0s\nstatic inline double ImConstrainNan(double val) { return isnan(val) ? 0 : val; }\n// Turns infinity to floating point maximums\nstatic inline double ImConstrainInf(double val) { return val >= DBL_MAX ?  DBL_MAX : val <= -DBL_MAX ? - DBL_MAX : val; }\n// Turns numbers less than or equal to 0 to 0.001 (sort of arbitrary, is there a better way?)\nstatic inline double ImConstrainLog(double val) { return val <= 0 ? 0.001f : val; }\n// Turns numbers less than 0 to zero\nstatic inline double ImConstrainTime(double val) { return val < IMPLOT_MIN_TIME ? IMPLOT_MIN_TIME : (val > IMPLOT_MAX_TIME ? IMPLOT_MAX_TIME : val); }\n// True if two numbers are approximately equal using units in the last place.\nstatic inline bool ImAlmostEqual(double v1, double v2, int ulp = 2) { return ImAbs(v1-v2) < DBL_EPSILON * ImAbs(v1+v2) * ulp || ImAbs(v1-v2) < DBL_MIN; }\n// Finds min value in an unsorted array\ntemplate <typename T>\nstatic inline T ImMinArray(const T* values, int count) { T m = values[0]; for (int i = 1; i < count; ++i) { if (values[i] < m) { m = values[i]; } } return m; }\n// Finds the max value in an unsorted array\ntemplate <typename T>\nstatic inline T ImMaxArray(const T* values, int count) { T m = values[0]; for (int i = 1; i < count; ++i) { if (values[i] > m) { m = values[i]; } } return m; }\n// Finds the min and max value in an unsorted array\ntemplate <typename T>\nstatic inline void ImMinMaxArray(const T* values, int count, T* min_out, T* max_out) {\n    T Min = values[0]; T Max = values[0];\n    for (int i = 1; i < count; ++i) {\n        if (values[i] < Min) { Min = values[i]; }\n        if (values[i] > Max) { Max = values[i]; }\n    }\n    *min_out = Min; *max_out = Max;\n}\n// Finds the sim of an array\ntemplate <typename T>\nstatic inline T ImSum(const T* values, int count) {\n    T sum  = 0;\n    for (int i = 0; i < count; ++i)\n        sum += values[i];\n    return sum;\n}\n// Finds the mean of an array\ntemplate <typename T>\nstatic inline double ImMean(const T* values, int count) {\n    double den = 1.0 / count;\n    double mu  = 0;\n    for (int i = 0; i < count; ++i)\n        mu += values[i] * den;\n    return mu;\n}\n// Finds the sample standard deviation of an array\ntemplate <typename T>\nstatic inline double ImStdDev(const T* values, int count) {\n    double den = 1.0 / (count - 1.0);\n    double mu  = ImMean(values, count);\n    double x   = 0;\n    for (int i = 0; i < count; ++i)\n        x += (values[i] - mu) * (values[i] - mu) * den;\n    return sqrt(x);\n}\n// Mix color a and b by factor s in [0 256]\nstatic inline ImU32 ImMixU32(ImU32 a, ImU32 b, ImU32 s) {\n#ifdef IMPLOT_MIX64\n    const ImU32 af = 256-s;\n    const ImU32 bf = s;\n    const ImU64 al = (a & 0x00ff00ff) | (((ImU64)(a & 0xff00ff00)) << 24);\n    const ImU64 bl = (b & 0x00ff00ff) | (((ImU64)(b & 0xff00ff00)) << 24);\n    const ImU64 mix = (al * af + bl * bf);\n    return ((mix >> 32) & 0xff00ff00) | ((mix & 0xff00ff00) >> 8);\n#else\n    const ImU32 af = 256-s;\n    const ImU32 bf = s;\n    const ImU32 al = (a & 0x00ff00ff);\n    const ImU32 ah = (a & 0xff00ff00) >> 8;\n    const ImU32 bl = (b & 0x00ff00ff);\n    const ImU32 bh = (b & 0xff00ff00) >> 8;\n    const ImU32 ml = (al * af + bl * bf);\n    const ImU32 mh = (ah * af + bh * bf);\n    return (mh & 0xff00ff00) | ((ml & 0xff00ff00) >> 8);\n#endif\n}\n\n// Lerp across an array of 32-bit collors given t in [0.0 1.0]\nstatic inline ImU32 ImLerpU32(const ImU32* colors, int size, float t) {\n    int i1 = (int)((size - 1 ) * t);\n    int i2 = i1 + 1;\n    if (i2 == size || size == 1)\n        return colors[i1];\n    float den = 1.0f / (size - 1);\n    float t1 = i1 * den;\n    float t2 = i2 * den;\n    float tr = ImRemap01(t, t1, t2);\n    return ImMixU32(colors[i1], colors[i2], (ImU32)(tr*256));\n}\n\n// Set alpha channel of 32-bit color from float in range [0.0 1.0]\nstatic inline ImU32 ImAlphaU32(ImU32 col, float alpha) {\n    return col & ~((ImU32)((1.0f-alpha)*255)<<IM_COL32_A_SHIFT);\n}\n\n//-----------------------------------------------------------------------------\n// [SECTION] ImPlot Enums\n//-----------------------------------------------------------------------------\n\ntypedef int ImPlotScale;       // -> enum ImPlotScale_\ntypedef int ImPlotTimeUnit;    // -> enum ImPlotTimeUnit_\ntypedef int ImPlotDateFmt;     // -> enum ImPlotDateFmt_\ntypedef int ImPlotTimeFmt;     // -> enum ImPlotTimeFmt_\n\n// XY axes scaling combinations\nenum ImPlotScale_ {\n    ImPlotScale_LinLin, // linear x, linear y\n    ImPlotScale_LogLin, // log x,    linear y\n    ImPlotScale_LinLog, // linear x, log y\n    ImPlotScale_LogLog  // log x,    log y\n};\n\nenum ImPlotTimeUnit_ {\n    ImPlotTimeUnit_Us,  // microsecond\n    ImPlotTimeUnit_Ms,  // millisecond\n    ImPlotTimeUnit_S,   // second\n    ImPlotTimeUnit_Min, // minute\n    ImPlotTimeUnit_Hr,  // hour\n    ImPlotTimeUnit_Day, // day\n    ImPlotTimeUnit_Mo,  // month\n    ImPlotTimeUnit_Yr,  // year\n    ImPlotTimeUnit_COUNT\n};\n\nenum ImPlotDateFmt_ {              // default        [ ISO 8601     ]\n    ImPlotDateFmt_None = 0,\n    ImPlotDateFmt_DayMo,           // 10/3           [ --10-03      ]\n    ImPlotDateFmt_DayMoYr,         // 10/3/91        [ 1991-10-03   ]\n    ImPlotDateFmt_MoYr,            // Oct 1991       [ 1991-10      ]\n    ImPlotDateFmt_Mo,              // Oct            [ --10         ]\n    ImPlotDateFmt_Yr               // 1991           [ 1991         ]\n};\n\nenum ImPlotTimeFmt_ {              // default        [ 24 Hour Clock ]\n    ImPlotTimeFmt_None = 0,\n    ImPlotTimeFmt_Us,              // .428 552       [ .428 552     ]\n    ImPlotTimeFmt_SUs,             // :29.428 552    [ :29.428 552  ]\n    ImPlotTimeFmt_SMs,             // :29.428        [ :29.428      ]\n    ImPlotTimeFmt_S,               // :29            [ :29          ]\n    ImPlotTimeFmt_HrMinSMs,        // 7:21:29.428pm  [ 19:21:29.428 ]\n    ImPlotTimeFmt_HrMinS,          // 7:21:29pm      [ 19:21:29     ]\n    ImPlotTimeFmt_HrMin,           // 7:21pm         [ 19:21        ]\n    ImPlotTimeFmt_Hr               // 7pm            [ 19:00        ]\n};\n\n//-----------------------------------------------------------------------------\n// [SECTION] ImPlot Structs\n//-----------------------------------------------------------------------------\n\n// Combined date/time format spec\nstruct ImPlotDateTimeFmt {\n    ImPlotDateTimeFmt(ImPlotDateFmt date_fmt, ImPlotTimeFmt time_fmt, bool use_24_hr_clk = false, bool use_iso_8601 = false) {\n        Date           = date_fmt;\n        Time           = time_fmt;\n        UseISO8601     = use_iso_8601;\n        Use24HourClock = use_24_hr_clk;\n    }\n    ImPlotDateFmt Date;\n    ImPlotTimeFmt Time;\n    bool UseISO8601;\n    bool Use24HourClock;\n};\n\n// Two part timestamp struct.\nstruct ImPlotTime {\n    time_t S;  // second part\n    int    Us; // microsecond part\n    ImPlotTime() { S = 0; Us = 0; }\n    ImPlotTime(time_t s, int us = 0) { S  = s + us / 1000000; Us = us % 1000000; }\n    void RollOver() { S  = S + Us / 1000000;  Us = Us % 1000000; }\n    double ToDouble() const { return (double)S + (double)Us / 1000000.0; }\n    static ImPlotTime FromDouble(double t) { return ImPlotTime((time_t)t, (int)(t * 1000000 - floor(t) * 1000000)); }\n};\n\nstatic inline ImPlotTime operator+(const ImPlotTime& lhs, const ImPlotTime& rhs)\n{ return ImPlotTime(lhs.S + rhs.S, lhs.Us + rhs.Us); }\nstatic inline ImPlotTime operator-(const ImPlotTime& lhs, const ImPlotTime& rhs)\n{ return ImPlotTime(lhs.S - rhs.S, lhs.Us - rhs.Us); }\nstatic inline bool operator==(const ImPlotTime& lhs, const ImPlotTime& rhs)\n{ return lhs.S == rhs.S && lhs.Us == rhs.Us; }\nstatic inline bool operator<(const ImPlotTime& lhs, const ImPlotTime& rhs)\n{ return lhs.S == rhs.S ? lhs.Us < rhs.Us : lhs.S < rhs.S; }\nstatic inline bool operator>(const ImPlotTime& lhs, const ImPlotTime& rhs)\n{ return rhs < lhs; }\nstatic inline bool operator<=(const ImPlotTime& lhs, const ImPlotTime& rhs)\n{ return lhs < rhs || lhs == rhs; }\nstatic inline bool operator>=(const ImPlotTime& lhs, const ImPlotTime& rhs)\n{ return lhs > rhs || lhs == rhs; }\n\n// Colormap data storage\nstruct ImPlotColormapData {\n    ImVector<ImU32> Keys;\n    ImVector<int>   KeyCounts;\n    ImVector<int>   KeyOffsets;\n    ImVector<ImU32> Tables;\n    ImVector<int>   TableSizes;\n    ImVector<int>   TableOffsets;\n    ImGuiTextBuffer Text;\n    ImVector<int>   TextOffsets;\n    ImVector<bool>  Quals;\n    ImGuiStorage    Map;\n    int             Count;\n\n    ImPlotColormapData() { Count = 0; }\n\n    int Append(const char* name, const ImU32* keys, int count, bool qual) {\n        if (GetIndex(name) != -1)\n            return -1;\n        KeyOffsets.push_back(Keys.size());\n        KeyCounts.push_back(count);\n        Keys.reserve(Keys.size()+count);\n        for (int i = 0; i < count; ++i)\n            Keys.push_back(keys[i]);\n        TextOffsets.push_back(Text.size());\n        Text.append(name, name + strlen(name) + 1);\n        Quals.push_back(qual);\n        ImGuiID id = ImHashStr(name);\n        int idx = Count++;\n        Map.SetInt(id,idx);\n        _AppendTable(idx);\n        return idx;\n    }\n\n    void _AppendTable(ImPlotColormap cmap) {\n        int key_count     = GetKeyCount(cmap);\n        const ImU32* keys = GetKeys(cmap);\n        int off = Tables.size();\n        TableOffsets.push_back(off);\n        if (IsQual(cmap)) {\n            Tables.reserve(key_count);\n            for (int i = 0; i < key_count; ++i)\n                Tables.push_back(keys[i]);\n            TableSizes.push_back(key_count);\n        }\n        else {\n            int max_size = 255 * (key_count-1) + 1;\n            Tables.reserve(off + max_size);\n            // ImU32 last = keys[0];\n            // Tables.push_back(last);\n            // int n = 1;\n            for (int i = 0; i < key_count-1; ++i) {\n                for (int s = 0; s < 255; ++s) {\n                    ImU32 a = keys[i];\n                    ImU32 b = keys[i+1];\n                    ImU32 c = ImMixU32(a,b,s);\n                    // if (c != last) {\n                        Tables.push_back(c);\n                        // last = c;\n                        // n++;\n                    // }\n                }\n            }\n            ImU32 c = keys[key_count-1];\n            // if (c != last) {\n                Tables.push_back(c);\n                // n++;\n            // }\n            // TableSizes.push_back(n);\n            TableSizes.push_back(max_size);\n        }\n    }\n\n    void RebuildTables() {\n        Tables.resize(0);\n        TableSizes.resize(0);\n        TableOffsets.resize(0);\n        for (int i = 0; i < Count; ++i)\n            _AppendTable(i);\n    }\n\n    inline bool           IsQual(ImPlotColormap cmap) const                      { return Quals[cmap];                                             }\n    inline const char*    GetName(ImPlotColormap cmap) const                     { return cmap < Count ? Text.Buf.Data + TextOffsets[cmap] : NULL; }\n    inline ImPlotColormap GetIndex(const char* name) const                       { ImGuiID key = ImHashStr(name); return Map.GetInt(key,-1);       }\n\n    inline const ImU32*   GetKeys(ImPlotColormap cmap) const                     { return &Keys[KeyOffsets[cmap]];                                 }\n    inline int            GetKeyCount(ImPlotColormap cmap) const                 { return KeyCounts[cmap];                                         }\n    inline ImU32          GetKeyColor(ImPlotColormap cmap, int idx) const        { return Keys[KeyOffsets[cmap]+idx];                              }\n    inline void           SetKeyColor(ImPlotColormap cmap, int idx, ImU32 value) { Keys[KeyOffsets[cmap]+idx] = value; RebuildTables();            }\n\n    inline const ImU32*   GetTable(ImPlotColormap cmap) const                    { return &Tables[TableOffsets[cmap]];                             }\n    inline int            GetTableSize(ImPlotColormap cmap) const                { return TableSizes[cmap];                                        }\n    inline ImU32          GetTableColor(ImPlotColormap cmap, int idx) const      { return Tables[TableOffsets[cmap]+idx];                          }\n\n    inline ImU32 LerpTable(ImPlotColormap cmap, float t) const {\n        int off = TableOffsets[cmap];\n        int siz = TableSizes[cmap];\n        int idx = Quals[cmap] ? ImClamp((int)(siz*t),0,siz-1) : (int)((siz - 1) * t + 0.5f);\n        return Tables[off + idx];\n    }\n\n};\n\n// ImPlotPoint with positive/negative error values\nstruct ImPlotPointError {\n    double X, Y, Neg, Pos;\n    ImPlotPointError(double x, double y, double neg, double pos) {\n        X = x; Y = y; Neg = neg; Pos = pos;\n    }\n};\n\n// Interior plot label/annotation\nstruct ImPlotAnnotation {\n    ImVec2 Pos;\n    ImVec2 Offset;\n    ImU32  ColorBg;\n    ImU32  ColorFg;\n    int    TextOffset;\n    bool   Clamp;\n};\n\n// Collection of plot labels\nstruct ImPlotAnnotationCollection {\n\n    ImVector<ImPlotAnnotation> Annotations;\n    ImGuiTextBuffer            TextBuffer;\n    int                        Size;\n\n    ImPlotAnnotationCollection() { Reset(); }\n\n    void AppendV(const ImVec2& pos, const ImVec2& off, ImU32 bg, ImU32 fg, bool clamp, const char* fmt,  va_list args) IM_FMTLIST(7) {\n        ImPlotAnnotation an;\n        an.Pos = pos; an.Offset = off;\n        an.ColorBg = bg; an.ColorFg = fg;\n        an.TextOffset = TextBuffer.size();\n        an.Clamp = clamp;\n        Annotations.push_back(an);\n        TextBuffer.appendfv(fmt, args);\n        const char nul[] = \"\";\n        TextBuffer.append(nul,nul+1);\n        Size++;\n    }\n\n    void Append(const ImVec2& pos, const ImVec2& off, ImU32 bg, ImU32 fg, bool clamp, const char* fmt,  ...) IM_FMTARGS(7) {\n        va_list args;\n        va_start(args, fmt);\n        AppendV(pos, off, bg, fg, clamp, fmt, args);\n        va_end(args);\n    }\n\n    const char* GetText(int idx) {\n        return TextBuffer.Buf.Data + Annotations[idx].TextOffset;\n    }\n\n    void Reset() {\n        Annotations.shrink(0);\n        TextBuffer.Buf.shrink(0);\n        Size = 0;\n    }\n};\n\nstruct ImPlotTag {\n    ImAxis Axis;\n    double Value;\n    ImU32  ColorBg;\n    ImU32  ColorFg;\n    int    TextOffset;\n};\n\nstruct ImPlotTagCollection {\n\n    ImVector<ImPlotTag> Tags;\n    ImGuiTextBuffer     TextBuffer;\n    int                 Size;\n\n    ImPlotTagCollection() { Reset(); }\n\n    void AppendV(ImAxis axis, double value, ImU32 bg, ImU32 fg, const char* fmt, va_list args) IM_FMTLIST(6) {\n        ImPlotTag tag;\n        tag.Axis = axis;\n        tag.Value = value;\n        tag.ColorBg = bg;\n        tag.ColorFg = fg;\n        tag.TextOffset = TextBuffer.size();\n        Tags.push_back(tag);\n        TextBuffer.appendfv(fmt, args);\n        const char nul[] = \"\";\n        TextBuffer.append(nul,nul+1);\n        Size++;\n    }\n\n    void Append(ImAxis axis, double value, ImU32 bg, ImU32 fg, const char* fmt, ...) IM_FMTARGS(6) {\n        va_list args;\n        va_start(args, fmt);\n        AppendV(axis, value, bg, fg, fmt, args);\n        va_end(args);\n    }\n\n    const char* GetText(int idx) {\n        return TextBuffer.Buf.Data + Tags[idx].TextOffset;\n    }\n\n    void Reset() {\n        Tags.shrink(0);\n        TextBuffer.Buf.shrink(0);\n        Size = 0;\n    }\n};\n\n// Tick mark info\nstruct ImPlotTick\n{\n    double PlotPos;\n    float  PixelPos;\n    ImVec2 LabelSize;\n    int    TextOffset;\n    bool   Major;\n    bool   ShowLabel;\n    int    Level;\n\n    ImPlotTick(double value, bool major, bool show_label) {\n        PlotPos      = value;\n        Major        = major;\n        ShowLabel    = show_label;\n        TextOffset   = -1;\n        Level        = 0;\n    }\n};\n\n// Collection of ticks\nstruct ImPlotTickCollection {\n    ImVector<ImPlotTick> Ticks;\n    ImGuiTextBuffer      TextBuffer;\n    ImVec2               MaxSize;\n    ImVec2               LateSize;\n    int                  Size;\n\n    ImPlotTickCollection() { Reset(); }\n\n    const ImPlotTick& Append(const ImPlotTick& tick) {\n        if (tick.ShowLabel) {\n            MaxSize.x     =  tick.LabelSize.x > MaxSize.x ? tick.LabelSize.x : MaxSize.x;\n            MaxSize.y     =  tick.LabelSize.y > MaxSize.y ? tick.LabelSize.y : MaxSize.y;\n        }\n        Ticks.push_back(tick);\n        Size++;\n        return Ticks.back();\n    }\n\n    const ImPlotTick& Append(double value, bool major, bool show_label, ImPlotFormatter formatter, void* data) {\n        ImPlotTick tick(value, major, show_label);\n        if (show_label && formatter != NULL) {\n            char buff[IMPLOT_LABEL_MAX_SIZE];\n            tick.TextOffset = TextBuffer.size();\n            formatter(tick.PlotPos, buff, sizeof(buff), data);\n            TextBuffer.append(buff, buff + strlen(buff) + 1);\n            tick.LabelSize = ImGui::CalcTextSize(TextBuffer.Buf.Data + tick.TextOffset);\n        }\n        return Append(tick);\n    }\n\n    const char* GetText(int idx) const {\n        return TextBuffer.Buf.Data + Ticks[idx].TextOffset;\n    }\n\n    void OverrideSize(const ImVec2& size) {\n        MaxSize.x = size.x > MaxSize.x ? size.x : MaxSize.x;\n        MaxSize.y = size.y > MaxSize.y ? size.y : MaxSize.y;\n    }\n\n    void OverrideSizeLate(const ImVec2& size) {\n        LateSize.x = size.x > LateSize.x ? size.x : LateSize.x;\n        LateSize.y = size.y > LateSize.y ? size.y : LateSize.y;\n    }\n\n    void Reset() {\n        Ticks.shrink(0);\n        TextBuffer.Buf.shrink(0);\n        MaxSize = LateSize;\n        LateSize = ImVec2(0,0);\n        Size = 0;\n    }\n};\n\n// Axis state information that must persist after EndPlot\nstruct ImPlotAxis\n{\n    ImGuiID              ID;\n    ImPlotAxisFlags      Flags;\n    ImPlotAxisFlags      PreviousFlags;\n    ImPlotCond           RangeCond;\n    ImPlotTickCollection Ticks;\n    ImPlotRange          Range;\n    ImPlotRange          FitExtents;\n    ImPlotAxis*          OrthoAxis;\n    double*              LinkedMin;\n    double*              LinkedMax;\n    int                  PickerLevel;\n    ImPlotTime           PickerTimeMin, PickerTimeMax;\n    float                Datum1, Datum2;\n    float                PixelMin, PixelMax;\n    double               LinM, LogD;\n    ImRect               HoverRect;\n    int                  LabelOffset;\n    ImU32                ColorMaj, ColorMin, ColorTick, ColorTxt, ColorBg, ColorHov, ColorAct, ColorHiLi;\n    char                 FormatSpec[16];\n    ImPlotFormatter      Formatter;\n    void*                FormatterData;\n    bool                 Enabled;\n    bool                 Vertical;\n    bool                 FitThisFrame;\n    bool                 HasRange;\n    bool                 HasFormatSpec;\n    bool                 ShowDefaultTicks;\n    bool                 Hovered;\n    bool                 Held;\n\n    ImPlotAxis() {\n        Flags            = PreviousFlags = ImPlotAxisFlags_None;\n        Range.Min        = 0;\n        Range.Max        = 1;\n        FitExtents.Min   = HUGE_VAL;\n        FitExtents.Max   = -HUGE_VAL;\n        OrthoAxis        = NULL;\n        LinkedMin        = LinkedMax = NULL;\n        PickerLevel      = 0;\n        Datum1           = Datum2 = 0;\n        PixelMin         = PixelMax = 0;\n        LabelOffset      = -1;\n        ColorMaj         = ColorMin = ColorTick = ColorTxt = ColorBg = ColorHov = ColorAct = 0;\n        ColorHiLi        = IM_COL32_BLACK_TRANS;\n        Formatter        = NULL;\n        FormatterData    = NULL;\n        Enabled          = Hovered = Held = FitThisFrame = HasRange = HasFormatSpec = false;\n        ShowDefaultTicks = true;\n    }\n\n    inline void Reset() {\n        Enabled          = false;\n        LabelOffset      = -1;\n        HasFormatSpec    = false;\n        Formatter        = NULL;\n        FormatterData    = NULL;\n        ShowDefaultTicks = true;\n        FitThisFrame     = false;\n        FitExtents.Min   = HUGE_VAL;\n        FitExtents.Max   = -HUGE_VAL;\n        OrthoAxis        = NULL;\n        Ticks.Reset();\n    }\n\n    inline bool SetMin(double _min, bool force=false) {\n        if (!force && IsLockedMin())\n            return false;\n        _min = ImConstrainNan(ImConstrainInf(_min));\n        if (ImHasFlag(Flags, ImPlotAxisFlags_LogScale))\n            _min = ImConstrainLog(_min);\n        if (ImHasFlag(Flags, ImPlotAxisFlags_Time))\n            _min = ImConstrainTime(_min);\n        if (_min >= Range.Max)\n            return false;\n        Range.Min = _min;\n        PickerTimeMin = ImPlotTime::FromDouble(Range.Min);\n        UpdateTransformCache();\n        return true;\n    };\n\n    inline bool SetMax(double _max, bool force=false) {\n        if (!force && IsLockedMax())\n            return false;\n        _max = ImConstrainNan(ImConstrainInf(_max));\n        if (ImHasFlag(Flags, ImPlotAxisFlags_LogScale))\n            _max = ImConstrainLog(_max);\n        if (ImHasFlag(Flags, ImPlotAxisFlags_Time))\n            _max = ImConstrainTime(_max);\n        if (_max <= Range.Min)\n            return false;\n        Range.Max = _max;\n        PickerTimeMax = ImPlotTime::FromDouble(Range.Max);\n        UpdateTransformCache();\n        return true;\n    };\n\n    inline void SetRange(double v1, double v2) {\n        Range.Min = ImMin(v1,v2);\n        Range.Max = ImMax(v1,v2);\n        Constrain();\n        PickerTimeMin = ImPlotTime::FromDouble(Range.Min);\n        PickerTimeMax = ImPlotTime::FromDouble(Range.Max);\n        UpdateTransformCache();\n    }\n\n    inline void SetRange(const ImPlotRange& range) {\n        SetRange(range.Min, range.Max);\n    }\n\n    inline void SetAspect(double unit_per_pix) {\n        double new_size = unit_per_pix * PixelSize();\n        double delta    = (new_size - Range.Size()) * 0.5f;\n        if (IsLocked())\n            return;\n        else if (IsLockedMin() && !IsLockedMax())\n            SetRange(Range.Min, Range.Max  + 2*delta);\n        else if (!IsLockedMin() && IsLockedMax())\n            SetRange(Range.Min - 2*delta, Range.Max);\n        else\n            SetRange(Range.Min - delta, Range.Max + delta);\n    }\n\n    inline float PixelSize() const { return ImAbs(PixelMax - PixelMin); }\n\n    inline double GetAspect() const { return Range.Size() / PixelSize(); }\n\n    inline void Constrain() {\n        Range.Min = ImConstrainNan(ImConstrainInf(Range.Min));\n        Range.Max = ImConstrainNan(ImConstrainInf(Range.Max));\n        if (IsLog()) {\n            Range.Min = ImConstrainLog(Range.Min);\n            Range.Max = ImConstrainLog(Range.Max);\n        }\n        if (IsTime()) {\n            Range.Min = ImConstrainTime(Range.Min);\n            Range.Max = ImConstrainTime(Range.Max);\n        }\n        if (Range.Max <= Range.Min)\n            Range.Max = Range.Min + DBL_EPSILON;\n    }\n\n    inline void UpdateTransformCache() {\n        LinM = (PixelMax - PixelMin) / Range.Size();\n        LogD = IsLog() ? ImLog10(Range.Max / Range.Min) : 0;\n    }\n\n    inline double PixelsToPlot(float pix) const {\n        double plt = (pix - PixelMin) / LinM + Range.Min;\n        if (IsLog()) {\n            double t = (plt - Range.Min) / Range.Size();\n            plt = ImPow(10, t * LogD) * Range.Min;\n        }\n        return plt;\n    }\n\n    inline float PlotToPixels(double plt) const {\n        if (IsLog()) {\n            plt      = plt <= 0.0 ? IMPLOT_LOG_ZERO : plt;\n            double t = ImLog10(plt / Range.Min) / LogD;\n            plt      = ImLerp(Range.Min, Range.Max, (float)t);\n        }\n        return (float)(PixelMin + LinM * (plt - Range.Min));\n    }\n\n    inline void ExtendFit(double v) {\n        if (!ImNanOrInf(v) && !(IsLog() && v <= 0)) {\n            FitExtents.Min = v < FitExtents.Min ? v : FitExtents.Min;\n            FitExtents.Max = v > FitExtents.Max ? v : FitExtents.Max;\n        }\n    }\n\n    inline void ExtendFitWith(ImPlotAxis& alt, double v, double v_alt) {\n        if (ImHasFlag(Flags, ImPlotAxisFlags_RangeFit) && !alt.Range.Contains(v_alt))\n            return;\n        if (!ImNanOrInf(v) && !(IsLog() && v <= 0)) {\n            FitExtents.Min = v < FitExtents.Min ? v : FitExtents.Min;\n            FitExtents.Max = v > FitExtents.Max ? v : FitExtents.Max;\n        }\n    }\n\n    inline void ApplyFit(float padding) {\n        const double ext_size = FitExtents.Size() * 0.5;\n        FitExtents.Min -= ext_size * padding;\n        FitExtents.Max += ext_size * padding;\n        if (!IsLockedMin() && !ImNanOrInf(FitExtents.Min))\n            Range.Min = FitExtents.Min;\n        if (!IsLockedMax() && !ImNanOrInf(FitExtents.Max))\n            Range.Max = FitExtents.Max;\n        if (ImAlmostEqual(Range.Min, Range.Max))  {\n            Range.Max += 0.5;\n            Range.Min -= 0.5;\n        }\n        Constrain();\n        UpdateTransformCache();\n    }\n\n    inline bool HasLabel()          const { return LabelOffset != -1 && !ImHasFlag(Flags, ImPlotAxisFlags_NoLabel);                          }\n    inline bool HasGridLines()      const { return !ImHasFlag(Flags, ImPlotAxisFlags_NoGridLines);                                           }\n    inline bool HasTickLabels()     const { return !ImHasFlag(Flags, ImPlotAxisFlags_NoTickLabels);                                          }\n    inline bool HasTickMarks()      const { return !ImHasFlag(Flags, ImPlotAxisFlags_NoTickMarks);                                           }\n    inline bool WillRender()        const { return HasGridLines() || HasTickLabels() || HasTickMarks();                                      }\n    inline bool IsOpposite()        const { return ImHasFlag(Flags, ImPlotAxisFlags_Opposite);                                               }\n    inline bool IsInverted()        const { return ImHasFlag(Flags, ImPlotAxisFlags_Invert);                                                 }\n    inline bool IsForeground()      const { return ImHasFlag(Flags, ImPlotAxisFlags_Foreground);                                             }\n    inline bool IsAutoFitting()     const { return ImHasFlag(Flags, ImPlotAxisFlags_AutoFit);                                                }\n    inline bool CanInitFit()        const { return !ImHasFlag(Flags, ImPlotAxisFlags_NoInitialFit) && !HasRange && !LinkedMin && !LinkedMax; }\n    inline bool IsRangeLocked()     const { return HasRange && RangeCond == ImPlotCond_Always;                                                }\n    inline bool IsLockedMin()       const { return !Enabled || IsRangeLocked() || ImHasFlag(Flags, ImPlotAxisFlags_LockMin);                 }\n    inline bool IsLockedMax()       const { return !Enabled || IsRangeLocked() || ImHasFlag(Flags, ImPlotAxisFlags_LockMax);                 }\n    inline bool IsLocked()          const { return IsLockedMin() && IsLockedMax();                                                           }\n    inline bool IsInputLockedMin()  const { return IsLockedMin() || IsAutoFitting();                                                         }\n    inline bool IsInputLockedMax()  const { return IsLockedMax() || IsAutoFitting();                                                         }\n    inline bool IsInputLocked()     const { return IsLocked()    || IsAutoFitting();                                                         }\n    inline bool IsTime()            const { return ImHasFlag(Flags, ImPlotAxisFlags_Time);                                                   }\n    inline bool IsLog()             const { return ImHasFlag(Flags, ImPlotAxisFlags_LogScale);                                               }\n    inline bool HasMenus()          const { return !ImHasFlag(Flags, ImPlotAxisFlags_NoMenus);                                               }\n\n    void PushLinks() {\n        if (LinkedMin) { *LinkedMin = Range.Min; }\n        if (LinkedMax) { *LinkedMax = Range.Max; }\n    }\n\n    void PullLinks() {\n        if (LinkedMin) { SetMin(*LinkedMin,true); }\n        if (LinkedMax) { SetMax(*LinkedMax,true); }\n    }\n};\n\n// Align plots group data\nstruct ImPlotAlignmentData {\n    bool  Vertical;\n    float PadA;\n    float PadB;\n    float PadAMax;\n    float PadBMax;\n    ImPlotAlignmentData() {\n        Vertical    = true;\n        PadA = PadB = PadAMax = PadBMax = 0;\n    }\n    void Begin() { PadAMax = PadBMax = 0; }\n    void Update(float& pad_a, float& pad_b, float& delta_a, float& delta_b) {\n        float bak_a = pad_a; float bak_b = pad_b;\n        if (PadAMax < pad_a) { PadAMax = pad_a; }\n        if (PadBMax < pad_b) { PadBMax = pad_b; }\n        if (pad_a < PadA)    { pad_a = PadA; delta_a = pad_a - bak_a; } else { delta_a = 0; }\n        if (pad_b < PadB)    { pad_b = PadB; delta_b = pad_b - bak_b; } else { delta_b = 0; }\n    }\n    void End()   { PadA = PadAMax; PadB = PadBMax;      }\n    void Reset() { PadA = PadB = PadAMax = PadBMax = 0; }\n};\n\n// State information for Plot items\nstruct ImPlotItem\n{\n    ImGuiID      ID;\n    ImU32        Color;\n    ImRect       LegendHoverRect;\n    int          NameOffset;\n    bool         Show;\n    bool         LegendHovered;\n    bool         SeenThisFrame;\n\n    ImPlotItem() {\n        ID            = 0;\n        NameOffset    = -1;\n        Show          = true;\n        SeenThisFrame = false;\n        LegendHovered = false;\n    }\n\n    ~ImPlotItem() { ID = 0; }\n};\n\n// Holds Legend state\nstruct ImPlotLegend\n{\n    ImPlotLegendFlags Flags;\n    ImPlotLegendFlags PreviousFlags;\n    ImPlotLocation    Location;\n    ImPlotLocation    PreviousLocation;\n    ImVector<int>     Indices;\n    ImGuiTextBuffer   Labels;\n    ImRect            Rect;\n    bool              Hovered;\n    bool              Held;\n    bool              CanGoInside;\n\n    ImPlotLegend() {\n        Flags        = PreviousFlags = ImPlotLegendFlags_None;\n        CanGoInside  = true;\n        Hovered      = Held = false;\n        Location     = ImPlotLocation_NorthWest;\n    }\n\n    void Reset() { Indices.shrink(0); Labels.Buf.shrink(0); }\n};\n\n// Holds Items and Legend data\nstruct ImPlotItemGroup\n{\n    ImGuiID            ID;\n    ImPlotLegend       Legend;\n    ImPool<ImPlotItem> ItemPool;\n    int                ColormapIdx;\n\n    ImPlotItemGroup() { ColormapIdx = 0; }\n\n    int         GetItemCount() const             { return ItemPool.GetBufSize();                                 }\n    ImGuiID     GetItemID(const char*  label_id) { return ImGui::GetID(label_id); /* GetIDWithSeed */            }\n    ImPlotItem* GetItem(ImGuiID id)              { return ItemPool.GetByKey(id);                                 }\n    ImPlotItem* GetItem(const char* label_id)    { return GetItem(GetItemID(label_id));                          }\n    ImPlotItem* GetOrAddItem(ImGuiID id)         { return ItemPool.GetOrAddByKey(id);                            }\n    ImPlotItem* GetItemByIndex(int i)            { return ItemPool.GetByIndex(i);                                }\n    int         GetItemIndex(ImPlotItem* item)   { return ItemPool.GetIndex(item);                               }\n    int         GetLegendCount() const           { return Legend.Indices.size();                                 }\n    ImPlotItem* GetLegendItem(int i)             { return ItemPool.GetByIndex(Legend.Indices[i]);                }\n    const char* GetLegendLabel(int i)            { return Legend.Labels.Buf.Data + GetLegendItem(i)->NameOffset; }\n    void        Reset()                          { ItemPool.Clear(); Legend.Reset(); ColormapIdx = 0;            }\n};\n\n// Holds Plot state information that must persist after EndPlot\nstruct ImPlotPlot\n{\n    ImGuiID              ID;\n    ImPlotFlags          Flags;\n    ImPlotFlags          PreviousFlags;\n    ImPlotLocation       MouseTextLocation;\n    ImPlotMouseTextFlags MouseTextFlags;\n    ImPlotAxis           Axes[ImAxis_COUNT];\n    ImGuiTextBuffer      TextBuffer;\n    ImPlotItemGroup      Items;\n    ImAxis               CurrentX;\n    ImAxis               CurrentY;\n    ImRect               FrameRect;\n    ImRect               CanvasRect;\n    ImRect               PlotRect;\n    ImRect               AxesRect;\n    ImRect               SelectRect;\n    ImVec2               SelectStart;\n    int                  TitleOffset;\n    bool                 JustCreated;\n    bool                 Initialized;\n    bool                 SetupLocked;\n    bool                 FitThisFrame;\n    bool                 Hovered;\n    bool                 Held;\n    bool                 Selecting;\n    bool                 Selected;\n    bool                 ContextLocked;\n\n    ImPlotPlot() {\n        Flags             = PreviousFlags = ImPlotFlags_None;\n        for (int i = 0; i < IMPLOT_NUM_X_AXES; ++i)\n            XAxis(i).Vertical = false;\n        for (int i = 0; i < IMPLOT_NUM_Y_AXES; ++i)\n            YAxis(i).Vertical = true;\n        SelectStart       = ImVec2(0,0);\n        CurrentX          = ImAxis_X1;\n        CurrentY          = ImAxis_Y1;\n        MouseTextLocation  = ImPlotLocation_South | ImPlotLocation_East;\n        MouseTextFlags     = ImPlotMouseTextFlags_None;\n        TitleOffset       = -1;\n        JustCreated       = true;\n        Initialized = SetupLocked = FitThisFrame = false;\n        Hovered = Held = Selected = Selecting = ContextLocked = false;\n    }\n\n    inline bool IsInputLocked() const {\n        for (int i = 0; i < IMPLOT_NUM_X_AXES; ++i) {\n            if (!XAxis(i).IsInputLocked())\n                return false;\n        }\n        for (int i = 0; i < IMPLOT_NUM_Y_AXES; ++i) {\n            if (!YAxis(i).IsInputLocked())\n                return false;\n        }\n        return true;\n    }\n\n    inline void ClearTextBuffer() { TextBuffer.Buf.shrink(0); }\n\n    inline void SetTitle(const char* title) {\n        if (title && ImGui::FindRenderedTextEnd(title, NULL) != title) {\n            TitleOffset = TextBuffer.size();\n            TextBuffer.append(title, title + strlen(title) + 1);\n        }\n        else {\n            TitleOffset = -1;\n        }\n    }\n    inline bool HasTitle() const { return TitleOffset != -1 && !ImHasFlag(Flags, ImPlotFlags_NoTitle); }\n    inline const char* GetTitle() const { return TextBuffer.Buf.Data + TitleOffset; }\n\n    inline       ImPlotAxis& XAxis(int i)       { return Axes[ImAxis_X1 + i]; }\n    inline const ImPlotAxis& XAxis(int i) const { return Axes[ImAxis_X1 + i]; }\n    inline       ImPlotAxis& YAxis(int i)       { return Axes[ImAxis_Y1 + i]; }\n    inline const ImPlotAxis& YAxis(int i) const { return Axes[ImAxis_Y1 + i]; }\n\n    inline int EnabledAxesX() {\n        int cnt = 0;\n        for (int i = 0; i < IMPLOT_NUM_X_AXES; ++i)\n            cnt += XAxis(i).Enabled;\n        return cnt;\n    }\n\n    inline int EnabledAxesY() {\n        int cnt = 0;\n        for (int i = 0; i < IMPLOT_NUM_Y_AXES; ++i)\n            cnt += YAxis(i).Enabled;\n        return cnt;\n    }\n\n    inline void SetAxisLabel(ImPlotAxis& axis, const char* label) {\n        if (label && ImGui::FindRenderedTextEnd(label, NULL) != label) {\n            axis.LabelOffset = TextBuffer.size();\n            TextBuffer.append(label, label + strlen(label) + 1);\n        }\n        else {\n            axis.LabelOffset = -1;\n        }\n    }\n\n    inline const char* GetAxisLabel(const ImPlotAxis& axis) const { return TextBuffer.Buf.Data + axis.LabelOffset; }\n};\n\n// Holds subplot data that must persist afer EndSubplot\nstruct ImPlotSubplot {\n    ImGuiID                       ID;\n    ImPlotSubplotFlags            Flags;\n    ImPlotSubplotFlags            PreviousFlags;\n    ImPlotItemGroup               Items;\n    int                           Rows;\n    int                           Cols;\n    int                           CurrentIdx;\n    ImRect                        FrameRect;\n    ImRect                        GridRect;\n    ImVec2                        CellSize;\n    ImVector<ImPlotAlignmentData> RowAlignmentData;\n    ImVector<ImPlotAlignmentData> ColAlignmentData;\n    ImVector<float>               RowRatios;\n    ImVector<float>               ColRatios;\n    ImVector<ImPlotRange>         RowLinkData;\n    ImVector<ImPlotRange>         ColLinkData;\n    float                         TempSizes[2];\n    bool                          FrameHovered;\n    bool                          HasTitle;\n\n    ImPlotSubplot() {\n        Rows = Cols = CurrentIdx  = 0;\n        FrameHovered              = false;\n        Items.Legend.Location     = ImPlotLocation_North;\n        Items.Legend.Flags        = ImPlotLegendFlags_Horizontal|ImPlotLegendFlags_Outside;\n        Items.Legend.CanGoInside  = false;\n        HasTitle                  = false;\n    }\n};\n\n// Temporary data storage for upcoming plot\nstruct ImPlotNextPlotData\n{\n    ImPlotCond  RangeCond[ImAxis_COUNT];\n    ImPlotRange Range[ImAxis_COUNT];\n    bool        HasRange[ImAxis_COUNT];\n    bool        Fit[ImAxis_COUNT];\n    double*     LinkedMin[ImAxis_COUNT];\n    double*     LinkedMax[ImAxis_COUNT];\n\n    ImPlotNextPlotData() { Reset(); }\n\n    void Reset() {\n        for (int i = 0; i < ImAxis_COUNT; ++i) {\n            HasRange[i]                 = false;\n            Fit[i]                      = false;\n            LinkedMin[i] = LinkedMax[i] = NULL;\n        }\n    }\n\n};\n\n// Temporary data storage for upcoming item\nstruct ImPlotNextItemData {\n    ImVec4       Colors[5]; // ImPlotCol_Line, ImPlotCol_Fill, ImPlotCol_MarkerOutline, ImPlotCol_MarkerFill, ImPlotCol_ErrorBar\n    float        LineWeight;\n    ImPlotMarker Marker;\n    float        MarkerSize;\n    float        MarkerWeight;\n    float        FillAlpha;\n    float        ErrorBarSize;\n    float        ErrorBarWeight;\n    float        DigitalBitHeight;\n    float        DigitalBitGap;\n    bool         RenderLine;\n    bool         RenderFill;\n    bool         RenderMarkerLine;\n    bool         RenderMarkerFill;\n    bool         HasHidden;\n    bool         Hidden;\n    ImPlotCond   HiddenCond;\n    ImPlotNextItemData() { Reset(); }\n    void Reset() {\n        for (int i = 0; i < 5; ++i)\n            Colors[i] = IMPLOT_AUTO_COL;\n        LineWeight    = MarkerSize = MarkerWeight = FillAlpha = ErrorBarSize = ErrorBarWeight = DigitalBitHeight = DigitalBitGap = IMPLOT_AUTO;\n        Marker        = IMPLOT_AUTO;\n        HasHidden     = Hidden = false;\n    }\n};\n\n// Holds state information that must persist between calls to BeginPlot()/EndPlot()\nstruct ImPlotContext {\n    // Plot States\n    ImPool<ImPlotPlot>    Plots;\n    ImPool<ImPlotSubplot> Subplots;\n    ImPlotPlot*           CurrentPlot;\n    ImPlotSubplot*        CurrentSubplot;\n    ImPlotItemGroup*      CurrentItems;\n    ImPlotItem*           CurrentItem;\n    ImPlotItem*           PreviousItem;\n\n    // Tick Marks and Labels\n    ImPlotTickCollection CTicks;\n\n    // Annotation and Tabs\n    ImPlotAnnotationCollection Annotations;\n    ImPlotTagCollection        Tags;\n\n    // Flags\n    bool ChildWindowMade;\n\n    // Style and Colormaps\n    ImPlotStyle                 Style;\n    ImVector<ImGuiColorMod>     ColorModifiers;\n    ImVector<ImGuiStyleMod>     StyleModifiers;\n    ImPlotColormapData          ColormapData;\n    ImVector<ImPlotColormap>    ColormapModifiers;\n\n    // Time\n    tm Tm;\n\n    // Temp data for general use\n    ImVector<double>   TempDouble1, TempDouble2;\n    ImVector<int>      TempInt1;\n\n    // Misc\n    int                DigitalPlotItemCnt;\n    int                DigitalPlotOffset;\n    ImPlotNextPlotData NextPlotData;\n    ImPlotNextItemData NextItemData;\n    ImPlotInputMap     InputMap;\n    bool               OpenContextThisFrame;\n    ImGuiTextBuffer    MousePosStringBuilder;\n\n    // Align plots\n    ImPool<ImPlotAlignmentData> AlignmentData;\n    ImPlotAlignmentData*        CurrentAlignmentH;\n    ImPlotAlignmentData*        CurrentAlignmentV;\n};\n\n//-----------------------------------------------------------------------------\n// [SECTION] Internal API\n// No guarantee of forward compatibility here!\n//-----------------------------------------------------------------------------\n\nnamespace ImPlot {\n\n//-----------------------------------------------------------------------------\n// [SECTION] Context Utils\n//-----------------------------------------------------------------------------\n\n// Initializes an ImPlotContext\nIMPLOT_API void Initialize(ImPlotContext* ctx);\n// Resets an ImPlot context for the next call to BeginPlot\nIMPLOT_API void ResetCtxForNextPlot(ImPlotContext* ctx);\n// Resets an ImPlot context for the next call to BeginAlignedPlots\nIMPLOT_API void ResetCtxForNextAlignedPlots(ImPlotContext* ctx);\n// Resets an ImPlot context for the next call to BeginSubplot\nIMPLOT_API void ResetCtxForNextSubplot(ImPlotContext* ctx);\n\n//-----------------------------------------------------------------------------\n// [SECTION] Plot Utils\n//-----------------------------------------------------------------------------\n\n// Gets a plot from the current ImPlotContext\nIMPLOT_API ImPlotPlot* GetPlot(const char* title);\n// Gets the current plot from the current ImPlotContext\nIMPLOT_API ImPlotPlot* GetCurrentPlot();\n// Busts the cache for every plot in the current context\nIMPLOT_API void BustPlotCache();\n\n// Shows a plot's context menu.\nIMPLOT_API void ShowPlotContextMenu(ImPlotPlot& plot);\n\n//-----------------------------------------------------------------------------\n// [SECTION] Setup Utils\n//-----------------------------------------------------------------------------\n\n// Lock Setup and call SetupFinish if necessary.\nstatic inline void SetupLock() {\n    if (!GImPlot->CurrentPlot->SetupLocked)\n        SetupFinish();\n    GImPlot->CurrentPlot->SetupLocked = true;\n}\n\n//-----------------------------------------------------------------------------\n// [SECTION] Subplot Utils\n//-----------------------------------------------------------------------------\n\n// Advances to next subplot\nIMPLOT_API void SubplotNextCell();\n\n// Shows a subplot's context menu.\nIMPLOT_API void ShowSubplotsContextMenu(ImPlotSubplot& subplot);\n\n//-----------------------------------------------------------------------------\n// [SECTION] Item Utils\n//-----------------------------------------------------------------------------\n\n// Begins a new item. Returns false if the item should not be plotted. Pushes PlotClipRect.\nIMPLOT_API bool BeginItem(const char* label_id, ImPlotCol recolor_from = -1);\n// Ends an item (call only if BeginItem returns true). Pops PlotClipRect.\nIMPLOT_API void EndItem();\n\n// Register or get an existing item from the current plot.\nIMPLOT_API ImPlotItem* RegisterOrGetItem(const char* label_id, bool* just_created = NULL);\n// Get a plot item from the current plot.\nIMPLOT_API ImPlotItem* GetItem(const char* label_id);\n// Gets the current item.\nIMPLOT_API ImPlotItem* GetCurrentItem();\n// Busts the cache for every item for every plot in the current context.\nIMPLOT_API void BustItemCache();\n\n//-----------------------------------------------------------------------------\n// [SECTION] Axis Utils\n//-----------------------------------------------------------------------------\n\n// Returns true if any enabled axis is locked from user input.\nstatic inline bool AnyAxesInputLocked(ImPlotAxis* axes, int count) {\n    for (int i = 0; i < count; ++i) {\n        if (axes[i].Enabled && axes[i].IsInputLocked())\n            return true;\n    }\n    return false;\n}\n\n// Returns true if all enabled axes are locked from user input.\nstatic inline bool AllAxesInputLocked(ImPlotAxis* axes, int count) {\n    for (int i = 0; i < count; ++i) {\n        if (axes[i].Enabled && !axes[i].IsInputLocked())\n            return false;\n    }\n    return true;\n}\n\nstatic inline bool AnyAxesHeld(ImPlotAxis* axes, int count) {\n    for (int i = 0; i < count; ++i) {\n        if (axes[i].Enabled && axes[i].Held)\n            return true;\n    }\n    return false;\n}\n\nstatic inline bool AnyAxesHovered(ImPlotAxis* axes, int count) {\n    for (int i = 0; i < count; ++i) {\n        if (axes[i].Enabled && axes[i].Hovered)\n            return true;\n    }\n    return false;\n}\n\n// Gets the XY scale for the current plot and y-axis (TODO)\nstatic inline ImPlotScale GetCurrentScale() {\n    ImPlotPlot& plot = *GetCurrentPlot();\n    ImPlotAxis& x = plot.Axes[plot.CurrentX];\n    ImPlotAxis& y = plot.Axes[plot.CurrentY];\n    if (!x.IsLog() && !y.IsLog())\n        return ImPlotScale_LinLin;\n    else if (x.IsLog() && !y.IsLog())\n        return ImPlotScale_LogLin;\n    else if (!x.IsLog() && y.IsLog())\n        return ImPlotScale_LinLog;\n    else\n        return ImPlotScale_LogLog;\n}\n\n// Returns true if the user has requested data to be fit.\nstatic inline bool FitThisFrame() {\n    return GImPlot->CurrentPlot->FitThisFrame;\n}\n\n// Extends the current plot's axes so that it encompasses a vertical line at x\nstatic inline void FitPointX(double x) {\n    ImPlotPlot& plot   = *GetCurrentPlot();\n    ImPlotAxis& x_axis = plot.Axes[plot.CurrentX];\n    x_axis.ExtendFit(x);\n}\n\n// Extends the current plot's axes so that it encompasses a horizontal line at y\nstatic inline void FitPointY(double y) {\n    ImPlotPlot& plot   = *GetCurrentPlot();\n    ImPlotAxis& y_axis = plot.Axes[plot.CurrentY];\n    y_axis.ExtendFit(y);\n}\n\n// Extends the current plot's axes so that it encompasses point p\nstatic inline void FitPoint(const ImPlotPoint& p) {\n    ImPlotPlot& plot   = *GetCurrentPlot();\n    ImPlotAxis& x_axis = plot.Axes[plot.CurrentX];\n    ImPlotAxis& y_axis = plot.Axes[plot.CurrentY];\n    x_axis.ExtendFitWith(y_axis, p.x, p.y);\n    y_axis.ExtendFitWith(x_axis, p.y, p.x);\n}\n\n// Returns true if two ranges overlap\nstatic inline bool RangesOverlap(const ImPlotRange& r1, const ImPlotRange& r2)\n{ return r1.Min <= r2.Max && r2.Min <= r1.Max; }\n\n// Shows an axis's context menu.\nIMPLOT_API void ShowAxisContextMenu(ImPlotAxis& axis, ImPlotAxis* equal_axis, bool time_allowed = false);\n\n//-----------------------------------------------------------------------------\n// [SECTION] Legend Utils\n//-----------------------------------------------------------------------------\n\n// Gets the position of an inner rect that is located inside of an outer rect according to an ImPlotLocation and padding amount.\nIMPLOT_API ImVec2 GetLocationPos(const ImRect& outer_rect, const ImVec2& inner_size, ImPlotLocation location, const ImVec2& pad = ImVec2(0,0));\n// Calculates the bounding box size of a legend\nIMPLOT_API ImVec2 CalcLegendSize(ImPlotItemGroup& items, const ImVec2& pad, const ImVec2& spacing, bool vertical);\n// Renders legend entries into a bounding box\nIMPLOT_API bool ShowLegendEntries(ImPlotItemGroup& items, const ImRect& legend_bb, bool interactable, const ImVec2& pad, const ImVec2& spacing, bool vertical, ImDrawList& DrawList);\n// Shows an alternate legend for the plot identified by #title_id, outside of the plot frame (can be called before or after of Begin/EndPlot but must occur in the same ImGui window!).\nIMPLOT_API void ShowAltLegend(const char* title_id, bool vertical = true, const ImVec2 size = ImVec2(0,0), bool interactable = true);\n// Shows an legends's context menu.\nIMPLOT_API bool ShowLegendContextMenu(ImPlotLegend& legend, bool visible);\n\n//-----------------------------------------------------------------------------\n// [SECTION] Tick Utils\n//-----------------------------------------------------------------------------\n\n// Label a tick with time formatting.\nIMPLOT_API void LabelTickTime(ImPlotTick& tick, ImGuiTextBuffer& buffer, const ImPlotTime& t, ImPlotDateTimeFmt fmt);\n\n// Populates a list of ImPlotTicks with normal spaced and formatted ticks\nIMPLOT_API void AddTicksDefault(const ImPlotRange& range, float pix, bool vertical, ImPlotTickCollection& ticks, ImPlotFormatter formatter, void* data);\n// Populates a list of ImPlotTicks with logarithmic space and formatted ticks\nIMPLOT_API void AddTicksLogarithmic(const ImPlotRange& range, float pix, bool vertical, ImPlotTickCollection& ticks, ImPlotFormatter formatter, void* data);\n// Populates a list of ImPlotTicks with custom spaced and labeled ticks\nIMPLOT_API void AddTicksCustom(const double* values, const char* const labels[], int n, ImPlotTickCollection& ticks, ImPlotFormatter formatter, void* data);\n// Populates a list of ImPlotTicks with time formatted ticks.\nIMPLOT_API void AddTicksTime(const ImPlotRange& range, float plot_width, ImPlotTickCollection& ticks);\n\n// Create a a string label for a an axis value\nIMPLOT_API void LabelAxisValue(const ImPlotAxis& axis, double value, char* buff, int size, bool round = false);\n\n//-----------------------------------------------------------------------------\n// [SECTION] Styling Utils\n//-----------------------------------------------------------------------------\n\n// Get styling data for next item (call between Begin/EndItem)\nstatic inline const ImPlotNextItemData& GetItemData() { return GImPlot->NextItemData; }\n\n// Returns true if a color is set to be automatically determined\nstatic inline bool IsColorAuto(const ImVec4& col) { return col.w == -1; }\n// Returns true if a style color is set to be automaticaly determined\nstatic inline bool IsColorAuto(ImPlotCol idx) { return IsColorAuto(GImPlot->Style.Colors[idx]); }\n// Returns the automatically deduced style color\nIMPLOT_API ImVec4 GetAutoColor(ImPlotCol idx);\n\n// Returns the style color whether it is automatic or custom set\nstatic inline ImVec4 GetStyleColorVec4(ImPlotCol idx) { return IsColorAuto(idx) ? GetAutoColor(idx) : GImPlot->Style.Colors[idx]; }\nstatic inline ImU32  GetStyleColorU32(ImPlotCol idx)  { return ImGui::ColorConvertFloat4ToU32(GetStyleColorVec4(idx)); }\n\n// Draws vertical text. The position is the bottom left of the text rect.\nIMPLOT_API void AddTextVertical(ImDrawList *DrawList, ImVec2 pos, ImU32 col, const char* text_begin, const char* text_end = NULL);\n// Draws multiline horizontal text centered.\nIMPLOT_API void AddTextCentered(ImDrawList* DrawList, ImVec2 top_center, ImU32 col, const char* text_begin, const char* text_end = NULL);\n// Calculates the size of vertical text\nstatic inline ImVec2 CalcTextSizeVertical(const char *text) {\n    ImVec2 sz = ImGui::CalcTextSize(text);\n    return ImVec2(sz.y, sz.x);\n}\n// Returns white or black text given background color\nstatic inline ImU32 CalcTextColor(const ImVec4& bg) { return (bg.x * 0.299f + bg.y * 0.587f + bg.z * 0.114f) > 0.5f ? IM_COL32_BLACK : IM_COL32_WHITE; }\nstatic inline ImU32 CalcTextColor(ImU32 bg)         { return CalcTextColor(ImGui::ColorConvertU32ToFloat4(bg)); }\n// Lightens or darkens a color for hover\nstatic inline ImU32 CalcHoverColor(ImU32 col)       {  return ImMixU32(col, CalcTextColor(col), 32); }\n\n// Clamps a label position so that it fits a rect defined by Min/Max\nstatic inline ImVec2 ClampLabelPos(ImVec2 pos, const ImVec2& size, const ImVec2& Min, const ImVec2& Max) {\n    if (pos.x < Min.x)              pos.x = Min.x;\n    if (pos.y < Min.y)              pos.y = Min.y;\n    if ((pos.x + size.x) > Max.x)   pos.x = Max.x - size.x;\n    if ((pos.y + size.y) > Max.y)   pos.y = Max.y - size.y;\n    return pos;\n}\n\n// Returns a color from the Color map given an index >= 0 (modulo will be performed).\nIMPLOT_API ImU32  GetColormapColorU32(int idx, ImPlotColormap cmap);\n// Returns the next unused colormap color and advances the colormap. Can be used to skip colors if desired.\nIMPLOT_API ImU32  NextColormapColorU32();\n// Linearly interpolates a color from the current colormap given t between 0 and 1.\nIMPLOT_API ImU32  SampleColormapU32(float t, ImPlotColormap cmap);\n\n// Render a colormap bar\nIMPLOT_API void RenderColorBar(const ImU32* colors, int size, ImDrawList& DrawList, const ImRect& bounds, bool vert, bool reversed, bool continuous);\n\n//-----------------------------------------------------------------------------\n// [SECTION] Math and Misc Utils\n//-----------------------------------------------------------------------------\n\n// Rounds x to powers of 2,5 and 10 for generating axis labels (from Graphics Gems 1 Chapter 11.2)\nIMPLOT_API double NiceNum(double x, bool round);\n// Computes order of magnitude of double.\nstatic inline int OrderOfMagnitude(double val) { return val == 0 ? 0 : (int)(floor(log10(fabs(val)))); }\n// Returns the precision required for a order of magnitude.\nstatic inline int OrderToPrecision(int order) { return order > 0 ? 0 : 1 - order; }\n// Returns a floating point precision to use given a value\nstatic inline int Precision(double val) { return OrderToPrecision(OrderOfMagnitude(val)); }\n// Round a value to a given precision\nstatic inline double RoundTo(double val, int prec) { double p = pow(10,(double)prec); return floor(val*p+0.5)/p; }\n\n// Returns the intersection point of two lines A and B (assumes they are not parallel!)\nstatic inline ImVec2 Intersection(const ImVec2& a1, const ImVec2& a2, const ImVec2& b1, const ImVec2& b2) {\n    float v1 = (a1.x * a2.y - a1.y * a2.x);  float v2 = (b1.x * b2.y - b1.y * b2.x);\n    float v3 = ((a1.x - a2.x) * (b1.y - b2.y) - (a1.y - a2.y) * (b1.x - b2.x));\n    return ImVec2((v1 * (b1.x - b2.x) - v2 * (a1.x - a2.x)) / v3, (v1 * (b1.y - b2.y) - v2 * (a1.y - a2.y)) / v3);\n}\n\n// Fills a buffer with n samples linear interpolated from vmin to vmax\ntemplate <typename T>\nvoid FillRange(ImVector<T>& buffer, int n, T vmin, T vmax) {\n    buffer.resize(n);\n    T step = (vmax - vmin) / (n - 1);\n    for (int i = 0; i < n; ++i) {\n        buffer[i] = vmin + i * step;\n    }\n}\n\n// Calculate histogram bin counts and widths\ntemplate <typename T>\nstatic inline void CalculateBins(const T* values, int count, ImPlotBin meth, const ImPlotRange& range, int& bins_out, double& width_out) {\n    switch (meth) {\n        case ImPlotBin_Sqrt:\n            bins_out  = (int)ceil(sqrt(count));\n            break;\n        case ImPlotBin_Sturges:\n            bins_out  = (int)ceil(1.0 + log2(count));\n            break;\n        case ImPlotBin_Rice:\n            bins_out  = (int)ceil(2 * cbrt(count));\n            break;\n        case ImPlotBin_Scott:\n            width_out = 3.49 * ImStdDev(values, count) / cbrt(count);\n            bins_out  = (int)round(range.Size() / width_out);\n            break;\n    }\n    width_out = range.Size() / bins_out;\n}\n\n//-----------------------------------------------------------------------------\n// Time Utils\n//-----------------------------------------------------------------------------\n\n// Returns true if year is leap year (366 days long)\nstatic inline bool IsLeapYear(int year) {\n    return  year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);\n}\n// Returns the number of days in a month, accounting for Feb. leap years. #month is zero indexed.\nstatic inline int GetDaysInMonth(int year, int month) {\n    static const int days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};\n    return  days[month] + (int)(month == 1 && IsLeapYear(year));\n}\n\n// Make a UNIX timestamp from a tm struct expressed in UTC time (i.e. GMT timezone).\nIMPLOT_API ImPlotTime MkGmtTime(struct tm *ptm);\n// Make a tm struct expressed in UTC time (i.e. GMT timezone) from a UNIX timestamp.\nIMPLOT_API tm* GetGmtTime(const ImPlotTime& t, tm* ptm);\n\n// Make a UNIX timestamp from a tm struct expressed in local time.\nIMPLOT_API ImPlotTime MkLocTime(struct tm *ptm);\n// Make a tm struct expressed in local time from a UNIX timestamp.\nIMPLOT_API tm* GetLocTime(const ImPlotTime& t, tm* ptm);\n\n// NB: The following functions only work if there is a current ImPlotContext because the\n// internal tm struct is owned by the context! They are aware of ImPlotStyle.UseLocalTime.\n\n// Make a timestamp from time components.\n// year[1970-3000], month[0-11], day[1-31], hour[0-23], min[0-59], sec[0-59], us[0,999999]\nIMPLOT_API ImPlotTime MakeTime(int year, int month = 0, int day = 1, int hour = 0, int min = 0, int sec = 0, int us = 0);\n// Get year component from timestamp [1970-3000]\nIMPLOT_API int GetYear(const ImPlotTime& t);\n\n// Adds or subtracts time from a timestamp. #count > 0 to add, < 0 to subtract.\nIMPLOT_API ImPlotTime AddTime(const ImPlotTime& t, ImPlotTimeUnit unit, int count);\n// Rounds a timestamp down to nearest unit.\nIMPLOT_API ImPlotTime FloorTime(const ImPlotTime& t, ImPlotTimeUnit unit);\n// Rounds a timestamp up to the nearest unit.\nIMPLOT_API ImPlotTime CeilTime(const ImPlotTime& t, ImPlotTimeUnit unit);\n// Rounds a timestamp up or down to the nearest unit.\nIMPLOT_API ImPlotTime RoundTime(const ImPlotTime& t, ImPlotTimeUnit unit);\n// Combines the date of one timestamp with the time-of-day of another timestamp.\nIMPLOT_API ImPlotTime CombineDateTime(const ImPlotTime& date_part, const ImPlotTime& time_part);\n\n// Formats the time part of timestamp t into a buffer according to #fmt\nIMPLOT_API int FormatTime(const ImPlotTime& t, char* buffer, int size, ImPlotTimeFmt fmt, bool use_24_hr_clk);\n// Formats the date part of timestamp t into a buffer according to #fmt\nIMPLOT_API int FormatDate(const ImPlotTime& t, char* buffer, int size, ImPlotDateFmt fmt, bool use_iso_8601);\n// Formats the time and/or date parts of a timestamp t into a buffer according to #fmt\nIMPLOT_API int FormatDateTime(const ImPlotTime& t, char* buffer, int size, ImPlotDateTimeFmt fmt);\n\n// Shows a date picker widget block (year/month/day).\n// #level = 0 for day, 1 for month, 2 for year. Modified by user interaction.\n// #t will be set when a day is clicked and the function will return true.\n// #t1 and #t2 are optional dates to highlight.\nIMPLOT_API bool ShowDatePicker(const char* id, int* level, ImPlotTime* t, const ImPlotTime* t1 = NULL, const ImPlotTime* t2 = NULL);\n// Shows a time picker widget block (hour/min/sec).\n// #t will be set when a new hour, minute, or sec is selected or am/pm is toggled, and the function will return true.\nIMPLOT_API bool ShowTimePicker(const char* id, ImPlotTime* t);\n\n} // namespace ImPlot\n"
  },
  {
    "path": "3rdparty/Cinder-VNM/ui/implot/implot_items.cpp",
    "content": "// MIT License\n\n// Copyright (c) 2020 Evan Pezent\n\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n// ImPlot v0.13 WIP\n\n#include \"implot.h\"\n#include \"implot_internal.h\"\n\n#define SQRT_1_2 0.70710678118f\n#define SQRT_3_2 0.86602540378f\n\n#ifndef IMPLOT_NO_FORCE_INLINE\n    #ifdef _MSC_VER\n        #define IMPLOT_INLINE __forceinline\n    #elif defined(__GNUC__)\n        #define IMPLOT_INLINE inline __attribute__((__always_inline__))\n    #elif defined(__CLANG__)\n        #if __has_attribute(__always_inline__)\n            #define IMPLOT_INLINE inline __attribute__((__always_inline__))\n        #else\n            #define IMPLOT_INLINE inline\n        #endif\n    #else\n        #define IMPLOT_INLINE inline\n    #endif\n#else\n    #define IMPLOT_INLINE inline\n#endif\n\n#if defined __SSE__ || defined __x86_64__ || defined _M_X64\n#ifndef IMGUI_ENABLE_SSE\n#include <immintrin.h>\n#endif\nstatic IMPLOT_INLINE float  ImInvSqrt(float x) { return _mm_cvtss_f32(_mm_rsqrt_ss(_mm_set_ss(x))); }\n#else\nstatic IMPLOT_INLINE float  ImInvSqrt(float x) { return 1.0f / sqrtf(x); }\n#endif\n\n#define IMPLOT_NORMALIZE2F_OVER_ZERO(VX,VY) do { float d2 = VX*VX + VY*VY; if (d2 > 0.0f) { float inv_len = ImInvSqrt(d2); VX *= inv_len; VY *= inv_len; } } while (0)\n\n// Support for pre-1.82 versions. Users on 1.82+ can use 0 (default) flags to mean \"all corners\" but in order to support older versions we are more explicit.\n#if (IMGUI_VERSION_NUM < 18102) && !defined(ImDrawFlags_RoundCornersAll)\n#define ImDrawFlags_RoundCornersAll ImDrawCornerFlags_All\n#endif\n\nnamespace ImPlot {\n\n//-----------------------------------------------------------------------------\n// Utils\n//-----------------------------------------------------------------------------\n\n// Calc maximum index size of ImDrawIdx\ntemplate <typename T>\nstruct MaxIdx { static const unsigned int Value; };\ntemplate <> const unsigned int MaxIdx<unsigned short>::Value = 65535;\ntemplate <> const unsigned int MaxIdx<unsigned int>::Value   = 4294967295;\n\n//-----------------------------------------------------------------------------\n// Item Utils\n//-----------------------------------------------------------------------------\n\nImPlotItem* RegisterOrGetItem(const char* label_id, bool* just_created) {\n    ImPlotContext& gp = *GImPlot;\n    ImPlotItemGroup& Items = *gp.CurrentItems;\n    ImGuiID id = Items.GetItemID(label_id);\n    if (just_created != NULL)\n        *just_created = Items.GetItem(id) == NULL;\n    ImPlotItem* item = Items.GetOrAddItem(id);\n    if (item->SeenThisFrame)\n        return item;\n    item->SeenThisFrame = true;\n    int idx = Items.GetItemIndex(item);\n    item->ID = id;\n    if (ImGui::FindRenderedTextEnd(label_id, NULL) != label_id) {\n        Items.Legend.Indices.push_back(idx);\n        item->NameOffset = Items.Legend.Labels.size();\n        Items.Legend.Labels.append(label_id, label_id + strlen(label_id) + 1);\n    }\n    else {\n        item->Show = true;\n    }\n    return item;\n}\n\nImPlotItem* GetItem(const char* label_id) {\n    ImPlotContext& gp = *GImPlot;\n    return gp.CurrentItems->GetItem(label_id);\n}\n\nbool IsItemHidden(const char* label_id) {\n    ImPlotItem* item = GetItem(label_id);\n    return item != NULL && !item->Show;\n}\n\nImPlotItem* GetCurrentItem() {\n    ImPlotContext& gp = *GImPlot;\n    return gp.CurrentItem;\n}\n\nvoid SetNextLineStyle(const ImVec4& col, float weight) {\n    ImPlotContext& gp = *GImPlot;\n    gp.NextItemData.Colors[ImPlotCol_Line] = col;\n    gp.NextItemData.LineWeight             = weight;\n}\n\nvoid SetNextFillStyle(const ImVec4& col, float alpha) {\n    ImPlotContext& gp = *GImPlot;\n    gp.NextItemData.Colors[ImPlotCol_Fill] = col;\n    gp.NextItemData.FillAlpha              = alpha;\n}\n\nvoid SetNextMarkerStyle(ImPlotMarker marker, float size, const ImVec4& fill, float weight, const ImVec4& outline) {\n    ImPlotContext& gp = *GImPlot;\n    gp.NextItemData.Marker                          = marker;\n    gp.NextItemData.Colors[ImPlotCol_MarkerFill]    = fill;\n    gp.NextItemData.MarkerSize                      = size;\n    gp.NextItemData.Colors[ImPlotCol_MarkerOutline] = outline;\n    gp.NextItemData.MarkerWeight                    = weight;\n}\n\nvoid SetNextErrorBarStyle(const ImVec4& col, float size, float weight) {\n    ImPlotContext& gp = *GImPlot;\n    gp.NextItemData.Colors[ImPlotCol_ErrorBar] = col;\n    gp.NextItemData.ErrorBarSize               = size;\n    gp.NextItemData.ErrorBarWeight             = weight;\n}\n\nImVec4 GetLastItemColor() {\n    ImPlotContext& gp = *GImPlot;\n    if (gp.PreviousItem)\n        return ImGui::ColorConvertU32ToFloat4(gp.PreviousItem->Color);\n    return ImVec4();\n}\n\nvoid BustItemCache() {\n    ImPlotContext& gp = *GImPlot;\n    for (int p = 0; p < gp.Plots.GetBufSize(); ++p) {\n        ImPlotPlot& plot = *gp.Plots.GetByIndex(p);\n        plot.Items.Reset();\n    }\n    for (int p = 0; p < gp.Subplots.GetBufSize(); ++p) {\n        ImPlotSubplot& subplot = *gp.Subplots.GetByIndex(p);\n        subplot.Items.Reset();\n    }\n}\n\nvoid BustColorCache(const char* plot_title_id) {\n    ImPlotContext& gp = *GImPlot;\n    if (plot_title_id == NULL) {\n        BustItemCache();\n    }\n    else {\n        ImGuiID id = ImGui::GetCurrentWindow()->GetID(plot_title_id);\n        ImPlotPlot* plot = gp.Plots.GetByKey(id);\n        if (plot != NULL)\n            plot->Items.Reset();\n        else {\n            ImPlotSubplot* subplot = gp.Subplots.GetByKey(id);\n            if (subplot != NULL)\n                subplot->Items.Reset();\n        }\n    }\n}\n\n//-----------------------------------------------------------------------------\n// Begin/EndItem\n//-----------------------------------------------------------------------------\n\nstatic const float ITEM_HIGHLIGHT_LINE_SCALE = 2.0f;\nstatic const float ITEM_HIGHLIGHT_MARK_SCALE = 1.25f;\n\n\n// Begins a new item. Returns false if the item should not be plotted.\nbool BeginItem(const char* label_id, ImPlotCol recolor_from) {\n    ImPlotContext& gp = *GImPlot;\n    IM_ASSERT_USER_ERROR(gp.CurrentPlot != NULL, \"PlotX() needs to be called between BeginPlot() and EndPlot()!\");\n    SetupLock();\n    bool just_created;\n    ImPlotItem* item = RegisterOrGetItem(label_id, &just_created);\n    // set current item\n    gp.CurrentItem = item;\n    ImPlotNextItemData& s = gp.NextItemData;\n    // set/override item color\n    if (recolor_from != -1) {\n        if (!IsColorAuto(s.Colors[recolor_from]))\n            item->Color = ImGui::ColorConvertFloat4ToU32(s.Colors[recolor_from]);\n        else if (!IsColorAuto(gp.Style.Colors[recolor_from]))\n            item->Color = ImGui::ColorConvertFloat4ToU32(gp.Style.Colors[recolor_from]);\n        else if (just_created)\n            item->Color = NextColormapColorU32();\n    }\n    else if (just_created) {\n        item->Color = NextColormapColorU32();\n    }\n    // hide/show item\n    if (gp.NextItemData.HasHidden) {\n        if (just_created || gp.NextItemData.HiddenCond == ImGuiCond_Always)\n            item->Show = !gp.NextItemData.Hidden;\n    }\n    if (!item->Show) {\n        // reset next item data\n        gp.NextItemData.Reset();\n        gp.PreviousItem = item;\n        gp.CurrentItem  = NULL;\n        return false;\n    }\n    else {\n        ImVec4 item_color = ImGui::ColorConvertU32ToFloat4(item->Color);\n        // stage next item colors\n        s.Colors[ImPlotCol_Line]           = IsColorAuto(s.Colors[ImPlotCol_Line])          ? ( IsColorAuto(ImPlotCol_Line)           ? item_color                 : gp.Style.Colors[ImPlotCol_Line]          ) : s.Colors[ImPlotCol_Line];\n        s.Colors[ImPlotCol_Fill]           = IsColorAuto(s.Colors[ImPlotCol_Fill])          ? ( IsColorAuto(ImPlotCol_Fill)           ? item_color                 : gp.Style.Colors[ImPlotCol_Fill]          ) : s.Colors[ImPlotCol_Fill];\n        s.Colors[ImPlotCol_MarkerOutline]  = IsColorAuto(s.Colors[ImPlotCol_MarkerOutline]) ? ( IsColorAuto(ImPlotCol_MarkerOutline)  ? s.Colors[ImPlotCol_Line]   : gp.Style.Colors[ImPlotCol_MarkerOutline] ) : s.Colors[ImPlotCol_MarkerOutline];\n        s.Colors[ImPlotCol_MarkerFill]     = IsColorAuto(s.Colors[ImPlotCol_MarkerFill])    ? ( IsColorAuto(ImPlotCol_MarkerFill)     ? s.Colors[ImPlotCol_Line]   : gp.Style.Colors[ImPlotCol_MarkerFill]    ) : s.Colors[ImPlotCol_MarkerFill];\n        s.Colors[ImPlotCol_ErrorBar]       = IsColorAuto(s.Colors[ImPlotCol_ErrorBar])      ? ( GetStyleColorVec4(ImPlotCol_ErrorBar)                                                                         ) : s.Colors[ImPlotCol_ErrorBar];\n        // stage next item style vars\n        s.LineWeight         = s.LineWeight       < 0 ? gp.Style.LineWeight       : s.LineWeight;\n        s.Marker             = s.Marker           < 0 ? gp.Style.Marker           : s.Marker;\n        s.MarkerSize         = s.MarkerSize       < 0 ? gp.Style.MarkerSize       : s.MarkerSize;\n        s.MarkerWeight       = s.MarkerWeight     < 0 ? gp.Style.MarkerWeight     : s.MarkerWeight;\n        s.FillAlpha          = s.FillAlpha        < 0 ? gp.Style.FillAlpha        : s.FillAlpha;\n        s.ErrorBarSize       = s.ErrorBarSize     < 0 ? gp.Style.ErrorBarSize     : s.ErrorBarSize;\n        s.ErrorBarWeight     = s.ErrorBarWeight   < 0 ? gp.Style.ErrorBarWeight   : s.ErrorBarWeight;\n        s.DigitalBitHeight   = s.DigitalBitHeight < 0 ? gp.Style.DigitalBitHeight : s.DigitalBitHeight;\n        s.DigitalBitGap      = s.DigitalBitGap    < 0 ? gp.Style.DigitalBitGap    : s.DigitalBitGap;\n        // apply alpha modifier(s)\n        s.Colors[ImPlotCol_Fill].w       *= s.FillAlpha;\n        s.Colors[ImPlotCol_MarkerFill].w *= s.FillAlpha; // TODO: this should be separate, if it at all\n        // apply highlight mods\n        if (item->LegendHovered) {\n            if (!ImHasFlag(gp.CurrentItems->Legend.Flags, ImPlotLegendFlags_NoHighlightItem)) {\n                s.LineWeight   *= ITEM_HIGHLIGHT_LINE_SCALE;\n                s.MarkerSize   *= ITEM_HIGHLIGHT_MARK_SCALE;\n                s.MarkerWeight *= ITEM_HIGHLIGHT_LINE_SCALE;\n                // TODO: how to highlight fills?\n            }\n            if (!ImHasFlag(gp.CurrentItems->Legend.Flags, ImPlotLegendFlags_NoHighlightAxis)) {\n                if (gp.CurrentPlot->EnabledAxesX() > 1)\n                    gp.CurrentPlot->Axes[gp.CurrentPlot->CurrentX].ColorHiLi = item->Color;\n                if (gp.CurrentPlot->EnabledAxesY() > 1)\n                    gp.CurrentPlot->Axes[gp.CurrentPlot->CurrentY].ColorHiLi = item->Color;\n            }\n        }\n        // set render flags\n        s.RenderLine       = s.Colors[ImPlotCol_Line].w          > 0 && s.LineWeight > 0;\n        s.RenderFill       = s.Colors[ImPlotCol_Fill].w          > 0;\n        s.RenderMarkerLine = s.Colors[ImPlotCol_MarkerOutline].w > 0 && s.MarkerWeight > 0;\n        s.RenderMarkerFill = s.Colors[ImPlotCol_MarkerFill].w    > 0;\n        // push rendering clip rect\n        PushPlotClipRect();\n        return true;\n    }\n}\n\n// Ends an item (call only if BeginItem returns true)\nvoid EndItem() {\n    ImPlotContext& gp = *GImPlot;\n    // pop rendering clip rect\n    PopPlotClipRect();\n    // reset next item data\n    gp.NextItemData.Reset();\n    // set current item\n    gp.PreviousItem = gp.CurrentItem;\n    gp.CurrentItem  = NULL;\n}\n\n//-----------------------------------------------------------------------------\n// INDEXERS\n//-----------------------------------------------------------------------------\n\n// Offsets and strides a data buffer\ntemplate <typename T>\nIMPLOT_INLINE T IndexData(const T* data, int idx, int count, int offset, int stride) {\n    const int s = ((offset == 0) << 0) | ((stride == sizeof(T)) << 1);\n    switch (s) {\n        case 3 : return data[idx];\n        case 2 : return data[(offset + idx) % count];\n        case 1 : return *(const T*)(const void*)((const unsigned char*)data + (size_t)((idx) ) * stride);\n        case 0 : return *(const T*)(const void*)((const unsigned char*)data + (size_t)((offset + idx) % count) * stride);\n        default: return T(0);\n    }\n}\n\n//-----------------------------------------------------------------------------\n// GETTERS\n//-----------------------------------------------------------------------------\n\n// Getters can be thought of as iterators that convert user data (e.g. raw arrays)\n// to ImPlotPoints\n\ntemplate <typename T>\nstruct GetterIdx {\n    GetterIdx(const T* data, int count, int offset = 0, int stride = sizeof(T)) :\n        Data(data),\n        Count(count),\n        Offset(count ? ImPosMod(offset, count) : 0),\n        Stride(stride)\n    { }\n    template <typename I> IMPLOT_INLINE double operator()(I idx) const {\n        return (double)IndexData(Data, idx, Count, Offset, Stride);\n    }\n    const T* Data;\n    int Count;\n    int Offset;\n    int Stride;\n};\n\nstruct GetterLin {\n    GetterLin(double m, double b) : M(m), B(b) { }\n    template <typename I> IMPLOT_INLINE double operator()(I idx) const {\n        return M * idx + B;\n    }\n    const double M;\n    const double B;\n};\n\nstruct GetterRef {\n    GetterRef(double ref) : Ref(ref) { }\n    template <typename I> IMPLOT_INLINE double operator()(I) const { return Ref; }\n    const double Ref;\n};\n\ntemplate <typename TGetterX, typename TGetterY>\nstruct GetterXY {\n    GetterXY(TGetterX x, TGetterY y, int count) : GetterX(x), GetterY(y), Count(count) { }\n    template <typename I> IMPLOT_INLINE ImPlotPoint operator()(I idx) const {\n        return ImPlotPoint(GetterX(idx),GetterY(idx));\n    }\n    const TGetterX GetterX;\n    const TGetterY GetterY;\n    const int Count;\n};\n\n// Interprets an array of Y points as ImPlotPoints where the X value is the index\ntemplate <typename T>\nstruct GetterXs {\n    GetterXs(const T* xs, int count, double yscale, double y0, int offset, int stride) :\n        Xs(xs),\n        Count(count),\n        YScale(yscale),\n        Y0(y0),\n        Offset(count ? ImPosMod(offset, count) : 0),\n        Stride(stride)\n    { }\n    template <typename I> IMPLOT_INLINE ImPlotPoint operator()(I idx) const {\n        return ImPlotPoint((double)IndexData(Xs, idx, Count, Offset, Stride), Y0 + YScale * idx);\n    }\n    const T* const Xs;\n    const int Count;\n    const double YScale;\n    const double Y0;\n    const int Offset;\n    const int Stride;\n};\n\n/// Interprets a user's function pointer as ImPlotPoints\nstruct GetterFuncPtr {\n    GetterFuncPtr(ImPlotPoint (*getter)(void* data, int idx), void* data, int count) :\n        Getter(getter),\n        Data(data),\n        Count(count)\n    { }\n    template <typename I> IMPLOT_INLINE ImPlotPoint operator()(I idx) const {\n        return Getter(Data, idx);\n    }\n    ImPlotPoint (* const Getter)(void* data, int idx);\n    void* const Data;\n    const int Count;\n};\n\ntemplate <typename TGetter>\nstruct GetterOverrideX {\n    GetterOverrideX(const TGetter& getter, double x) : Getter(getter), X(x), Count(getter.Count) { }\n    template <typename I> IMPLOT_INLINE ImPlotPoint operator()(I idx) const {\n        ImPlotPoint p = Getter(idx);\n        p.x = X;\n        return p;\n    }\n    const TGetter& Getter;\n    const double X;\n    const int Count;\n};\n\ntemplate <typename TGetter>\nstruct GetterOverrideY {\n    GetterOverrideY(const TGetter& getter, double y) : Getter(getter), Y(y), Count(getter.Count) { }\n    template <typename I> IMPLOT_INLINE ImPlotPoint operator()(I idx) const {\n        ImPlotPoint p = Getter(idx);\n        p.y = Y;\n        return p;\n    }\n    const TGetter& Getter;\n    const double Y;\n    const int Count;\n};\n\ntemplate <typename T>\nstruct GetterError {\n    GetterError(const T* xs, const T* ys, const T* neg, const T* pos, int count, int offset, int stride) :\n        Xs(xs),\n        Ys(ys),\n        Neg(neg),\n        Pos(pos),\n        Count(count),\n        Offset(count ? ImPosMod(offset, count) : 0),\n        Stride(stride)\n    { }\n    template <typename I> IMPLOT_INLINE ImPlotPointError operator()(I idx) const {\n        return ImPlotPointError((double)IndexData(Xs,  idx, Count, Offset, Stride),\n                                (double)IndexData(Ys,  idx, Count, Offset, Stride),\n                                (double)IndexData(Neg, idx, Count, Offset, Stride),\n                                (double)IndexData(Pos, idx, Count, Offset, Stride));\n    }\n    const T* const Xs;\n    const T* const Ys;\n    const T* const Neg;\n    const T* const Pos;\n    const int Count;\n    const int Offset;\n    const int Stride;\n};\n\n//-----------------------------------------------------------------------------\n// TRANSFORMERS\n//-----------------------------------------------------------------------------\n\n// Transforms convert points in plot space (i.e. ImPlotPoint) to pixel space (i.e. ImVec2)\n\nstruct TransformerLin {\n    TransformerLin(double pixMin, double pltMin, double,       double m, double    ) : PixMin(pixMin), PltMin(pltMin), M(m) { }\n    template <typename T> IMPLOT_INLINE float operator()(T p) const { return (float)(PixMin + M * (p - PltMin)); }\n    double PixMin, PltMin, M;\n};\n\nstruct TransformerLog {\n    TransformerLog(double pixMin, double pltMin, double pltMax, double m, double den) : Den(den), PltMin(pltMin), PltMax(pltMax), PixMin(pixMin), M(m) { }\n    template <typename T> IMPLOT_INLINE float operator()(T p) const {\n        p = p <= 0.0 ? IMPLOT_LOG_ZERO : p;\n        double t = ImLog10(p / PltMin) / Den;\n        p = ImLerp(PltMin, PltMax, (float)t);\n        return (float)(PixMin + M * (p - PltMin));\n    }\n    double Den, PltMin, PltMax, PixMin, M;\n};\n\ntemplate <typename TransformerX, typename TransformerY>\nstruct TransformerXY {\n    TransformerXY(const ImPlotAxis& x_axis, const ImPlotAxis& y_axis) :\n        Tx(x_axis.PixelMin,\n           x_axis.Range.Min,\n           x_axis.Range.Max,\n           x_axis.LinM,\n           x_axis.LogD),\n        Ty(y_axis.PixelMin,\n           y_axis.Range.Min,\n           y_axis.Range.Max,\n           y_axis.LinM,\n           y_axis.LogD)\n    { }\n\n    TransformerXY(const ImPlotPlot& plot) :\n        TransformerXY(plot.Axes[plot.CurrentX], plot.Axes[plot.CurrentY])\n    { }\n\n    TransformerXY() :\n        TransformerXY(*GImPlot->CurrentPlot)\n    { }\n\n    template <typename P> IMPLOT_INLINE ImVec2 operator()(const P& plt) const {\n        ImVec2 out;\n        out.x = Tx(plt.x);\n        out.y = Ty(plt.y);\n        return out;\n    }\n    TransformerX Tx;\n    TransformerY Ty;\n};\n\ntypedef TransformerXY<TransformerLin,TransformerLin> TransformerLinLin;\ntypedef TransformerXY<TransformerLin,TransformerLog> TransformerLinLog;\ntypedef TransformerXY<TransformerLog,TransformerLin> TransformerLogLin;\ntypedef TransformerXY<TransformerLog,TransformerLog> TransformerLogLog;\n\n//-----------------------------------------------------------------------------\n// PRIMITIVE RENDERERS\n//-----------------------------------------------------------------------------\n\nIMPLOT_INLINE void PrimLine(const ImVec2& P1, const ImVec2& P2, float half_weight, ImU32 col, ImDrawList& DrawList, ImVec2 uv) {\n    float dx = P2.x - P1.x;\n    float dy = P2.y - P1.y;\n    IMPLOT_NORMALIZE2F_OVER_ZERO(dx, dy);\n    dx *= half_weight;\n    dy *= half_weight;\n    DrawList._VtxWritePtr[0].pos.x = P1.x + dy;\n    DrawList._VtxWritePtr[0].pos.y = P1.y - dx;\n    DrawList._VtxWritePtr[0].uv    = uv;\n    DrawList._VtxWritePtr[0].col   = col;\n    DrawList._VtxWritePtr[1].pos.x = P2.x + dy;\n    DrawList._VtxWritePtr[1].pos.y = P2.y - dx;\n    DrawList._VtxWritePtr[1].uv    = uv;\n    DrawList._VtxWritePtr[1].col   = col;\n    DrawList._VtxWritePtr[2].pos.x = P2.x - dy;\n    DrawList._VtxWritePtr[2].pos.y = P2.y + dx;\n    DrawList._VtxWritePtr[2].uv    = uv;\n    DrawList._VtxWritePtr[2].col   = col;\n    DrawList._VtxWritePtr[3].pos.x = P1.x - dy;\n    DrawList._VtxWritePtr[3].pos.y = P1.y + dx;\n    DrawList._VtxWritePtr[3].uv    = uv;\n    DrawList._VtxWritePtr[3].col   = col;\n    DrawList._VtxWritePtr += 4;\n    DrawList._IdxWritePtr[0] = (ImDrawIdx)(DrawList._VtxCurrentIdx);\n    DrawList._IdxWritePtr[1] = (ImDrawIdx)(DrawList._VtxCurrentIdx + 1);\n    DrawList._IdxWritePtr[2] = (ImDrawIdx)(DrawList._VtxCurrentIdx + 2);\n    DrawList._IdxWritePtr[3] = (ImDrawIdx)(DrawList._VtxCurrentIdx);\n    DrawList._IdxWritePtr[4] = (ImDrawIdx)(DrawList._VtxCurrentIdx + 2);\n    DrawList._IdxWritePtr[5] = (ImDrawIdx)(DrawList._VtxCurrentIdx + 3);\n    DrawList._IdxWritePtr += 6;\n    DrawList._VtxCurrentIdx += 4;\n}\n\nIMPLOT_INLINE void PrimRectFilled(const ImVec2& Pmin, const ImVec2& Pmax, ImU32 col, ImDrawList& DrawList, ImVec2 uv) {\n    DrawList._VtxWritePtr[0].pos   = Pmin;\n    DrawList._VtxWritePtr[0].uv    = uv;\n    DrawList._VtxWritePtr[0].col   = col;\n    DrawList._VtxWritePtr[1].pos   = Pmax;\n    DrawList._VtxWritePtr[1].uv    = uv;\n    DrawList._VtxWritePtr[1].col   = col;\n    DrawList._VtxWritePtr[2].pos.x = Pmin.x;\n    DrawList._VtxWritePtr[2].pos.y = Pmax.y;\n    DrawList._VtxWritePtr[2].uv    = uv;\n    DrawList._VtxWritePtr[2].col   = col;\n    DrawList._VtxWritePtr[3].pos.x = Pmax.x;\n    DrawList._VtxWritePtr[3].pos.y = Pmin.y;\n    DrawList._VtxWritePtr[3].uv    = uv;\n    DrawList._VtxWritePtr[3].col   = col;\n    DrawList._VtxWritePtr += 4;\n    DrawList._IdxWritePtr[0] = (ImDrawIdx)(DrawList._VtxCurrentIdx);\n    DrawList._IdxWritePtr[1] = (ImDrawIdx)(DrawList._VtxCurrentIdx + 1);\n    DrawList._IdxWritePtr[2] = (ImDrawIdx)(DrawList._VtxCurrentIdx + 2);\n    DrawList._IdxWritePtr[3] = (ImDrawIdx)(DrawList._VtxCurrentIdx);\n    DrawList._IdxWritePtr[4] = (ImDrawIdx)(DrawList._VtxCurrentIdx + 1);\n    DrawList._IdxWritePtr[5] = (ImDrawIdx)(DrawList._VtxCurrentIdx + 3);\n    DrawList._IdxWritePtr += 6;\n    DrawList._VtxCurrentIdx += 4;\n}\n\ntemplate <typename TGetter, typename TTransformer>\nstruct LineStripRenderer {\n    IMPLOT_INLINE LineStripRenderer(const TGetter& getter, const TTransformer& transformer, ImU32 col, float weight) :\n        Getter(getter),\n        Transformer(transformer),\n        Prims(Getter.Count - 1),\n        Col(col),\n        HalfWeight(weight/2)\n    {\n        P1 = Transformer(Getter(0));\n    }\n    IMPLOT_INLINE bool operator()(ImDrawList& DrawList, const ImRect& cull_rect, const ImVec2& uv, int prim) const {\n        ImVec2 P2 = Transformer(Getter(prim + 1));\n        if (!cull_rect.Overlaps(ImRect(ImMin(P1, P2), ImMax(P1, P2)))) {\n            P1 = P2;\n            return false;\n        }\n        PrimLine(P1,P2,HalfWeight,Col,DrawList,uv);\n        P1 = P2;\n        return true;\n    }\n    const TGetter& Getter;\n    const TTransformer& Transformer;\n    const int Prims;\n    const ImU32 Col;\n    const float HalfWeight;\n    mutable ImVec2 P1;\n    static const int IdxConsumed = 6;\n    static const int VtxConsumed = 4;\n};\n\ntemplate <typename TGetter1, typename TGetter2, typename TTransformer>\nstruct LineSegmentsRenderer {\n    IMPLOT_INLINE LineSegmentsRenderer(const TGetter1& getter1, const TGetter2& getter2, const TTransformer& transformer, ImU32 col, float weight) :\n        Getter1(getter1),\n        Getter2(getter2),\n        Transformer(transformer),\n        Prims(ImMin(Getter1.Count, Getter2.Count)),\n        Col(col),\n        HalfWeight(weight/2)\n    {}\n    IMPLOT_INLINE bool operator()(ImDrawList& DrawList, const ImRect& cull_rect, const ImVec2& uv, int prim) const {\n        ImVec2 P1 = Transformer(Getter1(prim));\n        ImVec2 P2 = Transformer(Getter2(prim));\n        if (!cull_rect.Overlaps(ImRect(ImMin(P1, P2), ImMax(P1, P2))))\n            return false;\n        PrimLine(P1,P2,HalfWeight,Col,DrawList,uv);\n        return true;\n    }\n    const TGetter1& Getter1;\n    const TGetter2& Getter2;\n    const TTransformer& Transformer;\n    const int Prims;\n    const ImU32 Col;\n    const float HalfWeight;\n    static const int IdxConsumed = 6;\n    static const int VtxConsumed = 4;\n};\n\ntemplate <typename TGetter, typename TTransformer>\nstruct StairsRenderer {\n    IMPLOT_INLINE StairsRenderer(const TGetter& getter, const TTransformer& transformer, ImU32 col, float weight) :\n        Getter(getter),\n        Transformer(transformer),\n        Prims(Getter.Count - 1),\n        Col(col),\n        HalfWeight(weight * 0.5f)\n    {\n        P1 = Transformer(Getter(0));\n    }\n    IMPLOT_INLINE bool operator()(ImDrawList& DrawList, const ImRect& cull_rect, const ImVec2& uv, int prim) const {\n        ImVec2 P2 = Transformer(Getter(prim + 1));\n        if (!cull_rect.Overlaps(ImRect(ImMin(P1, P2), ImMax(P1, P2)))) {\n            P1 = P2;\n            return false;\n        }\n        PrimRectFilled(ImVec2(P1.x, P1.y + HalfWeight), ImVec2(P2.x, P1.y - HalfWeight), Col, DrawList, uv);\n        PrimRectFilled(ImVec2(P2.x - HalfWeight, P2.y), ImVec2(P2.x + HalfWeight, P1.y), Col, DrawList, uv);\n        P1 = P2;\n        return true;\n    }\n    const TGetter& Getter;\n    const TTransformer& Transformer;\n    const int Prims;\n    const ImU32 Col;\n    const float HalfWeight;\n    mutable ImVec2 P1;\n    static const int IdxConsumed = 12;\n    static const int VtxConsumed = 8;\n};\n\n\n\ntemplate <typename TGetter1, typename TGetter2, typename TTransformer>\nstruct ShadedRenderer {\n    IMPLOT_INLINE ShadedRenderer(const TGetter1& getter1, const TGetter2& getter2, const TTransformer& transformer, ImU32 col) :\n        Getter1(getter1),\n        Getter2(getter2),\n        Transformer(transformer),\n        Prims(ImMin(Getter1.Count, Getter2.Count) - 1),\n        Col(col)\n    {\n        P11 = Transformer(Getter1(0));\n        P12 = Transformer(Getter2(0));\n    }\n\n    IMPLOT_INLINE bool operator()(ImDrawList& DrawList, const ImRect& cull_rect, const ImVec2& uv, int prim) const {\n        ImVec2 P21 = Transformer(Getter1(prim+1));\n        ImVec2 P22 = Transformer(Getter2(prim+1));\n        ImRect rect(ImMin(ImMin(ImMin(P11,P12),P21),P22), ImMax(ImMax(ImMax(P11,P12),P21),P22));\n        if (!cull_rect.Overlaps(rect)) {\n            P11 = P21;\n            P12 = P22;\n            return false;\n        }\n        const int intersect = (P11.y > P12.y && P22.y > P21.y) || (P12.y > P11.y && P21.y > P22.y);\n        ImVec2 intersection = Intersection(P11,P21,P12,P22);\n        DrawList._VtxWritePtr[0].pos = P11;\n        DrawList._VtxWritePtr[0].uv  = uv;\n        DrawList._VtxWritePtr[0].col = Col;\n        DrawList._VtxWritePtr[1].pos = P21;\n        DrawList._VtxWritePtr[1].uv  = uv;\n        DrawList._VtxWritePtr[1].col = Col;\n        DrawList._VtxWritePtr[2].pos = intersection;\n        DrawList._VtxWritePtr[2].uv  = uv;\n        DrawList._VtxWritePtr[2].col = Col;\n        DrawList._VtxWritePtr[3].pos = P12;\n        DrawList._VtxWritePtr[3].uv  = uv;\n        DrawList._VtxWritePtr[3].col = Col;\n        DrawList._VtxWritePtr[4].pos = P22;\n        DrawList._VtxWritePtr[4].uv  = uv;\n        DrawList._VtxWritePtr[4].col = Col;\n        DrawList._VtxWritePtr += 5;\n        DrawList._IdxWritePtr[0] = (ImDrawIdx)(DrawList._VtxCurrentIdx);\n        DrawList._IdxWritePtr[1] = (ImDrawIdx)(DrawList._VtxCurrentIdx + 1 + intersect);\n        DrawList._IdxWritePtr[2] = (ImDrawIdx)(DrawList._VtxCurrentIdx + 3);\n        DrawList._IdxWritePtr[3] = (ImDrawIdx)(DrawList._VtxCurrentIdx + 1);\n        DrawList._IdxWritePtr[4] = (ImDrawIdx)(DrawList._VtxCurrentIdx + 4);\n        DrawList._IdxWritePtr[5] = (ImDrawIdx)(DrawList._VtxCurrentIdx + 3 - intersect);\n        DrawList._IdxWritePtr += 6;\n        DrawList._VtxCurrentIdx += 5;\n        P11 = P21;\n        P12 = P22;\n        return true;\n    }\n    const TGetter1& Getter1;\n    const TGetter2& Getter2;\n    const TTransformer& Transformer;\n    const int Prims;\n    const ImU32 Col;\n    mutable ImVec2 P11;\n    mutable ImVec2 P12;\n    static const int IdxConsumed = 6;\n    static const int VtxConsumed = 5;\n};\n\n/// Renders primitive shapes in bulk as efficiently as possible.\ntemplate <typename Renderer>\nIMPLOT_INLINE void RenderPrimitives(const Renderer& renderer, ImDrawList& DrawList, const ImRect& cull_rect) {\n    unsigned int prims        = renderer.Prims;\n    unsigned int prims_culled = 0;\n    unsigned int idx          = 0;\n    const ImVec2 uv = DrawList._Data->TexUvWhitePixel;\n    while (prims) {\n        // find how many can be reserved up to end of current draw command's limit\n        unsigned int cnt = ImMin(prims, (MaxIdx<ImDrawIdx>::Value - DrawList._VtxCurrentIdx) / Renderer::VtxConsumed);\n        // make sure at least this many elements can be rendered to avoid situations where at the end of buffer this slow path is not taken all the time\n        if (cnt >= ImMin(64u, prims)) {\n            if (prims_culled >= cnt)\n                prims_culled -= cnt; // reuse previous reservation\n            else {\n                DrawList.PrimReserve((cnt - prims_culled) * Renderer::IdxConsumed, (cnt - prims_culled) * Renderer::VtxConsumed); // add more elements to previous reservation\n                prims_culled = 0;\n            }\n        }\n        else\n        {\n            if (prims_culled > 0) {\n                DrawList.PrimUnreserve(prims_culled * Renderer::IdxConsumed, prims_culled * Renderer::VtxConsumed);\n                prims_culled = 0;\n            }\n            cnt = ImMin(prims, (MaxIdx<ImDrawIdx>::Value - 0/*DrawList._VtxCurrentIdx*/) / Renderer::VtxConsumed);\n            DrawList.PrimReserve(cnt * Renderer::IdxConsumed, cnt * Renderer::VtxConsumed); // reserve new draw command\n        }\n        prims -= cnt;\n        for (unsigned int ie = idx + cnt; idx != ie; ++idx) {\n            if (!renderer(DrawList, cull_rect, uv, idx))\n                prims_culled++;\n        }\n    }\n    if (prims_culled > 0)\n        DrawList.PrimUnreserve(prims_culled * Renderer::IdxConsumed, prims_culled * Renderer::VtxConsumed);\n}\n\ntemplate <typename Getter, typename Transformer>\nIMPLOT_INLINE void RenderLineStrip(const Getter& getter, const Transformer& transformer, ImDrawList& DrawList, float line_weight, ImU32 col) {\n    ImPlotContext& gp = *GImPlot;\n    if (ImHasFlag(gp.CurrentPlot->Flags, ImPlotFlags_AntiAliased) || gp.Style.AntiAliasedLines) {\n        ImVec2 p1 = transformer(getter(0));\n        for (int i = 1; i < getter.Count; ++i) {\n            ImVec2 p2 = transformer(getter(i));\n            if (gp.CurrentPlot->PlotRect.Overlaps(ImRect(ImMin(p1, p2), ImMax(p1, p2))))\n                DrawList.AddLine(p1, p2, col, line_weight);\n            p1 = p2;\n        }\n    }\n    else {\n        RenderPrimitives(LineStripRenderer<Getter,Transformer>(getter, transformer, col, line_weight), DrawList, gp.CurrentPlot->PlotRect);\n    }\n}\n\ntemplate <typename Getter1, typename Getter2, typename Transformer>\nIMPLOT_INLINE void RenderLineSegments(const Getter1& getter1, const Getter2& getter2, const Transformer& transformer, ImDrawList& DrawList, float line_weight, ImU32 col) {\n    ImPlotContext& gp = *GImPlot;\n    if (ImHasFlag(gp.CurrentPlot->Flags, ImPlotFlags_AntiAliased) || gp.Style.AntiAliasedLines) {\n        int I = ImMin(getter1.Count, getter2.Count);\n        for (int i = 0; i < I; ++i) {\n            ImVec2 p1 = transformer(getter1(i));\n            ImVec2 p2 = transformer(getter2(i));\n            if (gp.CurrentPlot->PlotRect.Overlaps(ImRect(ImMin(p1, p2), ImMax(p1, p2))))\n                DrawList.AddLine(p1, p2, col, line_weight);\n        }\n    }\n    else {\n        RenderPrimitives(LineSegmentsRenderer<Getter1,Getter2,Transformer>(getter1, getter2, transformer, col, line_weight), DrawList, gp.CurrentPlot->PlotRect);\n    }\n}\n\ntemplate <typename Getter, typename Transformer>\nIMPLOT_INLINE void RenderStairs(const Getter& getter, const Transformer& transformer, ImDrawList& DrawList, float line_weight, ImU32 col) {\n    ImPlotContext& gp = *GImPlot;\n    if (ImHasFlag(gp.CurrentPlot->Flags, ImPlotFlags_AntiAliased) || gp.Style.AntiAliasedLines) {\n        ImVec2 p1 = transformer(getter(0));\n        for (int i = 1; i < getter.Count; ++i) {\n            ImVec2 p2 = transformer(getter(i));\n            if (gp.CurrentPlot->PlotRect.Overlaps(ImRect(ImMin(p1, p2), ImMax(p1, p2)))) {\n                ImVec2 p12(p2.x, p1.y);\n                DrawList.AddLine(p1, p12, col, line_weight);\n                DrawList.AddLine(p12, p2, col, line_weight);\n            }\n            p1 = p2;\n        }\n    }\n    else {\n        RenderPrimitives(StairsRenderer<Getter,Transformer>(getter, transformer, col, line_weight), DrawList, gp.CurrentPlot->PlotRect);\n    }\n}\n\n//-----------------------------------------------------------------------------\n// MARKER RENDERERS\n//-----------------------------------------------------------------------------\n\nIMPLOT_INLINE void TransformMarker(ImVec2* points, int n, const ImVec2& c, float s) {\n    for (int i = 0; i < n; ++i) {\n        points[i].x = c.x + points[i].x * s;\n        points[i].y = c.y + points[i].y * s;\n    }\n}\n\nIMPLOT_INLINE void RenderMarkerGeneral(ImDrawList& DrawList, ImVec2* points, int n, const ImVec2& c, float s, bool outline, ImU32 col_outline, bool fill, ImU32 col_fill, float weight) {\n    TransformMarker(points, n, c, s);\n    if (fill)\n        DrawList.AddConvexPolyFilled(points, n, col_fill);\n    if (outline && !(fill && col_outline == col_fill)) {\n        for (int i = 0; i < n; ++i)\n            DrawList.AddLine(points[i], points[(i+1)%n], col_outline, weight);\n    }\n}\n\nIMPLOT_INLINE void RenderMarkerCircle(ImDrawList& DrawList, const ImVec2& c, float s, bool outline, ImU32 col_outline, bool fill, ImU32 col_fill, float weight) {\n    ImVec2 marker[10] = {ImVec2(1.0f, 0.0f),\n                         ImVec2(0.809017f, 0.58778524f),\n                         ImVec2(0.30901697f, 0.95105654f),\n                         ImVec2(-0.30901703f, 0.9510565f),\n                         ImVec2(-0.80901706f, 0.5877852f),\n                         ImVec2(-1.0f, 0.0f),\n                         ImVec2(-0.80901694f, -0.58778536f),\n                         ImVec2(-0.3090171f, -0.9510565f),\n                         ImVec2(0.30901712f, -0.9510565f),\n                         ImVec2(0.80901694f, -0.5877853f)};\n    RenderMarkerGeneral(DrawList, marker, 10, c, s, outline, col_outline, fill, col_fill, weight);\n}\n\nIMPLOT_INLINE void RenderMarkerDiamond(ImDrawList& DrawList, const ImVec2& c, float s, bool outline, ImU32 col_outline, bool fill, ImU32 col_fill, float weight) {\n    ImVec2 marker[4] = {ImVec2(1, 0), ImVec2(0, -1), ImVec2(-1, 0), ImVec2(0, 1)};\n    RenderMarkerGeneral(DrawList, marker, 4, c, s, outline, col_outline, fill, col_fill, weight);\n}\n\nIMPLOT_INLINE void RenderMarkerSquare(ImDrawList& DrawList, const ImVec2& c, float s, bool outline, ImU32 col_outline, bool fill, ImU32 col_fill, float weight) {\n    ImVec2 marker[4] = {ImVec2(SQRT_1_2,SQRT_1_2),ImVec2(SQRT_1_2,-SQRT_1_2),ImVec2(-SQRT_1_2,-SQRT_1_2),ImVec2(-SQRT_1_2,SQRT_1_2)};\n    RenderMarkerGeneral(DrawList, marker, 4, c, s, outline, col_outline, fill, col_fill, weight);\n}\n\nIMPLOT_INLINE void RenderMarkerUp(ImDrawList& DrawList, const ImVec2& c, float s, bool outline, ImU32 col_outline, bool fill, ImU32 col_fill, float weight) {\n    ImVec2 marker[3] = {ImVec2(SQRT_3_2,0.5f),ImVec2(0,-1),ImVec2(-SQRT_3_2,0.5f)};\n    RenderMarkerGeneral(DrawList, marker, 3, c, s, outline, col_outline, fill, col_fill, weight);\n}\n\nIMPLOT_INLINE void RenderMarkerDown(ImDrawList& DrawList, const ImVec2& c, float s, bool outline, ImU32 col_outline, bool fill, ImU32 col_fill, float weight) {\n    ImVec2 marker[3] = {ImVec2(SQRT_3_2,-0.5f),ImVec2(0,1),ImVec2(-SQRT_3_2,-0.5f)};\n    RenderMarkerGeneral(DrawList, marker, 3, c, s, outline, col_outline, fill, col_fill, weight);\n}\n\nIMPLOT_INLINE void RenderMarkerLeft(ImDrawList& DrawList, const ImVec2& c, float s, bool outline, ImU32 col_outline, bool fill, ImU32 col_fill, float weight) {\n    ImVec2 marker[3] = {ImVec2(-1,0), ImVec2(0.5, SQRT_3_2), ImVec2(0.5, -SQRT_3_2)};\n    RenderMarkerGeneral(DrawList, marker, 3, c, s, outline, col_outline, fill, col_fill, weight);\n}\n\nIMPLOT_INLINE void RenderMarkerRight(ImDrawList& DrawList, const ImVec2& c, float s, bool outline, ImU32 col_outline, bool fill, ImU32 col_fill, float weight) {\n    ImVec2 marker[3] = {ImVec2(1,0), ImVec2(-0.5, SQRT_3_2), ImVec2(-0.5, -SQRT_3_2)};\n    RenderMarkerGeneral(DrawList, marker, 3, c, s, outline, col_outline, fill, col_fill, weight);\n}\n\nIMPLOT_INLINE void RenderMarkerAsterisk(ImDrawList& DrawList, const ImVec2& c, float s, bool /*outline*/, ImU32 col_outline, bool /*fill*/, ImU32 /*col_fill*/, float weight) {\n    ImVec2 marker[6] = {ImVec2(SQRT_3_2, 0.5f), ImVec2(0, -1), ImVec2(-SQRT_3_2, 0.5f), ImVec2(SQRT_3_2, -0.5f), ImVec2(0, 1),  ImVec2(-SQRT_3_2, -0.5f)};\n    TransformMarker(marker, 6, c, s);\n    DrawList.AddLine(marker[0], marker[5], col_outline, weight);\n    DrawList.AddLine(marker[1], marker[4], col_outline, weight);\n    DrawList.AddLine(marker[2], marker[3], col_outline, weight);\n}\n\nIMPLOT_INLINE void RenderMarkerPlus(ImDrawList& DrawList, const ImVec2& c, float s, bool /*outline*/, ImU32 col_outline, bool /*fill*/, ImU32 /*col_fill*/, float weight) {\n    ImVec2 marker[4] = {ImVec2(1, 0), ImVec2(0, -1), ImVec2(-1, 0), ImVec2(0, 1)};\n    TransformMarker(marker, 4, c, s);\n    DrawList.AddLine(marker[0], marker[2], col_outline, weight);\n    DrawList.AddLine(marker[1], marker[3], col_outline, weight);\n}\n\nIMPLOT_INLINE void RenderMarkerCross(ImDrawList& DrawList, const ImVec2& c, float s, bool /*outline*/, ImU32 col_outline, bool /*fill*/, ImU32 /*col_fill*/, float weight) {\n    ImVec2 marker[4] = {ImVec2(SQRT_1_2,SQRT_1_2),ImVec2(SQRT_1_2,-SQRT_1_2),ImVec2(-SQRT_1_2,-SQRT_1_2),ImVec2(-SQRT_1_2,SQRT_1_2)};\n    TransformMarker(marker, 4, c, s);\n    DrawList.AddLine(marker[0], marker[2], col_outline, weight);\n    DrawList.AddLine(marker[1], marker[3], col_outline, weight);\n}\n\ntemplate <typename Transformer, typename Getter>\nIMPLOT_INLINE void RenderMarkers(Getter getter, Transformer transformer, ImDrawList& DrawList, ImPlotMarker marker, float size, bool rend_mk_line, ImU32 col_mk_line, float weight, bool rend_mk_fill, ImU32 col_mk_fill) {\n    static void (*marker_table[ImPlotMarker_COUNT])(ImDrawList&, const ImVec2&, float s, bool, ImU32, bool, ImU32, float) = {\n        RenderMarkerCircle,\n        RenderMarkerSquare,\n        RenderMarkerDiamond ,\n        RenderMarkerUp ,\n        RenderMarkerDown ,\n        RenderMarkerLeft,\n        RenderMarkerRight,\n        RenderMarkerCross,\n        RenderMarkerPlus,\n        RenderMarkerAsterisk\n    };\n    ImPlotContext& gp = *GImPlot;\n    const ImRect& rect = gp.CurrentPlot->PlotRect;\n    for (int i = 0; i < getter.Count; ++i) {\n        ImVec2 c = transformer(getter(i));\n        if (c.x >= rect.Min.x && c.y >= rect.Min.y && c.x <= rect.Max.x && c.y <= rect.Max.y)\n            marker_table[marker](DrawList, c, size, rend_mk_line, col_mk_line, rend_mk_fill, col_mk_fill, weight);\n    }\n}\n\n//-----------------------------------------------------------------------------\n// PLOT LINE\n//-----------------------------------------------------------------------------\n\ntemplate <typename Getter>\nIMPLOT_INLINE void PlotLineEx(const char* label_id, const Getter& getter) {\n    if (BeginItem(label_id, ImPlotCol_Line)) {\n        if (FitThisFrame()) {\n            for (int i = 0; i < getter.Count; ++i) {\n                ImPlotPoint p = getter(i);\n                FitPoint(p);\n            }\n        }\n        const ImPlotNextItemData& s = GetItemData();\n        ImDrawList& DrawList = *GetPlotDrawList();\n        if (getter.Count > 1 && s.RenderLine) {\n            const ImU32 col_line    = ImGui::GetColorU32(s.Colors[ImPlotCol_Line]);\n            switch (GetCurrentScale()) {\n                case ImPlotScale_LinLin: RenderLineStrip(getter, TransformerLinLin(), DrawList, s.LineWeight, col_line); break;\n                case ImPlotScale_LogLin: RenderLineStrip(getter, TransformerLogLin(), DrawList, s.LineWeight, col_line); break;\n                case ImPlotScale_LinLog: RenderLineStrip(getter, TransformerLinLog(), DrawList, s.LineWeight, col_line); break;\n                case ImPlotScale_LogLog: RenderLineStrip(getter, TransformerLogLog(), DrawList, s.LineWeight, col_line); break;\n            }\n        }\n        // render markers\n        if (s.Marker != ImPlotMarker_None) {\n            // uncomment lines below to render markers over plot rect border\n            // PopPlotClipRect();\n            // PushPlotClipRect(s.MarkerSize);\n            const ImU32 col_line = ImGui::GetColorU32(s.Colors[ImPlotCol_MarkerOutline]);\n            const ImU32 col_fill = ImGui::GetColorU32(s.Colors[ImPlotCol_MarkerFill]);\n            switch (GetCurrentScale()) {\n                case ImPlotScale_LinLin: RenderMarkers(getter, TransformerLinLin(), DrawList, s.Marker, s.MarkerSize, s.RenderMarkerLine, col_line, s.MarkerWeight, s.RenderMarkerFill, col_fill); break;\n                case ImPlotScale_LogLin: RenderMarkers(getter, TransformerLogLin(), DrawList, s.Marker, s.MarkerSize, s.RenderMarkerLine, col_line, s.MarkerWeight, s.RenderMarkerFill, col_fill); break;\n                case ImPlotScale_LinLog: RenderMarkers(getter, TransformerLinLog(), DrawList, s.Marker, s.MarkerSize, s.RenderMarkerLine, col_line, s.MarkerWeight, s.RenderMarkerFill, col_fill); break;\n                case ImPlotScale_LogLog: RenderMarkers(getter, TransformerLogLog(), DrawList, s.Marker, s.MarkerSize, s.RenderMarkerLine, col_line, s.MarkerWeight, s.RenderMarkerFill, col_fill); break;\n            }\n        }\n        EndItem();\n    }\n}\n\n\ntemplate <typename T>\nvoid PlotLine(const char* label_id, const T* values, int count, double xscale, double x0, int offset, int stride) {\n    GetterXY<GetterLin,GetterIdx<T>> getter(GetterLin(xscale,x0),GetterIdx<T>(values,count,offset,stride),count);\n    PlotLineEx(label_id, getter);\n}\n\ntemplate IMPLOT_API void PlotLine<ImS8> (const char* label_id, const ImS8* values, int count, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotLine<ImU8> (const char* label_id, const ImU8* values, int count, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotLine<ImS16>(const char* label_id, const ImS16* values, int count, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotLine<ImU16>(const char* label_id, const ImU16* values, int count, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotLine<ImS32>(const char* label_id, const ImS32* values, int count, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotLine<ImU32>(const char* label_id, const ImU32* values, int count, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotLine<ImS64>(const char* label_id, const ImS64* values, int count, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotLine<ImU64>(const char* label_id, const ImU64* values, int count, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotLine<float>(const char* label_id, const float* values, int count, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotLine<double>(const char* label_id, const double* values, int count, double xscale, double x0, int offset, int stride);\n\ntemplate <typename T>\nvoid PlotLine(const char* label_id, const T* xs, const T* ys, int count, int offset, int stride) {\n    GetterXY<GetterIdx<T>,GetterIdx<T>> getter(GetterIdx<T>(xs,count,offset,stride),GetterIdx<T>(ys,count,offset,stride),count);\n    return PlotLineEx(label_id, getter);\n}\n\ntemplate IMPLOT_API void PlotLine<ImS8>(const char* label_id, const ImS8* xs, const ImS8* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotLine<ImU8>(const char* label_id, const ImU8* xs, const ImU8* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotLine<ImS16>(const char* label_id, const ImS16* xs, const ImS16* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotLine<ImU16>(const char* label_id, const ImU16* xs, const ImU16* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotLine<ImS32>(const char* label_id, const ImS32* xs, const ImS32* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotLine<ImU32>(const char* label_id, const ImU32* xs, const ImU32* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotLine<ImS64>(const char* label_id, const ImS64* xs, const ImS64* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotLine<ImU64>(const char* label_id, const ImU64* xs, const ImU64* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotLine<float>(const char* label_id, const float* xs, const float* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotLine<double>(const char* label_id, const double* xs, const double* ys, int count, int offset, int stride);\n\n// custom\nvoid PlotLineG(const char* label_id, ImPlotGetter getter_func, void* data, int count) {\n    GetterFuncPtr getter(getter_func,data, count);\n    return PlotLineEx(label_id, getter);\n}\n\n//-----------------------------------------------------------------------------\n// PLOT SCATTER\n//-----------------------------------------------------------------------------\n\ntemplate <typename Getter>\nIMPLOT_INLINE void PlotScatterEx(const char* label_id, const Getter& getter) {\n    if (BeginItem(label_id, ImPlotCol_MarkerOutline)) {\n        if (FitThisFrame()) {\n            for (int i = 0; i < getter.Count; ++i) {\n                ImPlotPoint p = getter(i);\n                FitPoint(p);\n            }\n        }\n        const ImPlotNextItemData& s = GetItemData();\n        ImDrawList& DrawList = *GetPlotDrawList();\n        // render markers\n        ImPlotMarker marker = s.Marker == ImPlotMarker_None ? ImPlotMarker_Circle : s.Marker;\n        if (marker != ImPlotMarker_None) {\n            // uncomment lines below to render markers over plot rect border\n            // PopPlotClipRect();\n            // PushPlotClipRect(s.MarkerSize);\n            const ImU32 col_line = ImGui::GetColorU32(s.Colors[ImPlotCol_MarkerOutline]);\n            const ImU32 col_fill = ImGui::GetColorU32(s.Colors[ImPlotCol_MarkerFill]);\n            switch (GetCurrentScale()) {\n                case ImPlotScale_LinLin: RenderMarkers(getter, TransformerLinLin(), DrawList, marker, s.MarkerSize, s.RenderMarkerLine, col_line, s.MarkerWeight, s.RenderMarkerFill, col_fill); break;\n                case ImPlotScale_LogLin: RenderMarkers(getter, TransformerLogLin(), DrawList, marker, s.MarkerSize, s.RenderMarkerLine, col_line, s.MarkerWeight, s.RenderMarkerFill, col_fill); break;\n                case ImPlotScale_LinLog: RenderMarkers(getter, TransformerLinLog(), DrawList, marker, s.MarkerSize, s.RenderMarkerLine, col_line, s.MarkerWeight, s.RenderMarkerFill, col_fill); break;\n                case ImPlotScale_LogLog: RenderMarkers(getter, TransformerLogLog(), DrawList, marker, s.MarkerSize, s.RenderMarkerLine, col_line, s.MarkerWeight, s.RenderMarkerFill, col_fill); break;\n            }\n        }\n        EndItem();\n    }\n}\n\ntemplate <typename T>\nvoid PlotScatter(const char* label_id, const T* values, int count, double xscale, double x0, int offset, int stride) {\n    GetterXY<GetterLin,GetterIdx<T>> getter(GetterLin(xscale,x0),GetterIdx<T>(values,count,offset,stride),count);\n    PlotScatterEx(label_id, getter);\n}\n\ntemplate IMPLOT_API void PlotScatter<ImS8>(const char* label_id, const ImS8* values, int count, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotScatter<ImU8>(const char* label_id, const ImU8* values, int count, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotScatter<ImS16>(const char* label_id, const ImS16* values, int count, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotScatter<ImU16>(const char* label_id, const ImU16* values, int count, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotScatter<ImS32>(const char* label_id, const ImS32* values, int count, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotScatter<ImU32>(const char* label_id, const ImU32* values, int count, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotScatter<ImS64>(const char* label_id, const ImS64* values, int count, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotScatter<ImU64>(const char* label_id, const ImU64* values, int count, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotScatter<float>(const char* label_id, const float* values, int count, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotScatter<double>(const char* label_id, const double* values, int count, double xscale, double x0, int offset, int stride);\n\ntemplate <typename T>\nvoid PlotScatter(const char* label_id, const T* xs, const T* ys, int count, int offset, int stride) {\n    GetterXY<GetterIdx<T>,GetterIdx<T>> getter(GetterIdx<T>(xs,count,offset,stride),GetterIdx<T>(ys,count,offset,stride),count);\n    return PlotScatterEx(label_id, getter);\n}\n\ntemplate IMPLOT_API void PlotScatter<ImS8>(const char* label_id, const ImS8* xs, const ImS8* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotScatter<ImU8>(const char* label_id, const ImU8* xs, const ImU8* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotScatter<ImS16>(const char* label_id, const ImS16* xs, const ImS16* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotScatter<ImU16>(const char* label_id, const ImU16* xs, const ImU16* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotScatter<ImS32>(const char* label_id, const ImS32* xs, const ImS32* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotScatter<ImU32>(const char* label_id, const ImU32* xs, const ImU32* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotScatter<ImS64>(const char* label_id, const ImS64* xs, const ImS64* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotScatter<ImU64>(const char* label_id, const ImU64* xs, const ImU64* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotScatter<float>(const char* label_id, const float* xs, const float* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotScatter<double>(const char* label_id, const double* xs, const double* ys, int count, int offset, int stride);\n\n// custom\nvoid PlotScatterG(const char* label_id, ImPlotGetter getter_func, void* data, int count) {\n    GetterFuncPtr getter(getter_func,data, count);\n    return PlotScatterEx(label_id, getter);\n}\n\n//-----------------------------------------------------------------------------\n// PLOT STAIRS\n//-----------------------------------------------------------------------------\n\ntemplate <typename Getter>\nIMPLOT_INLINE void PlotStairsEx(const char* label_id, const Getter& getter) {\n    if (BeginItem(label_id, ImPlotCol_Line)) {\n        if (FitThisFrame()) {\n            for (int i = 0; i < getter.Count; ++i) {\n                ImPlotPoint p = getter(i);\n                FitPoint(p);\n            }\n        }\n        const ImPlotNextItemData& s = GetItemData();\n        ImDrawList& DrawList = *GetPlotDrawList();\n        if (getter.Count > 1 && s.RenderLine) {\n            const ImU32 col_line    = ImGui::GetColorU32(s.Colors[ImPlotCol_Line]);\n            switch (GetCurrentScale()) {\n                case ImPlotScale_LinLin: RenderStairs(getter, TransformerLinLin(), DrawList, s.LineWeight, col_line); break;\n                case ImPlotScale_LogLin: RenderStairs(getter, TransformerLogLin(), DrawList, s.LineWeight, col_line); break;\n                case ImPlotScale_LinLog: RenderStairs(getter, TransformerLinLog(), DrawList, s.LineWeight, col_line); break;\n                case ImPlotScale_LogLog: RenderStairs(getter, TransformerLogLog(), DrawList, s.LineWeight, col_line); break;\n            }\n        }\n        // render markers\n        if (s.Marker != ImPlotMarker_None) {\n            PopPlotClipRect();\n            PushPlotClipRect(s.MarkerSize);\n            const ImU32 col_line = ImGui::GetColorU32(s.Colors[ImPlotCol_MarkerOutline]);\n            const ImU32 col_fill = ImGui::GetColorU32(s.Colors[ImPlotCol_MarkerFill]);\n            switch (GetCurrentScale()) {\n                case ImPlotScale_LinLin: RenderMarkers(getter, TransformerLinLin(), DrawList, s.Marker, s.MarkerSize, s.RenderMarkerLine, col_line, s.MarkerWeight, s.RenderMarkerFill, col_fill); break;\n                case ImPlotScale_LogLin: RenderMarkers(getter, TransformerLogLin(), DrawList, s.Marker, s.MarkerSize, s.RenderMarkerLine, col_line, s.MarkerWeight, s.RenderMarkerFill, col_fill); break;\n                case ImPlotScale_LinLog: RenderMarkers(getter, TransformerLinLog(), DrawList, s.Marker, s.MarkerSize, s.RenderMarkerLine, col_line, s.MarkerWeight, s.RenderMarkerFill, col_fill); break;\n                case ImPlotScale_LogLog: RenderMarkers(getter, TransformerLogLog(), DrawList, s.Marker, s.MarkerSize, s.RenderMarkerLine, col_line, s.MarkerWeight, s.RenderMarkerFill, col_fill); break;\n            }\n        }\n        EndItem();\n    }\n}\n\ntemplate <typename T>\nvoid PlotStairs(const char* label_id, const T* values, int count, double xscale, double x0, int offset, int stride) {\n    GetterXY<GetterLin,GetterIdx<T>> getter(GetterLin(xscale,x0),GetterIdx<T>(values,count,offset,stride),count);\n    PlotStairsEx(label_id, getter);\n}\n\ntemplate IMPLOT_API void PlotStairs<ImS8> (const char* label_id, const ImS8* values, int count, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotStairs<ImU8> (const char* label_id, const ImU8* values, int count, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotStairs<ImS16>(const char* label_id, const ImS16* values, int count, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotStairs<ImU16>(const char* label_id, const ImU16* values, int count, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotStairs<ImS32>(const char* label_id, const ImS32* values, int count, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotStairs<ImU32>(const char* label_id, const ImU32* values, int count, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotStairs<ImS64>(const char* label_id, const ImS64* values, int count, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotStairs<ImU64>(const char* label_id, const ImU64* values, int count, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotStairs<float>(const char* label_id, const float* values, int count, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotStairs<double>(const char* label_id, const double* values, int count, double xscale, double x0, int offset, int stride);\n\ntemplate <typename T>\nvoid PlotStairs(const char* label_id, const T* xs, const T* ys, int count, int offset, int stride) {\n    GetterXY<GetterIdx<T>,GetterIdx<T>> getter(GetterIdx<T>(xs,count,offset,stride),GetterIdx<T>(ys,count,offset,stride),count);\n    return PlotStairsEx(label_id, getter);\n}\n\ntemplate IMPLOT_API void PlotStairs<ImS8>(const char* label_id, const ImS8* xs, const ImS8* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotStairs<ImU8>(const char* label_id, const ImU8* xs, const ImU8* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotStairs<ImS16>(const char* label_id, const ImS16* xs, const ImS16* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotStairs<ImU16>(const char* label_id, const ImU16* xs, const ImU16* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotStairs<ImS32>(const char* label_id, const ImS32* xs, const ImS32* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotStairs<ImU32>(const char* label_id, const ImU32* xs, const ImU32* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotStairs<ImS64>(const char* label_id, const ImS64* xs, const ImS64* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotStairs<ImU64>(const char* label_id, const ImU64* xs, const ImU64* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotStairs<float>(const char* label_id, const float* xs, const float* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotStairs<double>(const char* label_id, const double* xs, const double* ys, int count, int offset, int stride);\n\n// custom\nvoid PlotStairsG(const char* label_id, ImPlotGetter getter_func, void* data, int count) {\n    GetterFuncPtr getter(getter_func,data, count);\n    return PlotStairsEx(label_id, getter);\n}\n\n//-----------------------------------------------------------------------------\n// PLOT SHADED\n//-----------------------------------------------------------------------------\n\ntemplate <typename Getter1, typename Getter2>\nIMPLOT_INLINE void PlotShadedEx(const char* label_id, const Getter1& getter1, const Getter2& getter2, bool fit2) {\n    if (BeginItem(label_id, ImPlotCol_Fill)) {\n        if (FitThisFrame()) {\n            for (int i = 0; i < getter1.Count; ++i)\n                FitPoint(getter1(i));\n            if (fit2) {\n                for (int i = 0; i < getter2.Count; ++i)\n                    FitPoint(getter2(i));\n            }\n        }\n        const ImPlotNextItemData& s = GetItemData();\n        ImDrawList & DrawList = *GetPlotDrawList();\n        if (s.RenderFill) {\n            ImU32 col = ImGui::GetColorU32(s.Colors[ImPlotCol_Fill]);\n            switch (GetCurrentScale()) {\n                case ImPlotScale_LinLin: RenderPrimitives(ShadedRenderer<Getter1,Getter2,TransformerLinLin>(getter1,getter2,TransformerLinLin(), col), DrawList, GImPlot->CurrentPlot->PlotRect); break;\n                case ImPlotScale_LogLin: RenderPrimitives(ShadedRenderer<Getter1,Getter2,TransformerLogLin>(getter1,getter2,TransformerLogLin(), col), DrawList, GImPlot->CurrentPlot->PlotRect); break;\n                case ImPlotScale_LinLog: RenderPrimitives(ShadedRenderer<Getter1,Getter2,TransformerLinLog>(getter1,getter2,TransformerLinLog(), col), DrawList, GImPlot->CurrentPlot->PlotRect); break;\n                case ImPlotScale_LogLog: RenderPrimitives(ShadedRenderer<Getter1,Getter2,TransformerLogLog>(getter1,getter2,TransformerLogLog(), col), DrawList, GImPlot->CurrentPlot->PlotRect); break;\n            }\n        }\n        EndItem();\n    }\n}\n\ntemplate <typename T>\nvoid PlotShaded(const char* label_id, const T* values, int count, double y_ref, double xscale, double x0, int offset, int stride) {\n    bool fit2 = true;\n    if (!(y_ref > -DBL_MAX)) { // filters out nans too\n        fit2 = false;\n        y_ref = GetPlotLimits(IMPLOT_AUTO,IMPLOT_AUTO).Y.Min;\n    }\n    if (!(y_ref < DBL_MAX)) { // filters out nans too\n        fit2 = false;\n        y_ref = GetPlotLimits(IMPLOT_AUTO,IMPLOT_AUTO).Y.Max;\n    }\n    GetterXY<GetterLin,GetterIdx<T>> getter1(GetterLin(xscale,x0),GetterIdx<T>(values,count,offset,stride),count);\n    GetterXY<GetterLin,GetterRef>    getter2(GetterLin(xscale,x0),GetterRef(y_ref),count);\n    PlotShadedEx(label_id, getter1, getter2, fit2);\n}\n\ntemplate IMPLOT_API void PlotShaded<ImS8>(const char* label_id, const ImS8* values, int count, double y_ref, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotShaded<ImU8>(const char* label_id, const ImU8* values, int count, double y_ref, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotShaded<ImS16>(const char* label_id, const ImS16* values, int count, double y_ref, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotShaded<ImU16>(const char* label_id, const ImU16* values, int count, double y_ref, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotShaded<ImS32>(const char* label_id, const ImS32* values, int count, double y_ref, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotShaded<ImU32>(const char* label_id, const ImU32* values, int count, double y_ref, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotShaded<ImS64>(const char* label_id, const ImS64* values, int count, double y_ref, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotShaded<ImU64>(const char* label_id, const ImU64* values, int count, double y_ref, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotShaded<float>(const char* label_id, const float* values, int count, double y_ref, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotShaded<double>(const char* label_id, const double* values, int count, double y_ref, double xscale, double x0, int offset, int stride);\n\ntemplate <typename T>\nvoid PlotShaded(const char* label_id, const T* xs, const T* ys, int count, double y_ref, int offset, int stride) {\n    bool fit2 = true;\n    if (!(y_ref > -DBL_MAX)) { // filters out nans too\n        fit2 = false;\n        y_ref = GetPlotLimits(IMPLOT_AUTO,IMPLOT_AUTO).Y.Min;\n    }\n    if (!(y_ref < DBL_MAX)) { // filters out nans too\n        fit2 = false;\n        y_ref = GetPlotLimits(IMPLOT_AUTO,IMPLOT_AUTO).Y.Max;\n    }\n    GetterXY<GetterIdx<T>,GetterIdx<T>> getter1(GetterIdx<T>(xs,count,offset,stride),GetterIdx<T>(ys,count,offset,stride),count);\n    GetterXY<GetterIdx<T>,GetterRef>    getter2(GetterIdx<T>(xs,count,offset,stride),GetterRef(y_ref),count);\n    PlotShadedEx(label_id, getter1, getter2, fit2);\n}\n\ntemplate IMPLOT_API void PlotShaded<ImS8>(const char* label_id, const ImS8* xs, const ImS8* ys, int count, double y_ref, int offset, int stride);\ntemplate IMPLOT_API void PlotShaded<ImU8>(const char* label_id, const ImU8* xs, const ImU8* ys, int count, double y_ref, int offset, int stride);\ntemplate IMPLOT_API void PlotShaded<ImS16>(const char* label_id, const ImS16* xs, const ImS16* ys, int count, double y_ref, int offset, int stride);\ntemplate IMPLOT_API void PlotShaded<ImU16>(const char* label_id, const ImU16* xs, const ImU16* ys, int count, double y_ref, int offset, int stride);\ntemplate IMPLOT_API void PlotShaded<ImS32>(const char* label_id, const ImS32* xs, const ImS32* ys, int count, double y_ref, int offset, int stride);\ntemplate IMPLOT_API void PlotShaded<ImU32>(const char* label_id, const ImU32* xs, const ImU32* ys, int count, double y_ref, int offset, int stride);\ntemplate IMPLOT_API void PlotShaded<ImS64>(const char* label_id, const ImS64* xs, const ImS64* ys, int count, double y_ref, int offset, int stride);\ntemplate IMPLOT_API void PlotShaded<ImU64>(const char* label_id, const ImU64* xs, const ImU64* ys, int count, double y_ref, int offset, int stride);\ntemplate IMPLOT_API void PlotShaded<float>(const char* label_id, const float* xs, const float* ys, int count, double y_ref, int offset, int stride);\ntemplate IMPLOT_API void PlotShaded<double>(const char* label_id, const double* xs, const double* ys, int count, double y_ref, int offset, int stride);\n\ntemplate <typename T>\nvoid PlotShaded(const char* label_id, const T* xs, const T* ys1, const T* ys2, int count, int offset, int stride) {\n    GetterXY<GetterIdx<T>,GetterIdx<T>> getter1(GetterIdx<T>(xs,count,offset,stride),GetterIdx<T>(ys1,count,offset,stride),count);\n    GetterXY<GetterIdx<T>,GetterIdx<T>> getter2(GetterIdx<T>(xs,count,offset,stride),GetterIdx<T>(ys2,count,offset,stride),count);\n    PlotShadedEx(label_id, getter1, getter2, true);\n}\n\ntemplate IMPLOT_API void PlotShaded<ImS8>(const char* label_id, const ImS8* xs, const ImS8* ys1, const ImS8* ys2, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotShaded<ImU8>(const char* label_id, const ImU8* xs, const ImU8* ys1, const ImU8* ys2, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotShaded<ImS16>(const char* label_id, const ImS16* xs, const ImS16* ys1, const ImS16* ys2, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotShaded<ImU16>(const char* label_id, const ImU16* xs, const ImU16* ys1, const ImU16* ys2, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotShaded<ImS32>(const char* label_id, const ImS32* xs, const ImS32* ys1, const ImS32* ys2, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotShaded<ImU32>(const char* label_id, const ImU32* xs, const ImU32* ys1, const ImU32* ys2, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotShaded<ImS64>(const char* label_id, const ImS64* xs, const ImS64* ys1, const ImS64* ys2, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotShaded<ImU64>(const char* label_id, const ImU64* xs, const ImU64* ys1, const ImU64* ys2, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotShaded<float>(const char* label_id, const float* xs, const float* ys1, const float* ys2, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotShaded<double>(const char* label_id, const double* xs, const double* ys1, const double* ys2, int count, int offset, int stride);\n\n// custom\nvoid PlotShadedG(const char* label_id, ImPlotGetter getter_func1, void* data1, ImPlotGetter getter_func2, void* data2, int count) {\n    GetterFuncPtr getter1(getter_func1, data1, count);\n    GetterFuncPtr getter2(getter_func2, data2, count);\n    PlotShadedEx(label_id, getter1, getter2, true);\n}\n\n//-----------------------------------------------------------------------------\n// PLOT BAR\n//-----------------------------------------------------------------------------\n\n// TODO: Migrate to RenderPrimitives\n\ntemplate <typename Getter1, typename Getter2>\nvoid PlotBarsEx(const char* label_id, const Getter1& getter1, const Getter2 getter2, double width) {\n    if (BeginItem(label_id, ImPlotCol_Fill)) {\n        const double half_width = width / 2;\n        if (FitThisFrame()) {\n            for (int i = 0; i < getter1.Count; ++i) {\n                ImPlotPoint p1 = getter1(i);\n                ImPlotPoint p2 = getter2(i);\n                FitPoint(ImPlotPoint(p1.x - half_width, p1.y));\n                FitPoint(ImPlotPoint(p2.x + half_width, p2.y));\n            }\n        }\n        const ImPlotNextItemData& s = GetItemData();\n        ImDrawList& DrawList = *GetPlotDrawList();\n        ImU32 col_line  = ImGui::GetColorU32(s.Colors[ImPlotCol_Line]);\n        ImU32 col_fill  = ImGui::GetColorU32(s.Colors[ImPlotCol_Fill]);\n        bool  rend_line = s.RenderLine;\n        if (s.RenderFill && col_line == col_fill)\n            rend_line = false;\n        for (int i = 0; i < getter1.Count; ++i) {\n            ImPlotPoint p1 = getter1(i);\n            ImPlotPoint p2 = getter2(i);\n            if (p1.y == p2.y)\n                continue;\n            ImVec2 a = PlotToPixels(p1.x - half_width, p1.y,IMPLOT_AUTO,IMPLOT_AUTO);\n            ImVec2 b = PlotToPixels(p2.x + half_width, p2.y,IMPLOT_AUTO,IMPLOT_AUTO);\n            float width_px = ImAbs(a.x-b.x);\n            if (width_px < 1.0f) {\n                a.x += a.x > b.x ? (1-width_px) / 2 : (width_px-1) / 2;\n                b.x += b.x > a.x ? (1-width_px) / 2 : (width_px-1) / 2;\n            }\n            // a.x = IM_ROUND(a.x);\n            // b.x = IM_ROUND(b.x);\n            if (s.RenderFill)\n                DrawList.AddRectFilled(a, b, col_fill);\n            if (rend_line)\n                DrawList.AddRect(a, b, col_line, 0, ImDrawFlags_RoundCornersAll, s.LineWeight);\n        }\n        EndItem();\n    }\n}\n\ntemplate <typename T>\nvoid PlotBars(const char* label_id, const T* values, int count, double width, double shift, int offset, int stride) {\n    GetterXY<GetterLin,GetterIdx<T>> getter1(GetterLin(1.0,shift),GetterIdx<T>(values,count,offset,stride),count);\n    GetterXY<GetterLin,GetterRef>    getter2(GetterLin(1.0,shift),GetterRef(0),count);\n    PlotBarsEx(label_id, getter1, getter2, width);\n}\n\ntemplate IMPLOT_API void PlotBars<ImS8>(const char* label_id, const ImS8* values, int count, double width, double shift, int offset, int stride);\ntemplate IMPLOT_API void PlotBars<ImU8>(const char* label_id, const ImU8* values, int count, double width, double shift, int offset, int stride);\ntemplate IMPLOT_API void PlotBars<ImS16>(const char* label_id, const ImS16* values, int count, double width, double shift, int offset, int stride);\ntemplate IMPLOT_API void PlotBars<ImU16>(const char* label_id, const ImU16* values, int count, double width, double shift, int offset, int stride);\ntemplate IMPLOT_API void PlotBars<ImS32>(const char* label_id, const ImS32* values, int count, double width, double shift, int offset, int stride);\ntemplate IMPLOT_API void PlotBars<ImU32>(const char* label_id, const ImU32* values, int count, double width, double shift, int offset, int stride);\ntemplate IMPLOT_API void PlotBars<ImS64>(const char* label_id, const ImS64* values, int count, double width, double shift, int offset, int stride);\ntemplate IMPLOT_API void PlotBars<ImU64>(const char* label_id, const ImU64* values, int count, double width, double shift, int offset, int stride);\ntemplate IMPLOT_API void PlotBars<float>(const char* label_id, const float* values, int count, double width, double shift, int offset, int stride);\ntemplate IMPLOT_API void PlotBars<double>(const char* label_id, const double* values, int count, double width, double shift, int offset, int stride);\n\ntemplate <typename T>\nvoid PlotBars(const char* label_id, const T* xs, const T* ys, int count, double width, int offset, int stride) {\n    GetterXY<GetterIdx<T>,GetterIdx<T>> getter1(GetterIdx<T>(xs,count,offset,stride),GetterIdx<T>(ys,count,offset,stride),count);\n    GetterXY<GetterIdx<T>,GetterRef>    getter2(GetterIdx<T>(xs,count,offset,stride),GetterRef(0),count);\n    PlotBarsEx(label_id, getter1, getter2, width);\n}\n\ntemplate IMPLOT_API void PlotBars<ImS8>(const char* label_id, const ImS8* xs, const ImS8* ys, int count, double width, int offset, int stride);\ntemplate IMPLOT_API void PlotBars<ImU8>(const char* label_id, const ImU8* xs, const ImU8* ys, int count, double width, int offset, int stride);\ntemplate IMPLOT_API void PlotBars<ImS16>(const char* label_id, const ImS16* xs, const ImS16* ys, int count, double width, int offset, int stride);\ntemplate IMPLOT_API void PlotBars<ImU16>(const char* label_id, const ImU16* xs, const ImU16* ys, int count, double width, int offset, int stride);\ntemplate IMPLOT_API void PlotBars<ImS32>(const char* label_id, const ImS32* xs, const ImS32* ys, int count, double width, int offset, int stride);\ntemplate IMPLOT_API void PlotBars<ImU32>(const char* label_id, const ImU32* xs, const ImU32* ys, int count, double width, int offset, int stride);\ntemplate IMPLOT_API void PlotBars<ImS64>(const char* label_id, const ImS64* xs, const ImS64* ys, int count, double width, int offset, int stride);\ntemplate IMPLOT_API void PlotBars<ImU64>(const char* label_id, const ImU64* xs, const ImU64* ys, int count, double width, int offset, int stride);\ntemplate IMPLOT_API void PlotBars<float>(const char* label_id, const float* xs, const float* ys, int count, double width, int offset, int stride);\ntemplate IMPLOT_API void PlotBars<double>(const char* label_id, const double* xs, const double* ys, int count, double width, int offset, int stride);\n\n// custom\nvoid PlotBarsG(const char* label_id, ImPlotGetter getter_func, void* data, int count, double width) {\n    GetterFuncPtr getter1(getter_func, data, count);\n    GetterOverrideY<GetterFuncPtr> getter2(getter1,0);\n    PlotBarsEx(label_id, getter1, getter2, width);\n}\n\n//-----------------------------------------------------------------------------\n// PLOT BAR H\n//-----------------------------------------------------------------------------\n\n// TODO: Migrate to RenderPrimitives\n\ntemplate <typename Getter1, typename Getter2>\nvoid PlotBarsHEx(const char* label_id, const Getter1& getter1, const Getter2& getter2, double height) {\n    if (BeginItem(label_id, ImPlotCol_Fill)) {\n        const double half_height = height / 2;\n        if (FitThisFrame()) {\n            for (int i = 0; i < getter1.Count; ++i) {\n                ImPlotPoint p1 = getter1(i);\n                ImPlotPoint p2 = getter2(i);\n                FitPoint(ImPlotPoint(p1.x, p1.y - half_height));\n                FitPoint(ImPlotPoint(p2.x, p2.y + half_height));\n            }\n        }\n        const ImPlotNextItemData& s = GetItemData();\n        ImDrawList& DrawList = *GetPlotDrawList();\n        ImU32 col_line  = ImGui::GetColorU32(s.Colors[ImPlotCol_Line]);\n        ImU32 col_fill  = ImGui::GetColorU32(s.Colors[ImPlotCol_Fill]);\n        bool  rend_line = s.RenderLine;\n        if (s.RenderFill && col_line == col_fill)\n            rend_line = false;\n        for (int i = 0; i < getter1.Count; ++i) {\n            ImPlotPoint p1 = getter1(i);\n            ImPlotPoint p2 = getter2(i);\n            if (p1.x == p2.x)\n                continue;\n            ImVec2 a = PlotToPixels(p1.x, p1.y - half_height,IMPLOT_AUTO,IMPLOT_AUTO);\n            ImVec2 b = PlotToPixels(p2.x, p2.y + half_height,IMPLOT_AUTO,IMPLOT_AUTO);\n            if (s.RenderFill)\n                DrawList.AddRectFilled(a, b, col_fill);\n            if (rend_line)\n                DrawList.AddRect(a, b, col_line, 0, ImDrawFlags_RoundCornersAll, s.LineWeight);\n        }\n        EndItem();\n    }\n}\n\ntemplate <typename T>\nvoid PlotBarsH(const char* label_id, const T* values, int count, double height, double shift, int offset, int stride) {\n    GetterXY<GetterIdx<T>,GetterLin> getter1(GetterIdx<T>(values,count,offset,stride),GetterLin(1.0,shift),count);\n    GetterXY<GetterRef,GetterLin>    getter2(GetterRef(0),GetterLin(1.0,shift),count);\n    PlotBarsHEx(label_id, getter1, getter2, height);\n}\n\ntemplate IMPLOT_API void PlotBarsH<ImS8>(const char* label_id, const ImS8* values, int count, double height, double shift, int offset, int stride);\ntemplate IMPLOT_API void PlotBarsH<ImU8>(const char* label_id, const ImU8* values, int count, double height, double shift, int offset, int stride);\ntemplate IMPLOT_API void PlotBarsH<ImS16>(const char* label_id, const ImS16* values, int count, double height, double shift, int offset, int stride);\ntemplate IMPLOT_API void PlotBarsH<ImU16>(const char* label_id, const ImU16* values, int count, double height, double shift, int offset, int stride);\ntemplate IMPLOT_API void PlotBarsH<ImS32>(const char* label_id, const ImS32* values, int count, double height, double shift, int offset, int stride);\ntemplate IMPLOT_API void PlotBarsH<ImU32>(const char* label_id, const ImU32* values, int count, double height, double shift, int offset, int stride);\ntemplate IMPLOT_API void PlotBarsH<ImS64>(const char* label_id, const ImS64* values, int count, double height, double shift, int offset, int stride);\ntemplate IMPLOT_API void PlotBarsH<ImU64>(const char* label_id, const ImU64* values, int count, double height, double shift, int offset, int stride);\ntemplate IMPLOT_API void PlotBarsH<float>(const char* label_id, const float* values, int count, double height, double shift, int offset, int stride);\ntemplate IMPLOT_API void PlotBarsH<double>(const char* label_id, const double* values, int count, double height, double shift, int offset, int stride);\n\ntemplate <typename T>\nvoid PlotBarsH(const char* label_id, const T* xs, const T* ys, int count, double height, int offset, int stride) {\n    GetterXY<GetterIdx<T>,GetterIdx<T>> getter1(GetterIdx<T>(xs,count,offset,stride),GetterIdx<T>(ys,count,offset,stride),count);\n    GetterXY<GetterRef,   GetterIdx<T>> getter2(GetterRef(0),GetterIdx<T>(ys,count,offset,stride),count);\n    PlotBarsHEx(label_id, getter1, getter2, height);\n}\n\ntemplate IMPLOT_API void PlotBarsH<ImS8>(const char* label_id, const ImS8* xs, const ImS8* ys, int count, double height, int offset, int stride);\ntemplate IMPLOT_API void PlotBarsH<ImU8>(const char* label_id, const ImU8* xs, const ImU8* ys, int count, double height, int offset, int stride);\ntemplate IMPLOT_API void PlotBarsH<ImS16>(const char* label_id, const ImS16* xs, const ImS16* ys, int count, double height, int offset, int stride);\ntemplate IMPLOT_API void PlotBarsH<ImU16>(const char* label_id, const ImU16* xs, const ImU16* ys, int count, double height, int offset, int stride);\ntemplate IMPLOT_API void PlotBarsH<ImS32>(const char* label_id, const ImS32* xs, const ImS32* ys, int count, double height, int offset, int stride);\ntemplate IMPLOT_API void PlotBarsH<ImU32>(const char* label_id, const ImU32* xs, const ImU32* ys, int count, double height, int offset, int stride);\ntemplate IMPLOT_API void PlotBarsH<ImS64>(const char* label_id, const ImS64* xs, const ImS64* ys, int count, double height, int offset, int stride);\ntemplate IMPLOT_API void PlotBarsH<ImU64>(const char* label_id, const ImU64* xs, const ImU64* ys, int count, double height, int offset, int stride);\ntemplate IMPLOT_API void PlotBarsH<float>(const char* label_id, const float* xs, const float* ys, int count, double height, int offset, int stride);\ntemplate IMPLOT_API void PlotBarsH<double>(const char* label_id, const double* xs, const double* ys, int count, double height, int offset, int stride);\n\n// custom\nvoid PlotBarsHG(const char* label_id, ImPlotGetter getter_func, void* data, int count, double height) {\n    GetterFuncPtr getter1(getter_func, data, count);\n    GetterOverrideX<GetterFuncPtr> getter2(getter1,0);\n    PlotBarsHEx(label_id, getter1, getter2, height);\n}\n\n//-----------------------------------------------------------------------------\n// PLOT BAR GROUPS\n//-----------------------------------------------------------------------------\n\ntemplate <typename T>\nvoid PlotBarGroups(const char* const label_ids[], const T* values, int items, int groups, double width, double shift, ImPlotBarGroupsFlags flags) {\n    if (ImHasFlag(flags, ImPlotBarGroupsFlags_Stacked)) {\n        SetupLock();\n        GImPlot->TempDouble1.resize(4*groups);\n        double* temp = GImPlot->TempDouble1.Data;\n        double* neg =      &temp[0];\n        double* pos =      &temp[groups];\n        double* curr_min = &temp[groups*2];\n        double* curr_max = &temp[groups*3];\n        for (int g = 0; g < groups*2; ++g)\n            temp[g] = 0;\n        for (int i = 0; i < items; ++i) {\n            if (!IsItemHidden(label_ids[i])) {\n                for (int g = 0; g < groups; ++g) {\n                    double v = (double)values[i*groups+g];\n                    if (v > 0) {\n                        curr_min[g] = pos[g];\n                        curr_max[g] = curr_min[g] + v;\n                        pos[g]      += v;\n                    }\n                    else {\n                        curr_max[g] = neg[g];\n                        curr_min[g] = curr_max[g] + v;\n                        neg[g]      += v;\n                    }\n                }\n            }\n            GetterXY<GetterLin,GetterIdx<double>> getter1(GetterLin(1.0,shift),GetterIdx<double>(curr_min,groups),groups);\n            GetterXY<GetterLin,GetterIdx<double>> getter2(GetterLin(1.0,shift),GetterIdx<double>(curr_max,groups),groups);\n            PlotBarsEx(label_ids[i],getter1,getter2,width);\n        }\n    }\n    else {\n        const double subwidth = width / items;\n        for (int i = 0; i < items; ++i) {\n            const double subshift = (i+0.5)*subwidth - width/2;\n            PlotBars(label_ids[i],&values[i*groups],groups,subwidth,subshift+shift);\n        }\n    }\n}\n\ntemplate IMPLOT_API void PlotBarGroups<ImS8>(const char* const label_ids[], const ImS8* values, int items, int groups, double width, double shift, ImPlotBarGroupsFlags flags);\ntemplate IMPLOT_API void PlotBarGroups<ImU8>(const char* const label_ids[], const ImU8* values, int items, int groups, double width, double shift, ImPlotBarGroupsFlags flags);\ntemplate IMPLOT_API void PlotBarGroups<ImS16>(const char* const label_ids[], const ImS16* values, int items, int groups, double width, double shift, ImPlotBarGroupsFlags flags);\ntemplate IMPLOT_API void PlotBarGroups<ImU16>(const char* const label_ids[], const ImU16* values, int items, int groups, double width, double shift, ImPlotBarGroupsFlags flags);\ntemplate IMPLOT_API void PlotBarGroups<ImS32>(const char* const label_ids[], const ImS32* values, int items, int groups, double width, double shift, ImPlotBarGroupsFlags flags);\ntemplate IMPLOT_API void PlotBarGroups<ImU32>(const char* const label_ids[], const ImU32* values, int items, int groups, double width, double shift, ImPlotBarGroupsFlags flags);\ntemplate IMPLOT_API void PlotBarGroups<ImS64>(const char* const label_ids[], const ImS64* values, int items, int groups, double width, double shift, ImPlotBarGroupsFlags flags);\ntemplate IMPLOT_API void PlotBarGroups<ImU64>(const char* const label_ids[], const ImU64* values, int items, int groups, double width, double shift, ImPlotBarGroupsFlags flags);\ntemplate IMPLOT_API void PlotBarGroups<float>(const char* const label_ids[], const float* values, int items, int groups, double width, double shift, ImPlotBarGroupsFlags flags);\ntemplate IMPLOT_API void PlotBarGroups<double>(const char* const label_ids[], const double* values, int items, int groups, double width, double shift, ImPlotBarGroupsFlags flags);\n\ntemplate <typename T>\nvoid PlotBarGroupsH(const char* const label_ids[], const T* values, int items, int groups, double height, double shift, ImPlotBarGroupsFlags flags) {\n    if (ImHasFlag(flags, ImPlotBarGroupsFlags_Stacked)) {\n        SetupLock();\n        GImPlot->TempDouble1.resize(4*groups);\n        double* temp = GImPlot->TempDouble1.Data;\n        double* neg =      &temp[0];\n        double* pos =      &temp[groups];\n        double* curr_min = &temp[groups*2];\n        double* curr_max = &temp[groups*3];\n        for (int g = 0; g < groups*2; ++g)\n            temp[g] = 0;\n        for (int i = 0; i < items; ++i) {\n            if (!IsItemHidden(label_ids[i])) {\n                for (int g = 0; g < groups; ++g) {\n                    double v = (double)values[i*groups+g];\n                    if (v > 0) {\n                        curr_min[g] = pos[g];\n                        curr_max[g] = curr_min[g] + v;\n                        pos[g]      += v;\n                    }\n                    else {\n                        curr_max[g] = neg[g];\n                        curr_min[g] = curr_max[g] + v;\n                        neg[g]      += v;\n                    }\n                }\n            }\n            GetterXY<GetterIdx<double>,GetterLin> getter1(GetterIdx<double>(curr_min,groups),GetterLin(1.0,shift),groups);\n            GetterXY<GetterIdx<double>,GetterLin> getter2(GetterIdx<double>(curr_max,groups),GetterLin(1.0,shift),groups);\n            PlotBarsHEx(label_ids[i],getter1,getter2,height);\n        }\n    }\n    else {\n        const double subheight = height / items;\n        for (int i = 0; i < items; ++i) {\n            const double subshift = (i+0.5)*subheight - height/2;\n            PlotBarsH(label_ids[i],&values[i*groups],groups,subheight,subshift+shift);\n        }\n    }\n}\n\ntemplate IMPLOT_API void PlotBarGroupsH<ImS8>(const char* const label_ids[], const ImS8* values, int items, int groups, double width, double shift, ImPlotBarGroupsFlags flags);\ntemplate IMPLOT_API void PlotBarGroupsH<ImU8>(const char* const label_ids[], const ImU8* values, int items, int groups, double width, double shift, ImPlotBarGroupsFlags flags);\ntemplate IMPLOT_API void PlotBarGroupsH<ImS16>(const char* const label_ids[], const ImS16* values, int items, int groups, double width, double shift, ImPlotBarGroupsFlags flags);\ntemplate IMPLOT_API void PlotBarGroupsH<ImU16>(const char* const label_ids[], const ImU16* values, int items, int groups, double width, double shift, ImPlotBarGroupsFlags flags);\ntemplate IMPLOT_API void PlotBarGroupsH<ImS32>(const char* const label_ids[], const ImS32* values, int items, int groups, double width, double shift, ImPlotBarGroupsFlags flags);\ntemplate IMPLOT_API void PlotBarGroupsH<ImU32>(const char* const label_ids[], const ImU32* values, int items, int groups, double width, double shift, ImPlotBarGroupsFlags flags);\ntemplate IMPLOT_API void PlotBarGroupsH<ImS64>(const char* const label_ids[], const ImS64* values, int items, int groups, double width, double shift, ImPlotBarGroupsFlags flags);\ntemplate IMPLOT_API void PlotBarGroupsH<ImU64>(const char* const label_ids[], const ImU64* values, int items, int groups, double width, double shift, ImPlotBarGroupsFlags flags);\ntemplate IMPLOT_API void PlotBarGroupsH<float>(const char* const label_ids[], const float* values, int items, int groups, double width, double shift, ImPlotBarGroupsFlags flags);\ntemplate IMPLOT_API void PlotBarGroupsH<double>(const char* const label_ids[], const double* values, int items, int groups, double width, double shift, ImPlotBarGroupsFlags flags);\n\n//-----------------------------------------------------------------------------\n// PLOT ERROR BARS\n//-----------------------------------------------------------------------------\n\ntemplate <typename Getter>\nvoid PlotErrorBarsEx(const char* label_id, const Getter& getter) {\n    if (BeginItem(label_id)) {\n        if (FitThisFrame()) {\n            for (int i = 0; i < getter.Count; ++i) {\n                ImPlotPointError e = getter(i);\n                FitPoint(ImPlotPoint(e.X , e.Y - e.Neg));\n                FitPoint(ImPlotPoint(e.X , e.Y + e.Pos ));\n            }\n        }\n        const ImPlotNextItemData& s = GetItemData();\n        ImDrawList& DrawList = *GetPlotDrawList();\n        const ImU32 col = ImGui::GetColorU32(s.Colors[ImPlotCol_ErrorBar]);\n        const bool rend_whisker  = s.ErrorBarSize > 0;\n        const float half_whisker = s.ErrorBarSize * 0.5f;\n        for (int i = 0; i < getter.Count; ++i) {\n            ImPlotPointError e = getter(i);\n            ImVec2 p1 = PlotToPixels(e.X, e.Y - e.Neg,IMPLOT_AUTO,IMPLOT_AUTO);\n            ImVec2 p2 = PlotToPixels(e.X, e.Y + e.Pos,IMPLOT_AUTO,IMPLOT_AUTO);\n            DrawList.AddLine(p1,p2,col, s.ErrorBarWeight);\n            if (rend_whisker) {\n                DrawList.AddLine(p1 - ImVec2(half_whisker, 0), p1 + ImVec2(half_whisker, 0), col, s.ErrorBarWeight);\n                DrawList.AddLine(p2 - ImVec2(half_whisker, 0), p2 + ImVec2(half_whisker, 0), col, s.ErrorBarWeight);\n            }\n        }\n        EndItem();\n    }\n}\n\ntemplate <typename T>\nvoid PlotErrorBars(const char* label_id, const T* xs, const T* ys, const T* err, int count, int offset, int stride) {\n    GetterError<T> getter(xs, ys, err, err, count, offset, stride);\n    PlotErrorBarsEx(label_id, getter);\n}\n\ntemplate IMPLOT_API void PlotErrorBars<ImS8>(const char* label_id, const ImS8* xs, const ImS8* ys, const ImS8* err, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotErrorBars<ImU8>(const char* label_id, const ImU8* xs, const ImU8* ys, const ImU8* err, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotErrorBars<ImS16>(const char* label_id, const ImS16* xs, const ImS16* ys, const ImS16* err, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotErrorBars<ImU16>(const char* label_id, const ImU16* xs, const ImU16* ys, const ImU16* err, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotErrorBars<ImS32>(const char* label_id, const ImS32* xs, const ImS32* ys, const ImS32* err, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotErrorBars<ImU32>(const char* label_id, const ImU32* xs, const ImU32* ys, const ImU32* err, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotErrorBars<ImS64>(const char* label_id, const ImS64* xs, const ImS64* ys, const ImS64* err, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotErrorBars<ImU64>(const char* label_id, const ImU64* xs, const ImU64* ys, const ImU64* err, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotErrorBars<float>(const char* label_id, const float* xs, const float* ys, const float* err, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotErrorBars<double>(const char* label_id, const double* xs, const double* ys, const double* err, int count, int offset, int stride);\n\ntemplate <typename T>\nvoid PlotErrorBars(const char* label_id, const T* xs, const T* ys, const T* neg, const T* pos, int count, int offset, int stride) {\n    GetterError<T> getter(xs, ys, neg, pos, count, offset, stride);\n    PlotErrorBarsEx(label_id, getter);\n}\n\ntemplate IMPLOT_API void PlotErrorBars<ImS8>(const char* label_id, const ImS8* xs, const ImS8* ys, const ImS8* neg, const ImS8* pos, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotErrorBars<ImU8>(const char* label_id, const ImU8* xs, const ImU8* ys, const ImU8* neg, const ImU8* pos, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotErrorBars<ImS16>(const char* label_id, const ImS16* xs, const ImS16* ys, const ImS16* neg, const ImS16* pos, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotErrorBars<ImU16>(const char* label_id, const ImU16* xs, const ImU16* ys, const ImU16* neg, const ImU16* pos, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotErrorBars<ImS32>(const char* label_id, const ImS32* xs, const ImS32* ys, const ImS32* neg, const ImS32* pos, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotErrorBars<ImU32>(const char* label_id, const ImU32* xs, const ImU32* ys, const ImU32* neg, const ImU32* pos, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotErrorBars<ImS64>(const char* label_id, const ImS64* xs, const ImS64* ys, const ImS64* neg, const ImS64* pos, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotErrorBars<ImU64>(const char* label_id, const ImU64* xs, const ImU64* ys, const ImU64* neg, const ImU64* pos, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotErrorBars<float>(const char* label_id, const float* xs, const float* ys, const float* neg, const float* pos, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotErrorBars<double>(const char* label_id, const double* xs, const double* ys, const double* neg, const double* pos, int count, int offset, int stride);\n\n//-----------------------------------------------------------------------------\n// PLOT ERROR BARS H\n//-----------------------------------------------------------------------------\n\ntemplate <typename Getter>\nvoid PlotErrorBarsHEx(const char* label_id, const Getter& getter) {\n    if (BeginItem(label_id)) {\n        if (FitThisFrame()) {\n            for (int i = 0; i < getter.Count; ++i) {\n                ImPlotPointError e = getter(i);\n                FitPoint(ImPlotPoint(e.X - e.Neg, e.Y));\n                FitPoint(ImPlotPoint(e.X + e.Pos, e.Y));\n            }\n        }\n        const ImPlotNextItemData& s = GetItemData();\n        ImDrawList& DrawList = *GetPlotDrawList();\n        const ImU32 col = ImGui::GetColorU32(s.Colors[ImPlotCol_ErrorBar]);\n        const bool rend_whisker  = s.ErrorBarSize > 0;\n        const float half_whisker = s.ErrorBarSize * 0.5f;\n        for (int i = 0; i < getter.Count; ++i) {\n            ImPlotPointError e = getter(i);\n            ImVec2 p1 = PlotToPixels(e.X - e.Neg, e.Y,IMPLOT_AUTO,IMPLOT_AUTO);\n            ImVec2 p2 = PlotToPixels(e.X + e.Pos, e.Y,IMPLOT_AUTO,IMPLOT_AUTO);\n            DrawList.AddLine(p1, p2, col, s.ErrorBarWeight);\n            if (rend_whisker) {\n                DrawList.AddLine(p1 - ImVec2(0, half_whisker), p1 + ImVec2(0, half_whisker), col, s.ErrorBarWeight);\n                DrawList.AddLine(p2 - ImVec2(0, half_whisker), p2 + ImVec2(0, half_whisker), col, s.ErrorBarWeight);\n            }\n        }\n        EndItem();\n    }\n}\n\ntemplate <typename T>\nvoid PlotErrorBarsH(const char* label_id, const T* xs, const T* ys, const T* err, int count, int offset, int stride) {\n    GetterError<T> getter(xs, ys, err, err, count, offset, stride);\n    PlotErrorBarsHEx(label_id, getter);\n}\n\ntemplate IMPLOT_API void PlotErrorBarsH<ImS8>(const char* label_id, const ImS8* xs, const ImS8* ys, const ImS8* err, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotErrorBarsH<ImU8>(const char* label_id, const ImU8* xs, const ImU8* ys, const ImU8* err, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotErrorBarsH<ImS16>(const char* label_id, const ImS16* xs, const ImS16* ys, const ImS16* err, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotErrorBarsH<ImU16>(const char* label_id, const ImU16* xs, const ImU16* ys, const ImU16* err, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotErrorBarsH<ImS32>(const char* label_id, const ImS32* xs, const ImS32* ys, const ImS32* err, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotErrorBarsH<ImU32>(const char* label_id, const ImU32* xs, const ImU32* ys, const ImU32* err, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotErrorBarsH<ImS64>(const char* label_id, const ImS64* xs, const ImS64* ys, const ImS64* err, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotErrorBarsH<ImU64>(const char* label_id, const ImU64* xs, const ImU64* ys, const ImU64* err, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotErrorBarsH<float>(const char* label_id, const float* xs, const float* ys, const float* err, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotErrorBarsH<double>(const char* label_id, const double* xs, const double* ys, const double* err, int count, int offset, int stride);\n\ntemplate <typename T>\nvoid PlotErrorBarsH(const char* label_id, const T* xs, const T* ys, const T* neg, const T* pos, int count, int offset, int stride) {\n    GetterError<T> getter(xs, ys, neg, pos, count, offset, stride);\n    PlotErrorBarsHEx(label_id, getter);\n}\n\ntemplate IMPLOT_API void PlotErrorBarsH<ImS8>(const char* label_id, const ImS8* xs, const ImS8* ys, const ImS8* neg, const ImS8* pos, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotErrorBarsH<ImU8>(const char* label_id, const ImU8* xs, const ImU8* ys, const ImU8* neg, const ImU8* pos, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotErrorBarsH<ImS16>(const char* label_id, const ImS16* xs, const ImS16* ys, const ImS16* neg, const ImS16* pos, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotErrorBarsH<ImU16>(const char* label_id, const ImU16* xs, const ImU16* ys, const ImU16* neg, const ImU16* pos, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotErrorBarsH<ImS32>(const char* label_id, const ImS32* xs, const ImS32* ys, const ImS32* neg, const ImS32* pos, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotErrorBarsH<ImU32>(const char* label_id, const ImU32* xs, const ImU32* ys, const ImU32* neg, const ImU32* pos, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotErrorBarsH<ImS64>(const char* label_id, const ImS64* xs, const ImS64* ys, const ImS64* neg, const ImS64* pos, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotErrorBarsH<ImU64>(const char* label_id, const ImU64* xs, const ImU64* ys, const ImU64* neg, const ImU64* pos, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotErrorBarsH<float>(const char* label_id, const float* xs, const float* ys, const float* neg, const float* pos, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotErrorBarsH<double>(const char* label_id, const double* xs, const double* ys, const double* neg, const double* pos, int count, int offset, int stride);\n\n//-----------------------------------------------------------------------------\n// PLOT STEMS\n//-----------------------------------------------------------------------------\n\ntemplate <typename GetterM, typename GetterB>\nIMPLOT_INLINE void PlotStemsEx(const char* label_id, const GetterM& get_mark, const GetterB& get_base) {\n    if (BeginItem(label_id, ImPlotCol_Line)) {\n        if (FitThisFrame()) {\n            for (int i = 0; i < get_base.Count; ++i) {\n                FitPoint(get_mark(i));\n                FitPoint(get_base(i));\n            }\n        }\n        const ImPlotNextItemData& s = GetItemData();\n        ImDrawList& DrawList = *GetPlotDrawList();\n        // render stems\n        if (s.RenderLine) {\n            const ImU32 col_line = ImGui::GetColorU32(s.Colors[ImPlotCol_Line]);\n            switch (GetCurrentScale()) {\n                case ImPlotScale_LinLin: RenderLineSegments(get_mark, get_base, TransformerLinLin(), DrawList, s.LineWeight, col_line); break;\n                case ImPlotScale_LogLin: RenderLineSegments(get_mark, get_base, TransformerLogLin(), DrawList, s.LineWeight, col_line); break;\n                case ImPlotScale_LinLog: RenderLineSegments(get_mark, get_base, TransformerLinLog(), DrawList, s.LineWeight, col_line); break;\n                case ImPlotScale_LogLog: RenderLineSegments(get_mark, get_base, TransformerLogLog(), DrawList, s.LineWeight, col_line); break;\n            }\n        }\n        // render markers\n        ImPlotMarker marker = s.Marker == ImPlotMarker_None ? ImPlotMarker_Circle : s.Marker;\n        if (marker != ImPlotMarker_None) {\n            PopPlotClipRect();\n            PushPlotClipRect(s.MarkerSize);\n            const ImU32 col_line = ImGui::GetColorU32(s.Colors[ImPlotCol_MarkerOutline]);\n            const ImU32 col_fill = ImGui::GetColorU32(s.Colors[ImPlotCol_MarkerFill]);\n            switch (GetCurrentScale()) {\n                case ImPlotScale_LinLin: RenderMarkers(get_mark, TransformerLinLin(), DrawList, marker, s.MarkerSize, s.RenderMarkerLine, col_line, s.MarkerWeight, s.RenderMarkerFill, col_fill); break;\n                case ImPlotScale_LogLin: RenderMarkers(get_mark, TransformerLogLin(), DrawList, marker, s.MarkerSize, s.RenderMarkerLine, col_line, s.MarkerWeight, s.RenderMarkerFill, col_fill); break;\n                case ImPlotScale_LinLog: RenderMarkers(get_mark, TransformerLinLog(), DrawList, marker, s.MarkerSize, s.RenderMarkerLine, col_line, s.MarkerWeight, s.RenderMarkerFill, col_fill); break;\n                case ImPlotScale_LogLog: RenderMarkers(get_mark, TransformerLogLog(), DrawList, marker, s.MarkerSize, s.RenderMarkerLine, col_line, s.MarkerWeight, s.RenderMarkerFill, col_fill); break;\n            }\n        }\n        EndItem();\n    }\n}\n\ntemplate <typename T>\nvoid PlotStems(const char* label_id, const T* values, int count, double y_ref, double xscale, double x0, int offset, int stride) {\n    GetterXY<GetterLin,GetterIdx<T>> get_mark(GetterLin(xscale,x0),GetterIdx<T>(values,count,offset,stride),count);\n    GetterXY<GetterLin,GetterRef>    get_base(GetterLin(xscale,x0),GetterRef(y_ref),count);\n    PlotStemsEx(label_id, get_mark, get_base);\n}\n\ntemplate IMPLOT_API void PlotStems<ImS8>(const char* label_id, const ImS8* values, int count, double y_ref, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotStems<ImU8>(const char* label_id, const ImU8* values, int count, double y_ref, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotStems<ImS16>(const char* label_id, const ImS16* values, int count, double y_ref, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotStems<ImU16>(const char* label_id, const ImU16* values, int count, double y_ref, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotStems<ImS32>(const char* label_id, const ImS32* values, int count, double y_ref, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotStems<ImU32>(const char* label_id, const ImU32* values, int count, double y_ref, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotStems<ImS64>(const char* label_id, const ImS64* values, int count, double y_ref, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotStems<ImU64>(const char* label_id, const ImU64* values, int count, double y_ref, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotStems<float>(const char* label_id, const float* values, int count, double y_ref, double xscale, double x0, int offset, int stride);\ntemplate IMPLOT_API void PlotStems<double>(const char* label_id, const double* values, int count, double y_ref, double xscale, double x0, int offset, int stride);\n\ntemplate <typename T>\nvoid PlotStems(const char* label_id, const T* xs, const T* ys, int count, double y_ref, int offset, int stride) {\n    GetterXY<GetterIdx<T>,GetterIdx<T>> get_mark(GetterIdx<T>(xs,count,offset,stride),GetterIdx<T>(ys,count,offset,stride),count);\n    GetterXY<GetterIdx<T>,GetterRef>    get_base(GetterIdx<T>(xs,count,offset,stride),GetterRef(y_ref),count);\n    PlotStemsEx(label_id, get_mark, get_base);\n}\n\ntemplate IMPLOT_API void PlotStems<ImS8>(const char* label_id, const ImS8* xs, const ImS8* ys, int count, double y_ref, int offset, int stride);\ntemplate IMPLOT_API void PlotStems<ImU8>(const char* label_id, const ImU8* xs, const ImU8* ys, int count, double y_ref, int offset, int stride);\ntemplate IMPLOT_API void PlotStems<ImS16>(const char* label_id, const ImS16* xs, const ImS16* ys, int count, double y_ref, int offset, int stride);\ntemplate IMPLOT_API void PlotStems<ImU16>(const char* label_id, const ImU16* xs, const ImU16* ys, int count, double y_ref, int offset, int stride);\ntemplate IMPLOT_API void PlotStems<ImS32>(const char* label_id, const ImS32* xs, const ImS32* ys, int count, double y_ref, int offset, int stride);\ntemplate IMPLOT_API void PlotStems<ImU32>(const char* label_id, const ImU32* xs, const ImU32* ys, int count, double y_ref, int offset, int stride);\ntemplate IMPLOT_API void PlotStems<ImS64>(const char* label_id, const ImS64* xs, const ImS64* ys, int count, double y_ref, int offset, int stride);\ntemplate IMPLOT_API void PlotStems<ImU64>(const char* label_id, const ImU64* xs, const ImU64* ys, int count, double y_ref, int offset, int stride);\ntemplate IMPLOT_API void PlotStems<float>(const char* label_id, const float* xs, const float* ys, int count, double y_ref, int offset, int stride);\ntemplate IMPLOT_API void PlotStems<double>(const char* label_id, const double* xs, const double* ys, int count, double y_ref, int offset, int stride);\n\n//-----------------------------------------------------------------------------\n// INFINITE LINES\n//-----------------------------------------------------------------------------\n\ntemplate <typename T>\nvoid PlotVLines(const char* label_id, const T* xs, int count, int offset, int stride) {\n    if (BeginItem(label_id, ImPlotCol_Line)) {\n        const ImPlotRect lims = GetPlotLimits(IMPLOT_AUTO,IMPLOT_AUTO);\n        GetterXY<GetterIdx<T>,GetterRef> get_min(GetterIdx<T>(xs,count,offset,stride),GetterRef(lims.Y.Min),count);\n        GetterXY<GetterIdx<T>,GetterRef> get_max(GetterIdx<T>(xs,count,offset,stride),GetterRef(lims.Y.Max),count);\n        if (FitThisFrame()) {\n            for (int i = 0; i < get_min.Count; ++i)\n                FitPointX(get_min(i).x);\n        }\n        const ImPlotNextItemData& s = GetItemData();\n        ImDrawList& DrawList = *GetPlotDrawList();\n        // render stems\n        if (s.RenderLine) {\n            const ImU32 col_line = ImGui::GetColorU32(s.Colors[ImPlotCol_Line]);\n            switch (GetCurrentScale()) {\n                case ImPlotScale_LinLin: RenderLineSegments(get_min, get_max, TransformerLinLin(), DrawList, s.LineWeight, col_line); break;\n                case ImPlotScale_LogLin: RenderLineSegments(get_min, get_max, TransformerLogLin(), DrawList, s.LineWeight, col_line); break;\n                case ImPlotScale_LinLog: RenderLineSegments(get_min, get_max, TransformerLinLog(), DrawList, s.LineWeight, col_line); break;\n                case ImPlotScale_LogLog: RenderLineSegments(get_min, get_max, TransformerLogLog(), DrawList, s.LineWeight, col_line); break;\n            }\n        }\n        EndItem();\n    }\n}\n\ntemplate IMPLOT_API void PlotVLines<ImS8>(const char* label_id, const ImS8* xs, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotVLines<ImU8>(const char* label_id, const ImU8* xs, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotVLines<ImS16>(const char* label_id, const ImS16* xs, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotVLines<ImU16>(const char* label_id, const ImU16* xs, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotVLines<ImS32>(const char* label_id, const ImS32* xs, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotVLines<ImU32>(const char* label_id, const ImU32* xs, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotVLines<ImS64>(const char* label_id, const ImS64* xs, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotVLines<ImU64>(const char* label_id, const ImU64* xs, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotVLines<float>(const char* label_id, const float* xs, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotVLines<double>(const char* label_id, const double* xs, int count, int offset, int stride);\n\n\ntemplate <typename T>\nvoid PlotHLines(const char* label_id, const T* ys, int count, int offset, int stride) {\n    if (BeginItem(label_id, ImPlotCol_Line)) {\n        const ImPlotRect lims = GetPlotLimits(IMPLOT_AUTO,IMPLOT_AUTO);\n        GetterXY<GetterRef,GetterIdx<T>> get_min(GetterRef(lims.X.Min),GetterIdx<T>(ys,count,offset,stride),count);\n        GetterXY<GetterRef,GetterIdx<T>> get_max(GetterRef(lims.X.Max),GetterIdx<T>(ys,count,offset,stride),count);\n        if (FitThisFrame()) {\n            for (int i = 0; i < get_min.Count; ++i)\n                FitPointY(get_min(i).y);\n        }\n        const ImPlotNextItemData& s = GetItemData();\n        ImDrawList& DrawList = *GetPlotDrawList();\n        // render stems\n        if (s.RenderLine) {\n            const ImU32 col_line = ImGui::GetColorU32(s.Colors[ImPlotCol_Line]);\n            switch (GetCurrentScale()) {\n                case ImPlotScale_LinLin: RenderLineSegments(get_min, get_max, TransformerLinLin(), DrawList, s.LineWeight, col_line); break;\n                case ImPlotScale_LogLin: RenderLineSegments(get_min, get_max, TransformerLogLin(), DrawList, s.LineWeight, col_line); break;\n                case ImPlotScale_LinLog: RenderLineSegments(get_min, get_max, TransformerLinLog(), DrawList, s.LineWeight, col_line); break;\n                case ImPlotScale_LogLog: RenderLineSegments(get_min, get_max, TransformerLogLog(), DrawList, s.LineWeight, col_line); break;\n            }\n        }\n        EndItem();\n    }\n}\n\ntemplate IMPLOT_API void PlotHLines<ImS8>(const char* label_id, const ImS8* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotHLines<ImU8>(const char* label_id, const ImU8* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotHLines<ImS16>(const char* label_id, const ImS16* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotHLines<ImU16>(const char* label_id, const ImU16* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotHLines<ImS32>(const char* label_id, const ImS32* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotHLines<ImU32>(const char* label_id, const ImU32* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotHLines<ImS64>(const char* label_id, const ImS64* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotHLines<ImU64>(const char* label_id, const ImU64* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotHLines<float>(const char* label_id, const float* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotHLines<double>(const char* label_id, const double* ys, int count, int offset, int stride);\n\n//-----------------------------------------------------------------------------\n// PLOT PIE CHART\n//-----------------------------------------------------------------------------\n\nIMPLOT_INLINE void RenderPieSlice(ImDrawList& DrawList, const ImPlotPoint& center, double radius, double a0, double a1, ImU32 col) {\n    static const float resolution = 50 / (2 * IM_PI);\n    static ImVec2 buffer[50];\n    buffer[0] = PlotToPixels(center,IMPLOT_AUTO,IMPLOT_AUTO);\n    int n = ImMax(3, (int)((a1 - a0) * resolution));\n    double da = (a1 - a0) / (n - 1);\n    for (int i = 0; i < n; ++i) {\n        double a = a0 + i * da;\n        buffer[i + 1] = PlotToPixels(center.x + radius * cos(a), center.y + radius * sin(a),IMPLOT_AUTO,IMPLOT_AUTO);\n    }\n    DrawList.AddConvexPolyFilled(buffer, n + 1, col);\n}\n\ntemplate <typename T>\nvoid PlotPieChart(const char* const label_ids[], const T* values, int count, double x, double y, double radius, bool normalize, const char* fmt, double angle0) {\n    IM_ASSERT_USER_ERROR(GImPlot->CurrentPlot != NULL, \"PlotPieChart() needs to be called between BeginPlot() and EndPlot()!\");\n    ImDrawList & DrawList = *GetPlotDrawList();\n    double sum = 0;\n    for (int i = 0; i < count; ++i)\n        sum += (double)values[i];\n    normalize = normalize || sum > 1.0;\n    ImPlotPoint center(x,y);\n    PushPlotClipRect();\n    double a0 = angle0 * 2 * IM_PI / 360.0;\n    double a1 = angle0 * 2 * IM_PI / 360.0;\n    for (int i = 0; i < count; ++i) {\n        double percent = normalize ? (double)values[i] / sum : (double)values[i];\n        a1 = a0 + 2 * IM_PI * percent;\n        if (BeginItem(label_ids[i])) {\n            if (FitThisFrame()) {\n                FitPoint(ImPlotPoint(x-radius,y-radius));\n                FitPoint(ImPlotPoint(x+radius,y+radius));\n            }\n            ImU32 col = GetCurrentItem()->Color;\n            if (percent < 0.5) {\n                RenderPieSlice(DrawList, center, radius, a0, a1, col);\n            }\n            else  {\n                RenderPieSlice(DrawList, center, radius, a0, a0 + (a1 - a0) * 0.5, col);\n                RenderPieSlice(DrawList, center, radius, a0 + (a1 - a0) * 0.5, a1, col);\n            }\n            EndItem();\n        }\n        a0 = a1;\n    }\n    if (fmt != NULL) {\n        a0 = angle0 * 2 * IM_PI / 360.0;\n        a1 = angle0 * 2 * IM_PI / 360.0;\n        char buffer[32];\n        for (int i = 0; i < count; ++i) {\n            ImPlotItem* item = GetItem(label_ids[i]);\n            double percent = normalize ? (double)values[i] / sum : (double)values[i];\n            a1 = a0 + 2 * IM_PI * percent;\n            if (item->Show) {\n                ImFormatString(buffer, 32, fmt, (double)values[i]);\n                ImVec2 size = ImGui::CalcTextSize(buffer);\n                double angle = a0 + (a1 - a0) * 0.5;\n                ImVec2 pos = PlotToPixels(center.x + 0.5 * radius * cos(angle), center.y + 0.5 * radius * sin(angle),IMPLOT_AUTO,IMPLOT_AUTO);\n                ImU32 col  = CalcTextColor(ImGui::ColorConvertU32ToFloat4(item->Color));\n                DrawList.AddText(pos - size * 0.5f, col, buffer);\n            }\n            a0 = a1;\n        }\n    }\n    PopPlotClipRect();\n}\n\ntemplate IMPLOT_API void PlotPieChart<ImS8>(const char* const label_ids[], const ImS8* values, int count, double x, double y, double radius, bool normalize, const char* fmt, double angle0);\ntemplate IMPLOT_API void PlotPieChart<ImU8>(const char* const label_ids[], const ImU8* values, int count, double x, double y, double radius, bool normalize, const char* fmt, double angle0);\ntemplate IMPLOT_API void PlotPieChart<ImS16>(const char* const label_ids[], const ImS16* values, int count, double x, double y, double radius, bool normalize, const char* fmt, double angle0);\ntemplate IMPLOT_API void PlotPieChart<ImU16>(const char* const label_ids[], const ImU16* values, int count, double x, double y, double radius, bool normalize, const char* fmt, double angle0);\ntemplate IMPLOT_API void PlotPieChart<ImS32>(const char* const label_ids[], const ImS32* values, int count, double x, double y, double radius, bool normalize, const char* fmt, double angle0);\ntemplate IMPLOT_API void PlotPieChart<ImU32>(const char* const label_ids[], const ImU32* values, int count, double x, double y, double radius, bool normalize, const char* fmt, double angle0);\ntemplate IMPLOT_API void PlotPieChart<ImS64>(const char* const label_ids[], const ImS64* values, int count, double x, double y, double radius, bool normalize, const char* fmt, double angle0);\ntemplate IMPLOT_API void PlotPieChart<ImU64>(const char* const label_ids[], const ImU64* values, int count, double x, double y, double radius, bool normalize, const char* fmt, double angle0);\ntemplate IMPLOT_API void PlotPieChart<float>(const char* const label_ids[], const float* values, int count, double x, double y, double radius, bool normalize, const char* fmt, double angle0);\ntemplate IMPLOT_API void PlotPieChart<double>(const char* const label_ids[], const double* values, int count, double x, double y, double radius, bool normalize, const char* fmt, double angle0);\n\n//-----------------------------------------------------------------------------\n// PLOT HEATMAP\n//-----------------------------------------------------------------------------\n\nstruct RectInfo {\n    ImPlotPoint Min, Max;\n    ImU32 Color;\n};\n\ntemplate <typename TGetter, typename TTransformer>\nstruct RectRenderer {\n    IMPLOT_INLINE RectRenderer(const TGetter& getter, const TTransformer& transformer) :\n        Getter(getter),\n        Transformer(transformer),\n        Prims(Getter.Count)\n    {}\n    IMPLOT_INLINE bool operator()(ImDrawList& DrawList, const ImRect& cull_rect, const ImVec2& uv, int prim) const {\n        RectInfo rect = Getter(prim);\n        ImVec2 P1 = Transformer(rect.Min);\n        ImVec2 P2 = Transformer(rect.Max);\n\n        if ((rect.Color & IM_COL32_A_MASK) == 0 || !cull_rect.Overlaps(ImRect(ImMin(P1, P2), ImMax(P1, P2))))\n            return false;\n\n        DrawList._VtxWritePtr[0].pos   = P1;\n        DrawList._VtxWritePtr[0].uv    = uv;\n        DrawList._VtxWritePtr[0].col   = rect.Color;\n        DrawList._VtxWritePtr[1].pos.x = P1.x;\n        DrawList._VtxWritePtr[1].pos.y = P2.y;\n        DrawList._VtxWritePtr[1].uv    = uv;\n        DrawList._VtxWritePtr[1].col   = rect.Color;\n        DrawList._VtxWritePtr[2].pos   = P2;\n        DrawList._VtxWritePtr[2].uv    = uv;\n        DrawList._VtxWritePtr[2].col   = rect.Color;\n        DrawList._VtxWritePtr[3].pos.x = P2.x;\n        DrawList._VtxWritePtr[3].pos.y = P1.y;\n        DrawList._VtxWritePtr[3].uv    = uv;\n        DrawList._VtxWritePtr[3].col   = rect.Color;\n        DrawList._VtxWritePtr += 4;\n        DrawList._IdxWritePtr[0] = (ImDrawIdx)(DrawList._VtxCurrentIdx);\n        DrawList._IdxWritePtr[1] = (ImDrawIdx)(DrawList._VtxCurrentIdx + 1);\n        DrawList._IdxWritePtr[2] = (ImDrawIdx)(DrawList._VtxCurrentIdx + 3);\n        DrawList._IdxWritePtr[3] = (ImDrawIdx)(DrawList._VtxCurrentIdx + 1);\n        DrawList._IdxWritePtr[4] = (ImDrawIdx)(DrawList._VtxCurrentIdx + 2);\n        DrawList._IdxWritePtr[5] = (ImDrawIdx)(DrawList._VtxCurrentIdx + 3);\n        DrawList._IdxWritePtr   += 6;\n        DrawList._VtxCurrentIdx += 4;\n        return true;\n    }\n    const TGetter& Getter;\n    const TTransformer& Transformer;\n    const int Prims;\n    static const int IdxConsumed = 6;\n    static const int VtxConsumed = 4;\n};\n\ntemplate <typename T>\nstruct GetterHeatmap {\n    GetterHeatmap(const T* values, int rows, int cols, double scale_min, double scale_max, double width, double height, double xref, double yref, double ydir) :\n        Values(values),\n        Count(rows*cols),\n        Rows(rows),\n        Cols(cols),\n        ScaleMin(scale_min),\n        ScaleMax(scale_max),\n        Width(width),\n        Height(height),\n        XRef(xref),\n        YRef(yref),\n        YDir(ydir),\n        HalfSize(Width*0.5, Height*0.5)\n    { }\n\n    template <typename I> IMPLOT_INLINE RectInfo operator()(I idx) const {\n        double val = (double)Values[idx];\n        const int r = idx / Cols;\n        const int c = idx % Cols;\n        const ImPlotPoint p(XRef + HalfSize.x + c*Width, YRef + YDir * (HalfSize.y + r*Height));\n        RectInfo rect;\n        rect.Min.x = p.x - HalfSize.x;\n        rect.Min.y = p.y - HalfSize.y;\n        rect.Max.x = p.x + HalfSize.x;\n        rect.Max.y = p.y + HalfSize.y;\n        const float t = ImClamp((float)ImRemap01(val, ScaleMin, ScaleMax),0.0f,1.0f);\n        rect.Color = GImPlot->ColormapData.LerpTable(GImPlot->Style.Colormap, t);\n        return rect;\n    }\n    const T* const Values;\n    const int Count, Rows, Cols;\n    const double ScaleMin, ScaleMax, Width, Height, XRef, YRef, YDir;\n    const ImPlotPoint HalfSize;\n};\n\ntemplate <typename T, typename Transformer>\nvoid RenderHeatmap(Transformer transformer, ImDrawList& DrawList, const T* values, int rows, int cols, double scale_min, double scale_max, const char* fmt, const ImPlotPoint& bounds_min, const ImPlotPoint& bounds_max, bool reverse_y) {\n    ImPlotContext& gp = *GImPlot;\n    if (scale_min == 0 && scale_max == 0) {\n        T temp_min, temp_max;\n        ImMinMaxArray(values,rows*cols,&temp_min,&temp_max);\n        scale_min = (double)temp_min;\n        scale_max = (double)temp_max;\n    }\n    if (scale_min == scale_max) {\n        ImVec2 a = transformer(bounds_min);\n        ImVec2 b = transformer(bounds_max);\n        ImU32  col = GetColormapColorU32(0,gp.Style.Colormap);\n        DrawList.AddRectFilled(a, b, col);\n        return;\n    }\n    const double yref = reverse_y ? bounds_max.y : bounds_min.y;\n    const double ydir = reverse_y ? -1 : 1;\n    GetterHeatmap<T> getter(values, rows, cols, scale_min, scale_max, (bounds_max.x - bounds_min.x) / cols, (bounds_max.y - bounds_min.y) / rows, bounds_min.x, yref, ydir);\n    switch (GetCurrentScale()) {\n        case ImPlotScale_LinLin: RenderPrimitives(RectRenderer<GetterHeatmap<T>, TransformerLinLin>(getter, TransformerLinLin()), DrawList, gp.CurrentPlot->PlotRect); break;\n        case ImPlotScale_LogLin: RenderPrimitives(RectRenderer<GetterHeatmap<T>, TransformerLogLin>(getter, TransformerLogLin()), DrawList, gp.CurrentPlot->PlotRect); break;;\n        case ImPlotScale_LinLog: RenderPrimitives(RectRenderer<GetterHeatmap<T>, TransformerLinLog>(getter, TransformerLinLog()), DrawList, gp.CurrentPlot->PlotRect); break;;\n        case ImPlotScale_LogLog: RenderPrimitives(RectRenderer<GetterHeatmap<T>, TransformerLogLog>(getter, TransformerLogLog()), DrawList, gp.CurrentPlot->PlotRect); break;;\n    }\n    if (fmt != NULL) {\n        const double w = (bounds_max.x - bounds_min.x) / cols;\n        const double h = (bounds_max.y - bounds_min.y) / rows;\n        const ImPlotPoint half_size(w*0.5,h*0.5);\n        int i = 0;\n        for (int r = 0; r < rows; ++r) {\n            for (int c = 0; c < cols; ++c) {\n                ImPlotPoint p;\n                p.x = bounds_min.x + 0.5*w + c*w;\n                p.y = yref + ydir * (0.5*h + r*h);\n                ImVec2 px = transformer(p);\n                char buff[32];\n                ImFormatString(buff, 32, fmt, values[i]);\n                ImVec2 size = ImGui::CalcTextSize(buff);\n                double t = ImClamp(ImRemap01((double)values[i], scale_min, scale_max),0.0,1.0);\n                ImVec4 color = SampleColormap((float)t);\n                ImU32 col = CalcTextColor(color);\n                DrawList.AddText(px - size * 0.5f, col, buff);\n                i++;\n            }\n        }\n    }\n}\n\ntemplate <typename T>\nvoid PlotHeatmap(const char* label_id, const T* values, int rows, int cols, double scale_min, double scale_max, const char* fmt, const ImPlotPoint& bounds_min, const ImPlotPoint& bounds_max) {\n    if (BeginItem(label_id)) {\n        if (FitThisFrame()) {\n            FitPoint(bounds_min);\n            FitPoint(bounds_max);\n        }\n        ImDrawList& DrawList = *GetPlotDrawList();\n        switch (GetCurrentScale()) {\n            case ImPlotScale_LinLin: RenderHeatmap(TransformerLinLin(), DrawList, values, rows, cols, scale_min, scale_max, fmt, bounds_min, bounds_max, true); break;\n            case ImPlotScale_LogLin: RenderHeatmap(TransformerLogLin(), DrawList, values, rows, cols, scale_min, scale_max, fmt, bounds_min, bounds_max, true); break;\n            case ImPlotScale_LinLog: RenderHeatmap(TransformerLinLog(), DrawList, values, rows, cols, scale_min, scale_max, fmt, bounds_min, bounds_max, true); break;\n            case ImPlotScale_LogLog: RenderHeatmap(TransformerLogLog(), DrawList, values, rows, cols, scale_min, scale_max, fmt, bounds_min, bounds_max, true); break;\n        }\n        EndItem();\n    }\n}\n\ntemplate IMPLOT_API void PlotHeatmap<ImS8>(const char* label_id, const ImS8* values, int rows, int cols, double scale_min, double scale_max, const char* fmt, const ImPlotPoint& bounds_min, const ImPlotPoint& bounds_max);\ntemplate IMPLOT_API void PlotHeatmap<ImU8>(const char* label_id, const ImU8* values, int rows, int cols, double scale_min, double scale_max, const char* fmt, const ImPlotPoint& bounds_min, const ImPlotPoint& bounds_max);\ntemplate IMPLOT_API void PlotHeatmap<ImS16>(const char* label_id, const ImS16* values, int rows, int cols, double scale_min, double scale_max, const char* fmt, const ImPlotPoint& bounds_min, const ImPlotPoint& bounds_max);\ntemplate IMPLOT_API void PlotHeatmap<ImU16>(const char* label_id, const ImU16* values, int rows, int cols, double scale_min, double scale_max, const char* fmt, const ImPlotPoint& bounds_min, const ImPlotPoint& bounds_max);\ntemplate IMPLOT_API void PlotHeatmap<ImS32>(const char* label_id, const ImS32* values, int rows, int cols, double scale_min, double scale_max, const char* fmt, const ImPlotPoint& bounds_min, const ImPlotPoint& bounds_max);\ntemplate IMPLOT_API void PlotHeatmap<ImU32>(const char* label_id, const ImU32* values, int rows, int cols, double scale_min, double scale_max, const char* fmt, const ImPlotPoint& bounds_min, const ImPlotPoint& bounds_max);\ntemplate IMPLOT_API void PlotHeatmap<ImS64>(const char* label_id, const ImS64* values, int rows, int cols, double scale_min, double scale_max, const char* fmt, const ImPlotPoint& bounds_min, const ImPlotPoint& bounds_max);\ntemplate IMPLOT_API void PlotHeatmap<ImU64>(const char* label_id, const ImU64* values, int rows, int cols, double scale_min, double scale_max, const char* fmt, const ImPlotPoint& bounds_min, const ImPlotPoint& bounds_max);\ntemplate IMPLOT_API void PlotHeatmap<float>(const char* label_id, const float* values, int rows, int cols, double scale_min, double scale_max, const char* fmt, const ImPlotPoint& bounds_min, const ImPlotPoint& bounds_max);\ntemplate IMPLOT_API void PlotHeatmap<double>(const char* label_id, const double* values, int rows, int cols, double scale_min, double scale_max, const char* fmt, const ImPlotPoint& bounds_min, const ImPlotPoint& bounds_max);\n\n//-----------------------------------------------------------------------------\n// PLOT HISTOGRAM\n//-----------------------------------------------------------------------------\n\ntemplate <typename T>\ndouble PlotHistogram(const char* label_id, const T* values, int count, int bins, bool cumulative, bool density, ImPlotRange range, bool outliers, double bar_scale) {\n\n    if (count <= 0 || bins == 0)\n        return 0;\n\n    if (range.Min == 0 && range.Max == 0) {\n        T Min, Max;\n        ImMinMaxArray(values, count, &Min, &Max);\n        range.Min = (double)Min;\n        range.Max = (double)Max;\n    }\n\n    double width;\n    if (bins < 0)\n        CalculateBins(values, count, bins, range, bins, width);\n    else\n        width = range.Size() / bins;\n\n    ImVector<double>& bin_centers = GImPlot->TempDouble1;\n    ImVector<double>& bin_counts  = GImPlot->TempDouble2;\n    bin_centers.resize(bins);\n    bin_counts.resize(bins);\n    int below = 0;\n\n    for (int b = 0; b < bins; ++b) {\n        bin_centers[b] = range.Min + b * width + width * 0.5;\n        bin_counts[b] = 0;\n    }\n    int counted = 0;\n    double max_count = 0;\n    for (int i = 0; i < count; ++i) {\n        double val = (double)values[i];\n        if (range.Contains(val)) {\n            const int b = ImClamp((int)((val - range.Min) / width), 0, bins - 1);\n            bin_counts[b] += 1.0;\n            if (bin_counts[b] > max_count)\n                max_count = bin_counts[b];\n            counted++;\n        }\n        else if (val < range.Min) {\n            below++;\n        }\n    }\n    if (cumulative && density) {\n        if (outliers)\n            bin_counts[0] += below;\n        for (int b = 1; b < bins; ++b)\n            bin_counts[b] += bin_counts[b-1];\n        double scale = 1.0 / (outliers ? count : counted);\n        for (int b = 0; b < bins; ++b)\n            bin_counts[b] *= scale;\n        max_count = bin_counts[bins-1];\n    }\n    else if (cumulative) {\n        if (outliers)\n            bin_counts[0] += below;\n        for (int b = 1; b < bins; ++b)\n            bin_counts[b] += bin_counts[b-1];\n        max_count = bin_counts[bins-1];\n    }\n    else if (density) {\n        double scale = 1.0 / ((outliers ? count : counted) * width);\n        for (int b = 0; b < bins; ++b)\n            bin_counts[b] *= scale;\n        max_count *= scale;\n    }\n    PlotBars(label_id, &bin_centers.Data[0], &bin_counts.Data[0], bins, bar_scale*width);\n    return max_count;\n}\n\ntemplate IMPLOT_API double PlotHistogram<ImS8>(const char* label_id, const ImS8* values, int count, int bins, bool cumulative, bool density, ImPlotRange range, bool outliers, double bar_scale);\ntemplate IMPLOT_API double PlotHistogram<ImU8>(const char* label_id, const ImU8* values, int count, int bins, bool cumulative, bool density, ImPlotRange range, bool outliers, double bar_scale);\ntemplate IMPLOT_API double PlotHistogram<ImS16>(const char* label_id, const ImS16* values, int count, int bins, bool cumulative, bool density, ImPlotRange range, bool outliers, double bar_scale);\ntemplate IMPLOT_API double PlotHistogram<ImU16>(const char* label_id, const ImU16* values, int count, int bins, bool cumulative, bool density, ImPlotRange range, bool outliers, double bar_scale);\ntemplate IMPLOT_API double PlotHistogram<ImS32>(const char* label_id, const ImS32* values, int count, int bins, bool cumulative, bool density, ImPlotRange range, bool outliers, double bar_scale);\ntemplate IMPLOT_API double PlotHistogram<ImU32>(const char* label_id, const ImU32* values, int count, int bins, bool cumulative, bool density, ImPlotRange range, bool outliers, double bar_scale);\ntemplate IMPLOT_API double PlotHistogram<ImS64>(const char* label_id, const ImS64* values, int count, int bins, bool cumulative, bool density, ImPlotRange range, bool outliers, double bar_scale);\ntemplate IMPLOT_API double PlotHistogram<ImU64>(const char* label_id, const ImU64* values, int count, int bins, bool cumulative, bool density, ImPlotRange range, bool outliers, double bar_scale);\ntemplate IMPLOT_API double PlotHistogram<float>(const char* label_id, const float* values, int count, int bins, bool cumulative, bool density, ImPlotRange range, bool outliers, double bar_scale);\ntemplate IMPLOT_API double PlotHistogram<double>(const char* label_id, const double* values, int count, int bins, bool cumulative, bool density, ImPlotRange range, bool outliers, double bar_scale);\n\n//-----------------------------------------------------------------------------\n// PLOT HISTOGRAM 2D\n//-----------------------------------------------------------------------------\n\ntemplate <typename T>\ndouble PlotHistogram2D(const char* label_id, const T* xs, const T* ys, int count, int x_bins, int y_bins, bool density, ImPlotRect range, bool outliers) {\n\n    if (count <= 0 || x_bins == 0 || y_bins == 0)\n        return 0;\n\n    if (range.X.Min == 0 && range.X.Max == 0) {\n        T Min, Max;\n        ImMinMaxArray(xs, count, &Min, &Max);\n        range.X.Min = (double)Min;\n        range.X.Max = (double)Max;\n    }\n    if (range.Y.Min == 0 && range.Y.Max == 0) {\n        T Min, Max;\n        ImMinMaxArray(ys, count, &Min, &Max);\n        range.Y.Min = (double)Min;\n        range.Y.Max = (double)Max;\n    }\n\n    double width, height;\n    if (x_bins < 0)\n        CalculateBins(xs, count, x_bins, range.X, x_bins, width);\n    else\n        width = range.X.Size() / x_bins;\n    if (y_bins < 0)\n        CalculateBins(ys, count, y_bins, range.Y, y_bins, height);\n    else\n        height = range.Y.Size() / y_bins;\n\n    const int bins = x_bins * y_bins;\n\n    ImVector<double>& bin_counts = GImPlot->TempDouble1;\n    bin_counts.resize(bins);\n\n    for (int b = 0; b < bins; ++b)\n        bin_counts[b] = 0;\n\n    int counted = 0;\n    double max_count = 0;\n    for (int i = 0; i < count; ++i) {\n        if (range.Contains((double)xs[i], (double)ys[i])) {\n            const int xb = ImClamp( (int)((double)(xs[i] - range.X.Min) / width)  , 0, x_bins - 1);\n            const int yb = ImClamp( (int)((double)(ys[i] - range.Y.Min) / height) , 0, y_bins - 1);\n            const int b  = yb * x_bins + xb;\n            bin_counts[b] += 1.0;\n            if (bin_counts[b] > max_count)\n                max_count = bin_counts[b];\n            counted++;\n        }\n    }\n    if (density) {\n        double scale = 1.0 / ((outliers ? count : counted) * width * height);\n        for (int b = 0; b < bins; ++b)\n            bin_counts[b] *= scale;\n        max_count *= scale;\n    }\n\n    if (BeginItem(label_id)) {\n        if (FitThisFrame()) {\n            FitPoint(range.Min());\n            FitPoint(range.Max());\n        }\n        ImDrawList& DrawList = *GetPlotDrawList();\n        switch (GetCurrentScale()) {\n            case ImPlotScale_LinLin: RenderHeatmap(TransformerLinLin(), DrawList, &bin_counts.Data[0], y_bins, x_bins, 0, max_count, NULL, range.Min(), range.Max(), false); break;\n            case ImPlotScale_LogLin: RenderHeatmap(TransformerLogLin(), DrawList, &bin_counts.Data[0], y_bins, x_bins, 0, max_count, NULL, range.Min(), range.Max(), false); break;\n            case ImPlotScale_LinLog: RenderHeatmap(TransformerLinLog(), DrawList, &bin_counts.Data[0], y_bins, x_bins, 0, max_count, NULL, range.Min(), range.Max(), false); break;\n            case ImPlotScale_LogLog: RenderHeatmap(TransformerLogLog(), DrawList, &bin_counts.Data[0], y_bins, x_bins, 0, max_count, NULL, range.Min(), range.Max(), false); break;\n        }\n        EndItem();\n    }\n    return max_count;\n}\n\ntemplate IMPLOT_API double PlotHistogram2D<ImS8>(const char* label_id,   const ImS8*   xs, const ImS8*   ys, int count, int x_bins, int y_bins, bool density, ImPlotRect range, bool outliers);\ntemplate IMPLOT_API double PlotHistogram2D<ImU8>(const char* label_id,   const ImU8*   xs, const ImU8*   ys, int count, int x_bins, int y_bins, bool density, ImPlotRect range, bool outliers);\ntemplate IMPLOT_API double PlotHistogram2D<ImS16>(const char* label_id,  const ImS16*  xs, const ImS16*  ys, int count, int x_bins, int y_bins, bool density, ImPlotRect range, bool outliers);\ntemplate IMPLOT_API double PlotHistogram2D<ImU16>(const char* label_id,  const ImU16*  xs, const ImU16*  ys, int count, int x_bins, int y_bins, bool density, ImPlotRect range, bool outliers);\ntemplate IMPLOT_API double PlotHistogram2D<ImS32>(const char* label_id,  const ImS32*  xs, const ImS32*  ys, int count, int x_bins, int y_bins, bool density, ImPlotRect range, bool outliers);\ntemplate IMPLOT_API double PlotHistogram2D<ImU32>(const char* label_id,  const ImU32*  xs, const ImU32*  ys, int count, int x_bins, int y_bins, bool density, ImPlotRect range, bool outliers);\ntemplate IMPLOT_API double PlotHistogram2D<ImS64>(const char* label_id,  const ImS64*  xs, const ImS64*  ys, int count, int x_bins, int y_bins, bool density, ImPlotRect range, bool outliers);\ntemplate IMPLOT_API double PlotHistogram2D<ImU64>(const char* label_id,  const ImU64*  xs, const ImU64*  ys, int count, int x_bins, int y_bins, bool density, ImPlotRect range, bool outliers);\ntemplate IMPLOT_API double PlotHistogram2D<float>(const char* label_id,  const float*  xs, const float*  ys, int count, int x_bins, int y_bins, bool density, ImPlotRect range, bool outliers);\ntemplate IMPLOT_API double PlotHistogram2D<double>(const char* label_id, const double* xs, const double* ys, int count, int x_bins, int y_bins, bool density, ImPlotRect range, bool outliers);\n\n//-----------------------------------------------------------------------------\n// PLOT DIGITAL\n//-----------------------------------------------------------------------------\n\n// TODO: Make this behave like all the other plot types (.e. not fixed in y axis)\n\ntemplate <typename Getter>\nIMPLOT_INLINE void PlotDigitalEx(const char* label_id, Getter getter) {\n    if (BeginItem(label_id, ImPlotCol_Fill)) {\n        ImPlotContext& gp = *GImPlot;\n        ImDrawList& DrawList = *GetPlotDrawList();\n        const ImPlotNextItemData& s = GetItemData();\n        if (getter.Count > 1 && s.RenderFill) {\n            ImPlotPlot& plot   = *gp.CurrentPlot;\n            ImPlotAxis& x_axis = plot.Axes[plot.CurrentX];\n            ImPlotAxis& y_axis = plot.Axes[plot.CurrentY];\n\n            int pixYMax = 0;\n            ImPlotPoint itemData1 = getter(0);\n            for (int i = 0; i < getter.Count; ++i) {\n                ImPlotPoint itemData2 = getter(i);\n                if (ImNanOrInf(itemData1.y)) {\n                    itemData1 = itemData2;\n                    continue;\n                }\n                if (ImNanOrInf(itemData2.y)) itemData2.y = ImConstrainNan(ImConstrainInf(itemData2.y));\n                int pixY_0 = (int)(s.LineWeight);\n                itemData1.y = ImMax(0.0, itemData1.y);\n                float pixY_1_float = s.DigitalBitHeight * (float)itemData1.y;\n                int pixY_1 = (int)(pixY_1_float); //allow only positive values\n                int pixY_chPosOffset = (int)(ImMax(s.DigitalBitHeight, pixY_1_float) + s.DigitalBitGap);\n                pixYMax = ImMax(pixYMax, pixY_chPosOffset);\n                ImVec2 pMin = PlotToPixels(itemData1,IMPLOT_AUTO,IMPLOT_AUTO);\n                ImVec2 pMax = PlotToPixels(itemData2,IMPLOT_AUTO,IMPLOT_AUTO);\n                int pixY_Offset = 0; //20 pixel from bottom due to mouse cursor label\n                pMin.y = (y_axis.PixelMin) + ((-gp.DigitalPlotOffset)                   - pixY_Offset);\n                pMax.y = (y_axis.PixelMin) + ((-gp.DigitalPlotOffset) - pixY_0 - pixY_1 - pixY_Offset);\n                //plot only one rectangle for same digital state\n                while (((i+2) < getter.Count) && (itemData1.y == itemData2.y)) {\n                    const int in = (i + 1);\n                    itemData2 = getter(in);\n                    if (ImNanOrInf(itemData2.y)) break;\n                    pMax.x = PlotToPixels(itemData2,IMPLOT_AUTO,IMPLOT_AUTO).x;\n                    i++;\n                }\n                //do not extend plot outside plot range\n                if (pMin.x < x_axis.PixelMin) pMin.x = x_axis.PixelMin;\n                if (pMax.x < x_axis.PixelMin) pMax.x = x_axis.PixelMin;\n                if (pMin.x > x_axis.PixelMax) pMin.x = x_axis.PixelMax;\n                if (pMax.x > x_axis.PixelMax) pMax.x = x_axis.PixelMax;\n                //plot a rectangle that extends up to x2 with y1 height\n                if ((pMax.x > pMin.x) && (gp.CurrentPlot->PlotRect.Contains(pMin) || gp.CurrentPlot->PlotRect.Contains(pMax))) {\n                    // ImVec4 colAlpha = item->Color;\n                    // colAlpha.w = item->Highlight ? 1.0f : 0.9f;\n                    DrawList.AddRectFilled(pMin, pMax, ImGui::GetColorU32(s.Colors[ImPlotCol_Fill]));\n                }\n                itemData1 = itemData2;\n            }\n            gp.DigitalPlotItemCnt++;\n            gp.DigitalPlotOffset += pixYMax;\n        }\n        EndItem();\n    }\n}\n\n\ntemplate <typename T>\nvoid PlotDigital(const char* label_id, const T* xs, const T* ys, int count, int offset, int stride) {\n    GetterXY<GetterIdx<T>,GetterIdx<T>> getter(GetterIdx<T>(xs,count,offset,stride),GetterIdx<T>(ys,count,offset,stride),count);\n    return PlotDigitalEx(label_id, getter);\n}\n\ntemplate IMPLOT_API void PlotDigital<ImS8>(const char* label_id, const ImS8* xs, const ImS8* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotDigital<ImU8>(const char* label_id, const ImU8* xs, const ImU8* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotDigital<ImS16>(const char* label_id, const ImS16* xs, const ImS16* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotDigital<ImU16>(const char* label_id, const ImU16* xs, const ImU16* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotDigital<ImS32>(const char* label_id, const ImS32* xs, const ImS32* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotDigital<ImU32>(const char* label_id, const ImU32* xs, const ImU32* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotDigital<ImS64>(const char* label_id, const ImS64* xs, const ImS64* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotDigital<ImU64>(const char* label_id, const ImU64* xs, const ImU64* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotDigital<float>(const char* label_id, const float* xs, const float* ys, int count, int offset, int stride);\ntemplate IMPLOT_API void PlotDigital<double>(const char* label_id, const double* xs, const double* ys, int count, int offset, int stride);\n\n// custom\nvoid PlotDigitalG(const char* label_id, ImPlotGetter getter_func, void* data, int count) {\n    GetterFuncPtr getter(getter_func,data,count);\n    return PlotDigitalEx(label_id, getter);\n}\n\n//-----------------------------------------------------------------------------\n// PLOT IMAGE\n//-----------------------------------------------------------------------------\n\nvoid PlotImage(const char* label_id, ImTextureID user_texture_id, const ImPlotPoint& bmin, const ImPlotPoint& bmax, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col) {\n    if (BeginItem(label_id)) {\n        if (FitThisFrame()) {\n            FitPoint(bmin);\n            FitPoint(bmax);\n        }\n        ImU32 tint_col32 = ImGui::ColorConvertFloat4ToU32(tint_col);\n        GetCurrentItem()->Color = tint_col32;\n        ImDrawList& DrawList = *GetPlotDrawList();\n        ImVec2 p1 = PlotToPixels(bmin.x, bmax.y,IMPLOT_AUTO,IMPLOT_AUTO);\n        ImVec2 p2 = PlotToPixels(bmax.x, bmin.y,IMPLOT_AUTO,IMPLOT_AUTO);\n        PushPlotClipRect();\n        DrawList.AddImage(user_texture_id, p1, p2, uv0, uv1, tint_col32);\n        PopPlotClipRect();\n        EndItem();\n    }\n}\n\n//-----------------------------------------------------------------------------\n// PLOT TEXT\n//-----------------------------------------------------------------------------\n\n// double\nvoid PlotText(const char* text, double x, double y, bool vertical, const ImVec2& pixel_offset) {\n    IM_ASSERT_USER_ERROR(GImPlot->CurrentPlot != NULL, \"PlotText() needs to be called between BeginPlot() and EndPlot()!\");\n    SetupLock();\n    ImDrawList & DrawList = *GetPlotDrawList();\n    PushPlotClipRect();\n    ImU32 colTxt = GetStyleColorU32(ImPlotCol_InlayText);\n    if (vertical) {\n        ImVec2 siz = CalcTextSizeVertical(text) * 0.5f;\n        ImVec2 ctr = siz * 0.5f;\n        ImVec2 pos = PlotToPixels(ImPlotPoint(x,y),IMPLOT_AUTO,IMPLOT_AUTO) + ImVec2(-ctr.x, ctr.y) + pixel_offset;\n        if (FitThisFrame()) {\n            FitPoint(PixelsToPlot(pos));\n            FitPoint(PixelsToPlot(pos.x + siz.x, pos.y - siz.y));\n        }\n        AddTextVertical(&DrawList, pos, colTxt, text);\n    }\n    else {\n        ImVec2 siz = ImGui::CalcTextSize(text);\n        ImVec2 pos = PlotToPixels(ImPlotPoint(x,y),IMPLOT_AUTO,IMPLOT_AUTO) - siz * 0.5f + pixel_offset;\n        if (FitThisFrame()) {\n            FitPoint(PixelsToPlot(pos));\n            FitPoint(PixelsToPlot(pos+siz));\n        }\n        DrawList.AddText(pos, colTxt, text);\n    }\n    PopPlotClipRect();\n}\n\n//-----------------------------------------------------------------------------\n// PLOT DUMMY\n//-----------------------------------------------------------------------------\n\nvoid PlotDummy(const char* label_id) {\n    if (BeginItem(label_id, ImPlotCol_Line))\n        EndItem();\n}\n\n} // namespace ImPlot\n"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2021 TapTap\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# perf-doctor\nA mobile game profiler.\n\n[Download prebuit binary](https://github.com/taptap/perf-doctor/releases)\n\n## GUI interface\n\n![](https://user-images.githubusercontent.com/558657/143417411-f257fc80-c1fa-4c51-8d9a-983df5cf22be.png)\n\n## Export perf data\n\n![](https://user-images.githubusercontent.com/558657/144166485-ba706ce1-544d-49be-a426-12fc9db79f42.png)\n\n# Build from scratch\n- clone https://github.com/taptap/perf-doctor\n- clone [Cinder framework](https://github.com/cinder/Cinder), `Cinder/` and `perf-doctor/` should be put in the same folder.\n- Open `Cinder/proj/vc2019/cinder.sln` with `Visual Studio 2019`, choose the same target (x64 Debug) as perf-doctor then build. The output is `cinder.lib`.\n- Open `vc2019/perf-doctor.sln` with `Visual Studio 2019`\n\n# Contact\n- vinjn@qq.com\n\n## adb commands for gpu profiling\n\n### adb shell settings list global | grep gpu\n```\nenable_gpu_debug_layers=1\ngpu_debug_app=com.xd.atelier\ngpu_debug_layer_app=com.google.android.gapid.arm64v8a:com.google.pixel.coral.gpuprofiling.vulkanlayer\ngpu_debug_layers=DebugMarker:CPUTiming:VkRenderStagesProducer\n```\n\n### Disable settings\n```\nadb shell settings delete global enable_gpu_debug_layers\nadb shell settings delete global gpu_debug_app\nadb shell settings delete global gpu_debug_layers_gles\nadb shell settings delete global gpu_debug_layers\nadb shell settings delete global gpu_debug_layer_app\n```\n\n### adb shell getprop | grep profiler\n```\n[debug.graphics.gpu.profiler.perfetto]: [1]\n[graphics.gpu.profiler.support]: [true]\n[graphics.gpu.profiler.vulkan_layer_apk]: [com.google.pixel.coral.gpuprofiling.vulkanlayer]\n```\n\n"
  },
  {
    "path": "_config.yml",
    "content": "theme: jekyll-theme-cayman"
  },
  {
    "path": "build.bat",
    "content": "pyinstaller.exe -p tidevice\\tidevice -F tidevice\\tidevice\\__main__.py -n tidevice.exe --distpath bin\r\n\r\ncd %~dp0\\vc2019\r\nset proj=perf-doctor.sln\r\nset msbuild=\"C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Community\\MSBuild\\Current\\Bin\\amd64\\MSBuild.exe\"\r\nset msbuild2=\"D:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Community\\MSBuild\\Current\\Bin\\amd64\\MSBuild.exe\"\r\nREM msbuild %proj% /p:Configuration=Debug /p:Platform=x64 /v:minimal /m\r\n%msbuild% %proj% /p:Configuration=Release /p:Platform=x64 /v:minimal /m\r\n%msbuild2% %proj% /p:Configuration=Release /p:Platform=x64 /v:minimal /m\r\nREM msbuild %proj% /p:Configuration=Debug_Shared /p:Platform=x64 /v:minimal /m\r\nREM msbuild %proj% /p:Configuration=Release_Shared /p:Platform=x64 /v:minimal /m\r\ncd .."
  },
  {
    "path": "deploy.bat",
    "content": "set mydate=%date:/=%\r\nset TIMESTAMP=%mydate: =_%\r\nset OUTPUT=perf-doctor-%TIMESTAMP%\r\nrmdir /S /Q %OUTPUT%\r\nmkdir %OUTPUT%\r\nset SRC=bin/\r\n\r\nrobocopy %SRC%/ %OUTPUT% *.bat\r\nrobocopy %SRC%/ %OUTPUT% *.py\r\nrobocopy %SRC%/ %OUTPUT% perf-doctor.exe\r\nrobocopy %SRC%/ %OUTPUT% unreal-cmd.txt\r\nrobocopy %SRC%/ %OUTPUT% UE4CommandLine.txt\r\nrobocopy %SRC%/ %OUTPUT% perfetto-template.txt\r\nrobocopy %SRC%/ %OUTPUT% *.ini\r\nrobocopy %SRC%/adb %OUTPUT%/adb *"
  },
  {
    "path": "doc/README.md",
    "content": "# Simpleperf\n\nSimpleperf is a native CPU profiling tool for Android. It can be used to profile\nboth Android applications and native processes running on Android. It can\nprofile both Java and C++ code on Android. The simpleperf executable can run on Android >=L,\nand Python scripts can be used on Android >= N.\n\nSimpleperf is part of the Android Open Source Project.\nThe source code is [here](https://android.googlesource.com/platform/system/extras/+/master/simpleperf/).\nThe latest document is [here](https://android.googlesource.com/platform/system/extras/+/master/simpleperf/doc/README.md).\n\n[TOC]\n\n## Introduction\n\nAn introduction slide deck is [here](./introduction.pdf).\n\nSimpleperf contains two parts: the simpleperf executable and Python scripts.\n\nThe simpleperf executable works similar to linux-tools-perf, but has some specific features for\nthe Android profiling environment:\n\n1. It collects more info in profiling data. Since the common workflow is \"record on the device, and\n   report on the host\", simpleperf not only collects samples in profiling data, but also collects\n   needed symbols, device info and recording time.\n\n2. It delivers new features for recording.\n   1) When recording dwarf based call graph, simpleperf unwinds the stack before writing a sample\n      to file. This is to save storage space on the device.\n   2) Support tracing both on CPU time and off CPU time with --trace-offcpu option.\n   3) Support recording callgraphs of JITed and interpreted Java code on Android >= P.\n\n3. It relates closely to the Android platform.\n   1) Is aware of Android environment, like using system properties to enable profiling, using\n      run-as to profile in application's context.\n   2) Supports reading symbols and debug information from the .gnu_debugdata section, because\n      system libraries are built with .gnu_debugdata section starting from Android O.\n   3) Supports profiling shared libraries embedded in apk files.\n   4) It uses the standard Android stack unwinder, so its results are consistent with all other\n      Android tools.\n\n4. It builds executables and shared libraries for different usages.\n   1) Builds static executables on the device. Since static executables don't rely on any library,\n      simpleperf executables can be pushed on any Android device and used to record profiling data.\n   2) Builds executables on different hosts: Linux, Mac and Windows. These executables can be used\n      to report on hosts.\n   3) Builds report shared libraries on different hosts. The report library is used by different\n      Python scripts to parse profiling data.\n\nDetailed documentation for the simpleperf executable is [here](#executable-commands-reference).\n\nPython scripts are split into three parts according to their functions:\n\n1. Scripts used for recording, like app_profiler.py, run_simpleperf_without_usb_connection.py.\n\n2. Scripts used for reporting, like report.py, report_html.py, inferno.\n\n3. Scripts used for parsing profiling data, like simpleperf_report_lib.py.\n\nDetailed documentation for the Python scripts is [here](#scripts-reference).\n\n\n## Tools in simpleperf\n\nThe simpleperf executables and Python scripts are located in simpleperf/ in ndk releases, and in\nsystem/extras/simpleperf/scripts/ in AOSP. Their functions are listed below.\n\nbin/: contains executables and shared libraries.\n\nbin/android/${arch}/simpleperf: static simpleperf executables used on the device.\n\nbin/${host}/${arch}/simpleperf: simpleperf executables used on the host, only supports reporting.\n\nbin/${host}/${arch}/libsimpleperf_report.${so/dylib/dll}: report shared libraries used on the host.\n\n*.py, inferno, purgatorio: Python scripts used for recording and reporting. Details are in [scripts_reference.md](scripts_reference.md).\n\n\n## Android application profiling\n\nSee [android_application_profiling.md](./android_application_profiling.md).\n\n\n## Android platform profiling\n\nSee [android_platform_profiling.md](./android_platform_profiling.md).\n\n\n## Executable commands reference\n\nSee [executable_commands_reference.md](./executable_commands_reference.md).\n\n\n## Scripts reference\n\nSee [scripts_reference.md](./scripts_reference.md).\n\n\n## Answers to common issues\n\n### Why we suggest profiling on Android >= N devices?\n\n1. Running on a device reflects a real running situation, so we suggest\n   profiling on real devices instead of emulators.\n2. To profile Java code, we need ART running in oat mode, which is only\n   available >= L for rooted devices, and >= N for non-rooted devices.\n3. Old Android versions are likely to be shipped with old kernels (< 3.18),\n   which may not support profiling features like recording dwarf based call graphs.\n4. Old Android versions are likely to be shipped with Arm32 chips. In Arm32\n   mode, recording stack frame based call graphs doesn't work well.\n\n### Suggestions about recording call graphs\n\nBelow is our experiences of dwarf based call graphs and stack frame based call graphs.\n\ndwarf based call graphs:\n1. Need support of debug information in binaries.\n2. Behave normally well on both ARM and ARM64, for both fully compiled Java code and C++ code.\n3. Can only unwind 64K stack for each sample. So usually can't show complete flamegraph. But\n   probably is enough for users to identify hot places.\n4. Take more CPU time than stack frame based call graphs. So the sample frequency is suggested\n   to be 1000 Hz. Thus at most 1000 samples per second.\n\nstack frame based call graphs:\n1. Need support of stack frame registers.\n2. Don't work well on ARM. Because ARM is short of registers, and ARM and THUMB code have different\n   stack frame registers. So the kernel can't unwind user stack containing both ARM/THUMB code.\n3. Also don't work well on fully compiled Java code on ARM64. Because the ART compiler doesn't\n   reserve stack frame registers.\n4. Work well when profiling native programs on ARM64. One example is profiling surfacelinger. And\n   usually shows complete flamegraph when it works well.\n5. Take less CPU time than dwarf based call graphs. So the sample frequency can be 4000 Hz or\n   higher.\n\nSo if you need to profile code on ARM or profile fully compiled Java code, dwarf based call graphs\nmay be better. If you need to profile C++ code on ARM64, stack frame based call graphs may be\nbetter. After all, you can always try dwarf based call graph first, because it always produces\nreasonable results when given unstripped binaries properly. If it doesn't work well enough, then\ntry stack frame based call graphs instead.\n\nSimpleperf may need unstripped native binaries on the device to generate good dwarf based call\ngraphs. It can be supported by downloading unstripped native libraries on device, as [here](#fix-broken-callchain-stopped-at-c-functions).\n\n### Why we can't always get complete DWARF-based call graphs?\n\nDWARF-based call graphs are generated by unwinding thread stacks. When a sample is generated, up to\n64KB stack data is dumped by the kernel. By unwinding the stack based on dwarf information, we get\na callchain. But the thread stack can be much longer than 64KB. In that case, we can't unwind to\nthe thread start point.\n\nTo alleviate the problem, simpleperf joins callchains after recording them. If two callchains of\na thread have an entry containing the same ip and sp address, then simpleperf tries to join them to\nmake the callchains longer. In that case, the longer we run, the more samples we get. This makes it\nmore likely to get complete callchains, but it's still not guaranteed to get complete call graphs.\n\n### How to solve missing symbols in report?\n\nThe simpleperf record command collects symbols on device in perf.data. But if the native libraries\nyou use on device are stripped, this will result in a lot of unknown symbols in the report. A\nsolution is to build binary_cache on host.\n\n```sh\n# Collect binaries needed by perf.data in binary_cache/.\n$ ./binary_cache_builder.py -lib NATIVE_LIB_DIR,...\n```\n\nThe NATIVE_LIB_DIRs passed in -lib option are the directories containing unstripped native\nlibraries on host. After running it, the native libraries containing symbol tables are collected\nin binary_cache/ for use when reporting.\n\n```sh\n$ ./report.py --symfs binary_cache\n\n# report_html.py searches binary_cache/ automatically, so you don't need to\n# pass it any argument.\n$ ./report_html.py\n```\n\n### Fix broken callchain stopped at C functions\n\nWhen using dwarf based call graphs, simpleperf generates callchains during recording to save space.\nThe debug information needed to unwind C functions is in .debug_frame section, which is usually\nstripped in native libraries in apks. To fix this, we can download unstripped version of native\nlibraries on device, and ask simpleperf to use them when recording.\n\nTo use simpleperf directly:\n\n```sh\n# create native_libs dir on device, and push unstripped libs in it (nested dirs are not supported).\n$ adb shell mkdir /data/local/tmp/native_libs\n$ adb push <unstripped_dir>/*.so /data/local/tmp/native_libs\n# run simpleperf record with --symfs option.\n$ adb shell simpleperf record xxx --symfs /data/local/tmp/native_libs\n```\n\nTo use app_profiler.py:\n\n```sh\n$ ./app_profiler.py -lib <unstripped_dir>\n```\n\n### Show annotated source code and disassembly\n\nTo show hot places at source code and instruction level, we need to show source code and\ndisassembly with event count annotation. Simpleperf supports showing annotated source code and\ndisassembly for C++ code and fully compiled Java code. Simpleperf supports two ways to do it:\n\n1. Through report_html.py:\n   1) Generate perf.data and pull it on host.\n   2) Generate binary_cache, containing elf files with debug information. Use -lib option to add\n     libs with debug info. Do it with\n     `binary_cache_builder.py -i perf.data -lib <dir_of_lib_with_debug_info>`.\n   3) Use report_html.py to generate report.html with annotated source code and disassembly,\n     as described [here](https://android.googlesource.com/platform/system/extras/+/master/simpleperf/doc/scripts_reference.md#report_html_py).\n\n2. Through pprof.\n   1) Generate perf.data and binary_cache as above.\n   2) Use pprof_proto_generator.py to generate pprof proto file. `pprof_proto_generator.py`.\n   3) Use pprof to report a function with annotated source code, as described [here](https://android.googlesource.com/platform/system/extras/+/master/simpleperf/doc/scripts_reference.md#pprof_proto_generator_py).\n\n## Bugs and contribution\n\nBugs and feature requests can be submitted at https://github.com/android/ndk/issues.\nPatches can be uploaded to android-review.googlesource.com as [here](https://source.android.com/setup/contribute/),\nor sent to email addresses listed [here](https://android.googlesource.com/platform/system/extras/+/master/simpleperf/OWNERS).\n\nIf you want to compile simpleperf C++ source code, follow below steps:\n1. Download AOSP main branch as [here](https://source.android.com/setup/build/requirements).\n2. Build simpleperf.\n```sh\n$ . build/envsetup.sh\n$ lunch aosp_arm64-userdebug\n$ mmma system/extras/simpleperf -j30\n```\n\nIf built successfully, out/target/product/generic_arm64/system/bin/simpleperf is for ARM64, and\nout/target/product/generic_arm64/system/bin/simpleperf32 is for ARM.\n"
  },
  {
    "path": "doc/android_application_profiling.md",
    "content": "# Android application profiling\n\nThis section shows how to profile an Android application.\nSome examples are [Here](https://android.googlesource.com/platform/system/extras/+/master/simpleperf/demo/README.md).\n\nProfiling an Android application involves three steps:\n1. Prepare an Android application.\n2. Record profiling data.\n3. Report profiling data.\n\n[TOC]\n\n## Prepare an Android application\n\nBased on the profiling situation, we may need to customize the build script to generate an apk file\nspecifically for profiling. Below are some suggestions.\n\n1. If you want to profile a debug build of an application:\n\nFor the debug build type, Android studio sets android::debuggable=\"true\" in AndroidManifest.xml,\nenables JNI checks and may not optimize C/C++ code. It can be profiled by simpleperf without any\nchange.\n\n2. If you want to profile a release build of an application:\n\nFor the release build type, Android studio sets android::debuggable=\"false\" in AndroidManifest.xml,\ndisables JNI checks and optimizes C/C++ code. However, security restrictions mean that only apps\nwith android::debuggable set to true can be profiled. So simpleperf can only profile a release\nbuild under these three circumstances:\nIf you are on a rooted device, you can profile any app.\n\nIf you are on Android >= Q, you can add profileableFromShell flag in AndroidManifest.xml, this makes\na released app profileable by preinstalled profiling tools. In this case, simpleperf downloaded by\nadb will invoke simpleperf preinstalled in system image to profile the app.\n\n```\n<manifest ...>\n    <application ...>\n      <profileable android:shell=\"true\" />\n    </application>\n</manifest>\n```\n\nIf you are on Android >= O, we can use [wrap.sh](https://developer.android.com/ndk/guides/wrap-script.html)\nto profile a release build:\nStep 1: Add android::debuggable=\"true\" in AndroidManifest.xml to enable profiling.\n```\n<manifest ...>\n    <application android::debuggable=\"true\" ...>\n```\n\nStep 2: Add wrap.sh in lib/`arch` directories. wrap.sh runs the app without passing any debug flags\nto ART, so the app runs as a release app. wrap.sh can be done by adding the script below in\napp/build.gradle.\n```\nandroid {\n    buildTypes {\n        release {\n            sourceSets {\n                release {\n                    resources {\n                        srcDir {\n                            \"wrap_sh_lib_dir\"\n                        }\n                    }\n                }\n            }\n        }\n    }\n}\n\ntask createWrapShLibDir\n    for (String abi : [\"armeabi\", \"armeabi-v7a\", \"arm64-v8a\", \"x86\", \"x86_64\"]) {\n        def dir = new File(\"app/wrap_sh_lib_dir/lib/\" + abi)\n        dir.mkdirs()\n        def wrapFile = new File(dir, \"wrap.sh\")\n        wrapFile.withWriter { writer ->\n            writer.write('#!/system/bin/sh\\n\\$@\\n')\n        }\n    }\n}\n```\n\n3. If you want to profile C/C++ code:\n\nAndroid studio strips symbol table and debug info of native libraries in the apk. So the profiling\nresults may contain unknown symbols or broken callgraphs. To fix this, we can pass app_profiler.py\na directory containing unstripped native libraries via the -lib option. Usually the directory can\nbe the path of your Android Studio project.\n\n\n4. If you want to profile Java code:\n\nOn Android >= P, simpleperf supports profiling Java code, no matter whether it is executed by\nthe interpreter, or JITed, or compiled into native instructions. So you don't need to do anything.\n\nOn Android O, simpleperf supports profiling Java code which is compiled into native instructions,\nand it also needs wrap.sh to use the compiled Java code. To compile Java code, we can pass\napp_profiler.py the --compile_java_code option.\n\nOn Android N, simpleperf supports profiling Java code that is compiled into native instructions.\nTo compile java code, we can pass app_profiler.py the --compile_java_code option.\n\nOn Android <= M, simpleperf doesn't support profiling Java code.\n\n\nBelow I use application [SimpleperfExampleCpp](https://android.googlesource.com/platform/system/extras/+/master/simpleperf/demo/SimpleperfExampleCpp).\nIt builds an app-debug.apk for profiling.\n\n```sh\n$ git clone https://android.googlesource.com/platform/system/extras\n$ cd extras/simpleperf/demo\n# Open SimpleperfExampleCpp project with Android studio, and build this project\n# successfully, otherwise the `./gradlew` command below will fail.\n$ cd SimpleperfExampleCpp\n\n# On windows, use \"gradlew\" instead.\n$ ./gradlew clean assemble\n$ adb install -r app/build/outputs/apk/debug/app-debug.apk\n```\n\n## Record and report profiling data\n\nWe can use [app-profiler.py](scripts_reference.md#app_profilerpy) to profile Android applications.\n\n```sh\n# Cd to the directory of simpleperf scripts. Record perf.data.\n# -p option selects the profiled app using its package name.\n# --compile_java_code option compiles Java code into native instructions, which isn't needed on\n# Android >= P.\n# -a option selects the Activity to profile.\n# -lib option gives the directory to find debug native libraries.\n$ ./app_profiler.py -p simpleperf.example.cpp -a .MixActivity -lib path_of_SimpleperfExampleCpp\n```\n\nThis will collect profiling data in perf.data in the current directory, and related native\nbinaries in binary_cache/.\n\nNormally we need to use the app when profiling, otherwise we may record no samples. But in this\ncase, the MixActivity starts a busy thread. So we don't need to use the app while profiling.\n\n```sh\n# Report perf.data in stdio interface.\n$ ./report.py\nCmdline: /data/data/simpleperf.example.cpp/simpleperf record ...\nArch: arm64\nEvent: task-clock:u (type 1, config 1)\nSamples: 10023\nEvent count: 10023000000\n\nOverhead  Command     Pid   Tid   Shared Object              Symbol\n27.04%    BusyThread  5703  5729  /system/lib64/libart.so    art::JniMethodStart(art::Thread*)\n25.87%    BusyThread  5703  5729  /system/lib64/libc.so      long StrToI<long, ...\n...\n```\n\n[report.py](scripts_reference.md#reportpy) reports profiling data in stdio interface. If there\nare a lot of unknown symbols in the report, check [here](README.md#how-to-solve-missing-symbols-in-report).\n\n```sh\n# Report perf.data in html interface.\n$ ./report_html.py\n\n# Add source code and disassembly. Change the path of source_dirs if it not correct.\n$ ./report_html.py --add_source_code --source_dirs path_of_SimpleperfExampleCpp \\\n      --add_disassembly\n```\n\n[report_html.py](scripts_reference.md#report_htmlpy) generates report in report.html, and pops up\na browser tab to show it.\n\n## Record and report call graph\n\nWe can record and report [call graphs](executable_commands_reference.md#record-call-graphs) as below.\n\n```sh\n# Record dwarf based call graphs: add \"-g\" in the -r option.\n$ ./app_profiler.py -p simpleperf.example.cpp \\\n        -r \"-e task-clock:u -f 1000 --duration 10 -g\" -lib path_of_SimpleperfExampleCpp\n\n# Record stack frame based call graphs: add \"--call-graph fp\" in the -r option.\n$ ./app_profiler.py -p simpleperf.example.cpp \\\n        -r \"-e task-clock:u -f 1000 --duration 10 --call-graph fp\" \\\n        -lib path_of_SimpleperfExampleCpp\n\n# Report call graphs in stdio interface.\n$ ./report.py -g\n\n# Report call graphs in python Tk interface.\n$ ./report.py -g --gui\n\n# Report call graphs in html interface.\n$ ./report_html.py\n\n# Report call graphs in flamegraphs.\n# On Windows, use inferno.bat instead of ./inferno.sh.\n$ ./inferno.sh -sc\n```\n\n## Report in html interface\n\nWe can use [report_html.py](scripts_reference.md#report_htmlpy) to show profiling results in a web browser.\nreport_html.py integrates chart statistics, sample table, flamegraphs, source code annotation\nand disassembly annotation. It is the recommended way to show reports.\n\n```sh\n$ ./report_html.py\n```\n\n## Show flamegraph\n\nTo show flamegraphs, we need to first record call graphs. Flamegraphs are shown by\nreport_html.py in the \"Flamegraph\" tab.\nWe can also use [inferno](scripts_reference.md#inferno) to show flamegraphs directly.\n\n```sh\n# On Windows, use inferno.bat instead of ./inferno.sh.\n$ ./inferno.sh -sc\n```\n\nWe can also build flamegraphs using https://github.com/brendangregg/FlameGraph.\nPlease make sure you have perl installed.\n\n```sh\n$ git clone https://github.com/brendangregg/FlameGraph.git\n$ ./report_sample.py --symfs binary_cache >out.perf\n$ FlameGraph/stackcollapse-perf.pl out.perf >out.folded\n$ FlameGraph/flamegraph.pl out.folded >a.svg\n```\n\n## Report in Android Studio\n\nsimpleperf report-sample command can convert perf.data into protobuf format accepted by\nAndroid Studio cpu profiler. The conversion can be done either on device or on host. If you have\nmore symbol info on host, then prefer do it on host with --symdir option.\n\n```sh\n$ simpleperf report-sample --protobuf --show-callchain -i perf.data -o perf.trace\n# Then open perf.trace in Android Studio to show it.\n```\n\n## Deobfuscate Java symbols\n\nJava symbols may be obfuscated by ProGuard. To restore the original symbols in a report, we can\npass a Proguard mapping file to the report scripts or report-sample command via\n`--proguard-mapping-file`.\n\n```sh\n$ ./report_html.py --proguard-mapping-file proguard_mapping_file.txt\n```\n\n## Record both on CPU time and off CPU time\n\nWe can [record both on CPU time and off CPU time](executable_commands_reference.md#record-both-on-cpu-time-and-off-cpu-time).\n\nFirst check if trace-offcpu feature is supported on the device.\n\n```sh\n$ ./run_simpleperf_on_device.py list --show-features\ndwarf-based-call-graph\ntrace-offcpu\n```\n\nIf trace-offcpu is supported, it will be shown in the feature list. Then we can try it.\n\n```sh\n$ ./app_profiler.py -p simpleperf.example.cpp -a .SleepActivity \\\n    -r \"-g -e task-clock:u -f 1000 --duration 10 --trace-offcpu\" \\\n    -lib path_of_SimpleperfExampleCpp\n$ ./report_html.py --add_disassembly --add_source_code \\\n    --source_dirs path_of_SimpleperfExampleCpp\n```\n\n## Profile from launch\n\nWe can [profile from launch of an application](scripts_reference.md#profile-from-launch-of-an-application).\n\n```sh\n# Start simpleperf recording, then start the Activity to profile.\n$ ./app_profiler.py -p simpleperf.example.cpp -a .MainActivity\n\n# We can also start the Activity on the device manually.\n# 1. Make sure the application isn't running or one of the recent apps.\n# 2. Start simpleperf recording.\n$ ./app_profiler.py -p simpleperf.example.cpp\n# 3. Start the app manually on the device.\n```\n\n## Control recording in application code\n\nSimpleperf supports controlling recording from application code. Below is the workflow:\n\n1. Run `api_profiler.py prepare -p <package_name>` to allow an app recording itself using\n   simpleperf. By default, the permission is reset after device reboot. So we need to run the\n   script every time the device reboots. But on Android >= 13, we can use `--days` options to\n   set how long we want the permission to last.\n\n2. Link simpleperf app_api code in the application. The app needs to be debuggable or\n   profileableFromShell as described [here](#prepare-an-android-application). Then the app can\n   use the api to start/pause/resume/stop recording. To start recording, the app_api forks a child\n   process running simpleperf, and uses pipe files to send commands to the child process. After\n   recording, a profiling data file is generated.\n\n3. Run `api_profiler.py collect -p <package_name>` to collect profiling data files to host.\n\nExamples are CppApi and JavaApi in [demo](https://android.googlesource.com/platform/system/extras/+/master/simpleperf/demo).\n\n\n## Parse profiling data manually\n\nWe can also write python scripts to parse profiling data manually, by using\n[simpleperf_report_lib.py](scripts_reference.md#simpleperf_report_libpy). Examples are report_sample.py,\nreport_html.py.\n"
  },
  {
    "path": "doc/android_platform_profiling.md",
    "content": "# Android platform profiling\n\n[TOC]\n\n## General Tips\n\nHere are some tips for Android platform developers, who build and flash system images on rooted\ndevices:\n1. After running `adb root`, simpleperf can be used to profile any process or system wide.\n2. It is recommended to use the latest simpleperf available in AOSP main, if you are not working\non the current main branch. Scripts are in `system/extras/simpleperf/scripts`, binaries are in\n`system/extras/simpleperf/scripts/bin/android`.\n3. It is recommended to use `app_profiler.py` for recording, and `report_html.py` for reporting.\nBelow is an example.\n\n```sh\n# Record surfaceflinger process for 10 seconds with dwarf based call graph. More examples are in\n# scripts reference in the doc.\n$ ./app_profiler.py -np surfaceflinger -r \"-g --duration 10\"\n\n# Generate html report.\n$ ./report_html.py\n```\n\n4. Since Android >= O has symbols for system libraries on device, we don't need to use unstripped\nbinaries in `$ANDROID_PRODUCT_OUT/symbols` to report call graphs. However, they are needed to add\nsource code and disassembly (with line numbers) in the report. Below is an example.\n\n```sh\n# Doing recording with app_profiler.py or simpleperf on device, and generates perf.data on host.\n$ ./app_profiler.py -np surfaceflinger -r \"--call-graph fp --duration 10\"\n\n# Collect unstripped binaries from $ANDROID_PRODUCT_OUT/symbols to binary_cache/.\n$ ./binary_cache_builder.py -lib $ANDROID_PRODUCT_OUT/symbols\n\n# Report source code and disassembly. Disassembling all binaries is slow, so it's better to add\n# --binary_filter option to only disassemble selected binaries.\n$ ./report_html.py --add_source_code --source_dirs $ANDROID_BUILD_TOP --add_disassembly \\\n  --binary_filter surfaceflinger.so\n```\n\n## Start simpleperf from system_server process\n\nSometimes we want to profile a process/system-wide when a special situation happens. In this case,\nwe can add code starting simpleperf at the point where the situation is detected.\n\n1. Disable selinux by `adb shell setenforce 0`. Because selinux only allows simpleperf running\n   in shell or debuggable/profileable apps.\n\n2. Add below code at the point where the special situation is detected.\n\n```java\ntry {\n  // for capability check\n  Os.prctl(OsConstants.PR_CAP_AMBIENT, OsConstants.PR_CAP_AMBIENT_RAISE,\n           OsConstants.CAP_SYS_PTRACE, 0, 0);\n  // Write to /data instead of /data/local/tmp. Because /data can be written by system user.\n  Runtime.getRuntime().exec(\"/system/bin/simpleperf record -g -p \" + String.valueOf(Process.myPid())\n            + \" -o /data/perf.data --duration 30 --log-to-android-buffer --log verbose\");\n} catch (Exception e) {\n  Slog.e(TAG, \"error while running simpleperf\");\n  e.printStackTrace();\n}\n```\n\n## Hardware PMU counter limit\n\nWhen monitoring instruction and cache related perf events (in hw/cache/raw/pmu category of list cmd),\nthese events are mapped to PMU counters on each cpu core. But each core only has a limited number\nof PMU counters. If number of events > number of PMU counters, then the counters are multiplexed\namong events, which probably isn't what we want. We can use `simpleperf stat --print-hw-counter` to\nshow hardware counters (per core) available on the device.\n\nOn Pixel devices, the number of PMU counters on each core is usually 7, of which 4 of them are used\nby the kernel to monitor memory latency. So only 3 counters are available. It's fine to monitor up\nto 3 PMU events at the same time. To monitor more than 3 events, the `--use-devfreq-counters` option\ncan be used to borrow from the counters used by the kernel.\n"
  },
  {
    "path": "doc/collect_etm_data_for_autofdo.md",
    "content": "# Collect ETM data for AutoFDO\n\n[TOC]\n\n## Introduction\n\nETM is a hardware feature available on arm64 devices. It collects the instruction stream running on\neach cpu. ARM uses ETM as an alternative for LBR (last branch record) on x86.\nSimpleperf supports collecting ETM data, and converting it to input files for AutoFDO, which can\nthen be used for PGO (profile-guided optimization) during compilation.\n\nOn ARMv8, ETM is considered as an external debug interface (unless ARMv8.4 Self-hosted Trace\nextension is impelemented). So it needs to be enabled explicitly in the bootloader, and isn't\navailable on user devices. For Pixel devices, it's available on EVT and DVT devices on Pixel 4,\nPixel 4a (5G) and Pixel 5. To test if it's available on other devices, you can follow commands in\nthis doc and see if you can record any ETM data.\n\n## Examples\n\nBelow are examples collecting ETM data for AutoFDO. It has two steps: first recording ETM data,\nsecond converting ETM data to AutoFDO input files.\n\nRecord ETM data:\n\n```sh\n# preparation: we need to be root to record ETM data\n$ adb root\n$ adb shell\nredfin:/ \\# cd data/local/tmp\nredfin:/data/local/tmp \\#\n\n# Do a system wide collection, it writes output to perf.data.\n# If only want ETM data for kernel, use `-e cs-etm:k`.\n# If only want ETM data for userspace, use `-e cs-etm:u`.\nredfin:/data/local/tmp \\# simpleperf record -e cs-etm --duration 3 -a\n\n# To reduce file size and time converting to AutoFDO input files, we recommend converting ETM data\n# into an intermediate branch-list format.\nredfin:/data/local/tmp \\# simpleperf inject --output branch-list -o branch_list.data\n```\n\nConverting ETM data to AutoFDO input files needs to read binaries.\nSo for userspace libraries, they can be converted on device. For kernel, it needs\nto be converted on host, with vmlinux and kernel modules available.\n\nConvert ETM data for userspace libraries:\n\n```sh\n# Injecting ETM data on device. It writes output to perf_inject.data.\n# perf_inject.data is a text file, containing branch counts for each library.\nredfin:/data/local/tmp \\# simpleperf inject -i branch_list.data\n```\n\nConvert ETM data for kernel:\n\n```sh\n# pull ETM data to host.\nhost $ adb pull /data/local/tmp/branch_list.data\n# download vmlinux and kernel modules to <binary_dir>\n# host simpleperf is in <aosp-top>/system/extras/simpleperf/scripts/bin/linux/x86_64/simpleperf,\n# or you can build simpleperf by `mmma system/extras/simpleperf`.\nhost $ simpleperf inject --symdir <binary_dir> -i branch_list.data\n```\n\nThe generated perf_inject.data may contain branch info for multiple binaries. But AutoFDO only\naccepts one at a time. So we need to split perf_inject.data.\nThe format of perf_inject.data is below:\n\n```perf_inject.data format\n\nexecuted range with count info for binary1\nbranch with count info for binary1\n// name for binary1\n\nexecuted range with count info for binary2\nbranch with count info for binary2\n// name for binary2\n\n...\n```\n\nWe need to split perf_inject.data, and make sure one file only contains info for one binary.\n\nThen we can use [AutoFDO](https://github.com/google/autofdo) to create profile like below:\n\n```sh\n# perf_inject_kernel.data is split from perf_inject.data, and only contains branch info for [kernel.kallsyms].\nhost $ autofdo/create_llvm_prof -profile perf_inject_kernel.data -profiler text -binary vmlinux -out a.prof -format binary\n```\n\nThen we can use a.prof for PGO during compilation, via `-fprofile-sample-use=a.prof`.\n[Here](https://clang.llvm.org/docs/UsersManual.html#using-sampling-profilers) are more details.\n\n## Collect ETM data with a daemon\n\nAndroid also has a daemon collecting ETM data periodically. It only runs on userdebug and eng\ndevices. The source code is in `<aosp-top>/system/extras/profcollectd`.\n\n## Support ETM in the kernel\n\nTo let simpleperf use ETM function, we need to enable Coresight driver in the kernel, which lives in\n`<linux_kernel>/drivers/hwtracing/coresight`.\n\nThe Coresight driver can be enabled by below kernel configs:\n\n```config\n\tCONFIG_CORESIGHT=y\n\tCONFIG_CORESIGHT_LINK_AND_SINK_TMC=y\n\tCONFIG_CORESIGHT_SOURCE_ETM4X=y\n\tCONFIG_CORESIGHT_DYNAMIC_REPLICATOR=y\n```\n\nOn Kernel 5.10+, we can build Coresight driver as kernel modules instead.\n\nAndroid common kernel 5.10+ should have all the Coresight patches needed. And we have backported\nnecessary Coresight patches to Android common kernel 4.14 and 4.19. Android common kernel 5.4\nmisses a few patches. Please create an [ndk issue](https://github.com/android/ndk/issues) if you\nneed ETM function on 5.4 kernel.\n\nBesides Coresight driver, we also need to add Coresight devices in device tree. An example is in\nhttps://github.com/torvalds/linux/blob/master/arch/arm64/boot/dts/arm/juno-base.dtsi. There should\nbe a path flowing ETM data from ETM device through funnels, ETF and replicators, all the way to\nETR, which writes ETM data to system memory.\n\n## Enable ETM in the bootloader\n\nUnless ARMv8.4 Self-hosted Trace extension is implemented, ETM is considered as an external debug\ninterface. It may be disabled by fuse (like JTAG). So we need to check if ETM is disabled, and\nif bootloader provides a way to reenable it.\n\nWe can tell if ETM is disable by checking its TRCAUTHSTATUS register, which is exposed in sysfs,\nlike /sys/bus/coresight/devices/coresight-etm0/mgmt/trcauthstatus. To reenable ETM, we need to\nenable non-Secure non-invasive debug on ARM CPU. The method depends on chip vendors(SOCs).\n\n\n## Related docs\n\n* [Arm Architecture Reference Manual Armv8, D3 AArch64 Self-hosted Trace](https://developer.arm.com/documentation/ddi0487/latest)\n* [ARM ETM Architecture Specification](https://developer.arm.com/documentation/ihi0064/latest/)\n* [ARM CoreSight Architecture Specification](https://developer.arm.com/documentation/ihi0029/latest)\n* [CoreSight Components Technical Reference Manual](https://developer.arm.com/documentation/ddi0314/h/)\n* [CoreSight Trace Memory Controller Technical Reference Manual](https://developer.arm.com/documentation/ddi0461/b/)\n* [OpenCSD library for decoding ETM data](https://github.com/Linaro/OpenCSD)\n* [AutoFDO tool for converting profile data](https://github.com/google/autofdo)\n"
  },
  {
    "path": "doc/debug_dwarf_unwinding.md",
    "content": "# Debug dwarf unwinding\n\nDwarf unwinding is the default way of getting call graphs in simpleperf. In this process,\nsimpleperf asks the kernel to add stack and register data to each sample. Then it uses\n[libunwindstack](https://cs.android.com/android/platform/superproject/+/master:system/unwinding/libunwindstack/)\nto unwind the call stack. libunwindstack uses dwarf sections (like .debug_frame or .eh_frame) in\nelf files to know how to unwind the stack.\n\nBy default, `simpleperf record` unwinds a sample before saving it to disk, to reduce space consumed\nby stack data. But this behavior makes it harder to reproduce unwinding problems. So we added\ndebug-unwind command, to help debug and profile dwarf unwinding. Below are two use cases.\n\n[TOC]\n\n## Debug failed unwinding cases\n\nUnwinding a sample can fail for different reasons: not enough stack or register data, unknown\nthread maps, no dwarf info, bugs in code, etc. And to fix them, we need to get error details\nand be able to reproduce them. simpleperf record cmd has two options for this:\n`--keep-failed-unwinding-result` keeps error code for failed unwinding samples. It's lightweight\nand gives us a brief idea why unwinding stops.\n`--keep-failed-unwinding-debug-info` keeps stack and register data for failed unwinding samples. It\ncan be used to reproduce the unwinding process given proper elf files. Below is an example.\n\n```sh\n# Run record cmd and keep failed unwinding debug info.\n$ simpleperf64 record --app com.example.android.displayingbitmaps -g --duration 10 \\\n    --keep-failed-unwinding-debug-info\n...\nsimpleperf I cmd_record.cpp:762] Samples recorded: 22026. Samples lost: 0.\n\n# Generate a text report containing failed unwinding cases.\n$ simpleperf debug-unwind --generate-report -o report.txt\n\n# Pull report.txt on host and show it using debug_unwind_reporter.py.\n# Show summary.\n$ debug_unwind_reporter.py -i report.txt --summary\n# Show summary of samples failed at a symbol.\n$ debug_unwind_reporter.py -i report.txt --summary --include-end-symbol SocketInputStream_socketRead0\n# Show details of samples failed at a symbol.\n$ debug_unwind_reporter.py -i report.txt --include-end-symbol SocketInputStream_socketRead0\n\n# Reproduce unwinding a failed case.\n$ simpleperf debug-unwind --unwind-sample --sample-time 256666343213301\n\n# Generate a test file containing a failed case and elf files for debugging it.\n$ simpleperf debug-unwind --generate-test-file --sample-time 256666343213301 --keep-binaries-in-test-file \\\n    /apex/com.android.runtime/lib64/bionic/libc.so,/apex/com.android.art/lib64/libopenjdk.so -o test.data\n```\n\n## Profile unwinding process\n\nWe can also record samples without unwinding them. Then we can use debug-unwind cmd to unwind the\nsamples after recording. Below is an example.\n\n```sh\n# Record samples without unwinding them.\n$ simpleperf record --app com.example.android.displayingbitmaps -g --duration 10 \\\n    --no-unwind\n...\nsimpleperf I cmd_record.cpp:762] Samples recorded: 9923. Samples lost: 0.\n\n# Use debug-unwind cmd to unwind samples.\n$ simpleperf debug-unwind --unwind-sample\n```\n\nWe can profile the unwinding process, get hot functions for improvement.\n\n```sh\n# Profile debug-unwind cmd.\n$ simpleperf record -g -o perf_unwind.data simpleperf debug-unwind --unwind-sample --skip-sample-print\n\n# Then pull perf_unwind.data and report it.\n$ report_html.py -i perf_unwind.data\n\n# We can also add source code annotation in report.html.\n$ binary_cache_builder.py -i perf_unwind.data -lib <path to aosp-master>/out/target/product/<device-name>/symbols/system\n$ report_html.py -i perf_unwind.data --add_source_code --source_dirs <path to aosp-master>/system/\n```\n"
  },
  {
    "path": "doc/executable_commands_reference.md",
    "content": "# Executable commands reference\n\n[TOC]\n\n## How simpleperf works\n\nModern CPUs have a hardware component called the performance monitoring unit (PMU). The PMU has\nseveral hardware counters, counting events like how many cpu cycles have happened, how many\ninstructions have executed, or how many cache misses have happened.\n\nThe Linux kernel wraps these hardware counters into hardware perf events. In addition, the Linux\nkernel also provides hardware independent software events and tracepoint events. The Linux kernel\nexposes all events to userspace via the perf_event_open system call, which is used by simpleperf.\n\nSimpleperf has three main commands: stat, record and report.\n\nThe stat command gives a summary of how many events have happened in the profiled processes in a\ntime period. Here’s how it works:\n1. Given user options, simpleperf enables profiling by making a system call to the kernel.\n2. The kernel enables counters while the profiled processes are running.\n3. After profiling, simpleperf reads counters from the kernel, and reports a counter summary.\n\nThe record command records samples of the profiled processes in a time period. Here’s how it works:\n1. Given user options, simpleperf enables profiling by making a system call to the kernel.\n2. Simpleperf creates mapped buffers between simpleperf and the kernel.\n3. The kernel enables counters while the profiled processes are running.\n4. Each time a given number of events happen, the kernel dumps a sample to the mapped buffers.\n5. Simpleperf reads samples from the mapped buffers and stores profiling data in a file called\n   perf.data.\n\nThe report command reads perf.data and any shared libraries used by the profiled processes,\nand outputs a report showing where the time was spent.\n\n## Commands\n\nSimpleperf supports several commands, listed below:\n\n```\nThe debug-unwind command: debug/test dwarf based offline unwinding, used for debugging simpleperf.\nThe dump command: dumps content in perf.data, used for debugging simpleperf.\nThe help command: prints help information for other commands.\nThe kmem command: collects kernel memory allocation information (will be replaced by Python scripts).\nThe list command: lists all event types supported on the Android device.\nThe record command: profiles processes and stores profiling data in perf.data.\nThe report command: reports profiling data in perf.data.\nThe report-sample command: reports each sample in perf.data, used for supporting integration of\n                           simpleperf in Android Studio.\nThe stat command: profiles processes and prints counter summary.\n\n```\n\nEach command supports different options, which can be seen through help message.\n\n```sh\n# List all commands.\n$ simpleperf --help\n\n# Print help message for record command.\n$ simpleperf record --help\n```\n\nBelow describes the most frequently used commands, which are list, stat, record and report.\n\n## The list command\n\nThe list command lists all events available on the device. Different devices may support different\nevents because they have different hardware and kernels.\n\n```sh\n$ simpleperf list\nList of hw-cache events:\n  branch-loads\n  ...\nList of hardware events:\n  cpu-cycles\n  instructions\n  ...\nList of software events:\n  cpu-clock\n  task-clock\n  ...\n```\n\nOn ARM/ARM64, the list command also shows a list of raw events, they are the events supported by\nthe ARM PMU on the device. The kernel has wrapped part of them into hardware events and hw-cache\nevents. For example, raw-cpu-cycles is wrapped into cpu-cycles, raw-instruction-retired is wrapped\ninto instructions. The raw events are provided in case we want to use some events supported on the\ndevice, but unfortunately not wrapped by the kernel.\n\n## The stat command\n\nThe stat command is used to get event counter values of the profiled processes. By passing options,\nwe can select which events to use, which processes/threads to monitor, how long to monitor and the\nprint interval.\n\n```sh\n# Stat using default events (cpu-cycles,instructions,...), and monitor process 7394 for 10 seconds.\n$ simpleperf stat -p 7394 --duration 10\nPerformance counter statistics:\n\n 1,320,496,145  cpu-cycles         # 0.131736 GHz                     (100%)\n   510,426,028  instructions       # 2.587047 cycles per instruction  (100%)\n     4,692,338  branch-misses      # 468.118 K/sec                    (100%)\n886.008130(ms)  task-clock         # 0.088390 cpus used               (100%)\n           753  context-switches   # 75.121 /sec                      (100%)\n           870  page-faults        # 86.793 /sec                      (100%)\n\nTotal test time: 10.023829 seconds.\n```\n\n### Select events to stat\n\nWe can select which events to use via -e.\n\n```sh\n# Stat event cpu-cycles.\n$ simpleperf stat -e cpu-cycles -p 11904 --duration 10\n\n# Stat event cache-references and cache-misses.\n$ simpleperf stat -e cache-references,cache-misses -p 11904 --duration 10\n```\n\nWhen running the stat command, if the number of hardware events is larger than the number of\nhardware counters available in the PMU, the kernel shares hardware counters between events, so each\nevent is only monitored for part of the total time. In the example below, there is a percentage at\nthe end of each row, showing the percentage of the total time that each event was actually\nmonitored.\n\n```sh\n# Stat using event cache-references, cache-references:u,....\n$ simpleperf stat -p 7394 -e cache-references,cache-references:u,cache-references:k \\\n      -e cache-misses,cache-misses:u,cache-misses:k,instructions --duration 1\nPerformance counter statistics:\n\n4,331,018  cache-references     # 4.861 M/sec    (87%)\n3,064,089  cache-references:u   # 3.439 M/sec    (87%)\n1,364,959  cache-references:k   # 1.532 M/sec    (87%)\n   91,721  cache-misses         # 102.918 K/sec  (87%)\n   45,735  cache-misses:u       # 51.327 K/sec   (87%)\n   38,447  cache-misses:k       # 43.131 K/sec   (87%)\n9,688,515  instructions         # 10.561 M/sec   (89%)\n\nTotal test time: 1.026802 seconds.\n```\n\nIn the example above, each event is monitored about 87% of the total time. But there is no\nguarantee that any pair of events are always monitored at the same time. If we want to have some\nevents monitored at the same time, we can use --group.\n\n```sh\n# Stat using event cache-references, cache-references:u,....\n$ simpleperf stat -p 7964 --group cache-references,cache-misses \\\n      --group cache-references:u,cache-misses:u --group cache-references:k,cache-misses:k \\\n      -e instructions --duration 1\nPerformance counter statistics:\n\n3,638,900  cache-references     # 4.786 M/sec          (74%)\n   65,171  cache-misses         # 1.790953% miss rate  (74%)\n2,390,433  cache-references:u   # 3.153 M/sec          (74%)\n   32,280  cache-misses:u       # 1.350383% miss rate  (74%)\n  879,035  cache-references:k   # 1.251 M/sec          (68%)\n   30,303  cache-misses:k       # 3.447303% miss rate  (68%)\n8,921,161  instructions         # 10.070 M/sec         (86%)\n\nTotal test time: 1.029843 seconds.\n```\n\n### Select target to stat\n\nWe can select which processes or threads to monitor via -p or -t. Monitoring a\nprocess is the same as monitoring all threads in the process. Simpleperf can also fork a child\nprocess to run the new command and then monitor the child process.\n\n```sh\n# Stat process 11904 and 11905.\n$ simpleperf stat -p 11904,11905 --duration 10\n\n# Stat thread 11904 and 11905.\n$ simpleperf stat -t 11904,11905 --duration 10\n\n# Start a child process running `ls`, and stat it.\n$ simpleperf stat ls\n\n# Stat the process of an Android application. This only works for debuggable apps on non-rooted\n# devices.\n$ simpleperf stat --app simpleperf.example.cpp\n\n# Stat system wide using -a.\n$ simpleperf stat -a --duration 10\n```\n\n### Decide how long to stat\n\nWhen monitoring existing threads, we can use --duration to decide how long to monitor. When\nmonitoring a child process running a new command, simpleperf monitors until the child process ends.\nIn this case, we can use Ctrl-C to stop monitoring at any time.\n\n```sh\n# Stat process 11904 for 10 seconds.\n$ simpleperf stat -p 11904 --duration 10\n\n# Stat until the child process running `ls` finishes.\n$ simpleperf stat ls\n\n# Stop monitoring using Ctrl-C.\n$ simpleperf stat -p 11904 --duration 10\n^C\n```\n\nIf you want to write a script to control how long to monitor, you can send one of SIGINT, SIGTERM,\nSIGHUP signals to simpleperf to stop monitoring.\n\n### Decide the print interval\n\nWhen monitoring perf counters, we can also use --interval to decide the print interval.\n\n```sh\n# Print stat for process 11904 every 300ms.\n$ simpleperf stat -p 11904 --duration 10 --interval 300\n\n# Print system wide stat at interval of 300ms for 10 seconds. Note that system wide profiling needs\n# root privilege.\n$ su 0 simpleperf stat -a --duration 10 --interval 300\n```\n\n### Display counters in systrace\n\nSimpleperf can also work with systrace to dump counters in the collected trace. Below is an example\nto do a system wide stat.\n\n```sh\n# Capture instructions (kernel only) and cache misses with interval of 300 milliseconds for 15\n# seconds.\n$ su 0 simpleperf stat -e instructions:k,cache-misses -a --interval 300 --duration 15\n# On host launch systrace to collect trace for 10 seconds.\n(HOST)$ external/chromium-trace/systrace.py --time=10 -o new.html sched gfx view\n# Open the collected new.html in browser and perf counters will be shown up.\n```\n\n### Show event count per thread\n\nBy default, stat cmd outputs an event count sum for all monitored targets. But when `--per-thread`\noption is used, stat cmd outputs an event count for each thread in monitored targets. It can be\nused to find busy threads in a process or system wide. With `--per-thread` option, stat cmd opens\na perf_event_file for each exisiting thread. If a monitored thread creates new threads, event\ncount for new threads will be added to the monitored thread by default, otherwise omitted if\n`--no-inherit` option is also used.\n\n```sh\n# Print event counts for each thread in process 11904. Event counts for threads created after\n# stat cmd will be added to threads creating them.\n$ simpleperf stat --per-thread -p 11904 --duration 1\n\n# Print event counts for all threads running in the system every 1s. Threads not running will not\n# be reported.\n$ su 0 simpleperf stat --per-thread -a --interval 1000 --interval-only-values\n\n# Print event counts for all threads running in the system every 1s. Event counts for threads\n# created after stat cmd will be omitted.\n$ su 0 simpleperf stat --per-thread -a --interval 1000 --interval-only-values --no-inherit\n```\n\n### Show event count per core\n\nBy default, stat cmd outputs an event count sum for all monitored cpu cores. But when `--per-core`\noption is used, stat cmd outputs an event count for each core. It can be used to see how events\nare distributed on different cores.\nWhen stating non-system wide with `--per-core` option, simpleperf creates a perf event for each\nmonitored thread on each core. When a thread is in running state, perf events on all cores are\nenabled, but only the perf event on the core running the thread is in running state. So the\npercentage comment shows runtime_on_a_core / runtime_on_all_cores. Note that, percentage is still\naffected by hardware counter multiplexing. Check simpleperf log output for ways to distinguish it.\n\n```sh\n# Print event counts for each cpu running threads in process 11904.\n# A percentage shows runtime_on_a_cpu / runtime_on_all_cpus.\n$ simpleperf stat --per-core -p 11904 --duration 1\nPerformance counter statistics:\n\n# cpu       count  event_name   # percentage = event_run_time / enabled_time\n  7    56,552,838  cpu-cycles   #   (60%)\n  3    25,958,605  cpu-cycles   #   (20%)\n  0    22,822,698  cpu-cycles   #   (15%)\n  1     6,661,495  cpu-cycles   #   (5%)\n  4     1,519,093  cpu-cycles   #   (0%)\n\nTotal test time: 1.001082 seconds.\n\n# Print event counts for each cpu system wide.\n$ su 0 simpleperf stat --per-core -a --duration 1\n\n# Print cpu-cycle event counts for each cpu for each thread running in the system.\n$ su 0 simpleperf stat -e cpu-cycles -a --per-thread --per-core --duration 1\n```\n\n## The record command\n\nThe record command is used to dump samples of the profiled processes. Each sample can contain\ninformation like the time at which the sample was generated, the number of events since last\nsample, the program counter of a thread, the call chain of a thread.\n\nBy passing options, we can select which events to use, which processes/threads to monitor,\nwhat frequency to dump samples, how long to monitor, and where to store samples.\n\n```sh\n# Record on process 7394 for 10 seconds, using default event (cpu-cycles), using default sample\n# frequency (4000 samples per second), writing records to perf.data.\n$ simpleperf record -p 7394 --duration 10\nsimpleperf I cmd_record.cpp:316] Samples recorded: 21430. Samples lost: 0.\n```\n\n### Select events to record\n\nBy default, the cpu-cycles event is used to evaluate consumed cpu cycles. But we can also use other\nevents via -e.\n\n```sh\n# Record using event instructions.\n$ simpleperf record -e instructions -p 11904 --duration 10\n\n# Record using task-clock, which shows the passed CPU time in nanoseconds.\n$ simpleperf record -e task-clock -p 11904 --duration 10\n```\n\n### Select target to record\n\nThe way to select target in record command is similar to that in the stat command.\n\n```sh\n# Record process 11904 and 11905.\n$ simpleperf record -p 11904,11905 --duration 10\n\n# Record thread 11904 and 11905.\n$ simpleperf record -t 11904,11905 --duration 10\n\n# Record a child process running `ls`.\n$ simpleperf record ls\n\n# Record the process of an Android application. This only works for debuggable apps on non-rooted\n# devices.\n$ simpleperf record --app simpleperf.example.cpp\n\n# Record system wide.\n$ simpleperf record -a --duration 10\n```\n\n### Set the frequency to record\n\nWe can set the frequency to dump records via -f or -c. For example, -f 4000 means\ndumping approximately 4000 records every second when the monitored thread runs. If a monitored\nthread runs 0.2s in one second (it can be preempted or blocked in other times), simpleperf dumps\nabout 4000 * 0.2 / 1.0 = 800 records every second. Another way is using -c. For example, -c 10000\nmeans dumping one record whenever 10000 events happen.\n\n```sh\n# Record with sample frequency 1000: sample 1000 times every second running.\n$ simpleperf record -f 1000 -p 11904,11905 --duration 10\n\n# Record with sample period 100000: sample 1 time every 100000 events.\n$ simpleperf record -c 100000 -t 11904,11905 --duration 10\n```\n\nTo avoid taking too much time generating samples, kernel >= 3.10 sets the max percent of cpu time\nused for generating samples (default is 25%), and decreases the max allowed sample frequency when\nhitting that limit. Simpleperf uses --cpu-percent option to adjust it, but it needs either root\nprivilege or to be on Android >= Q.\n\n```sh\n# Record with sample frequency 10000, with max allowed cpu percent to be 50%.\n$ simpleperf record -f 1000 -p 11904,11905 --duration 10 --cpu-percent 50\n```\n\n### Decide how long to record\n\nThe way to decide how long to monitor in record command is similar to that in the stat command.\n\n```sh\n# Record process 11904 for 10 seconds.\n$ simpleperf record -p 11904 --duration 10\n\n# Record until the child process running `ls` finishes.\n$ simpleperf record ls\n\n# Stop monitoring using Ctrl-C.\n$ simpleperf record -p 11904 --duration 10\n^C\n```\n\nIf you want to write a script to control how long to monitor, you can send one of SIGINT, SIGTERM,\nSIGHUP signals to simpleperf to stop monitoring.\n\n### Set the path to store profiling data\n\nBy default, simpleperf stores profiling data in perf.data in the current directory. But the path\ncan be changed using -o.\n\n```sh\n# Write records to data/perf2.data.\n$ simpleperf record -p 11904 -o data/perf2.data --duration 10\n```\n\n#### Record call graphs\n\nA call graph is a tree showing function call relations. Below is an example.\n\n```\nmain() {\n    FunctionOne();\n    FunctionTwo();\n}\nFunctionOne() {\n    FunctionTwo();\n    FunctionThree();\n}\na call graph:\n    main-> FunctionOne\n       |    |\n       |    |-> FunctionTwo\n       |    |-> FunctionThree\n       |\n       |-> FunctionTwo\n```\n\nA call graph shows how a function calls other functions, and a reversed call graph shows how\na function is called by other functions. To show a call graph, we need to first record it, then\nreport it.\n\nThere are two ways to record a call graph, one is recording a dwarf based call graph, the other is\nrecording a stack frame based call graph. Recording dwarf based call graphs needs support of debug\ninformation in native binaries. While recording stack frame based call graphs needs support of\nstack frame registers.\n\n```sh\n# Record a dwarf based call graph\n$ simpleperf record -p 11904 -g --duration 10\n\n# Record a stack frame based call graph\n$ simpleperf record -p 11904 --call-graph fp --duration 10\n```\n\n[Here](README.md#suggestions-about-recording-call-graphs) are some suggestions about recording call graphs.\n\n### Record both on CPU time and off CPU time\n\nSimpleperf is a CPU profiler, which generates samples for a thread only when it is running on a\nCPU. But sometimes we want to know where the thread time is spent off-cpu (like preempted by other\nthreads, blocked in IO or waiting for some events). To support this, simpleperf added a\n--trace-offcpu option to the record command. When --trace-offcpu is used, simpleperf does the\nfollowing things:\n\n1) Only cpu-clock/task-clock event is allowed to be used with --trace-offcpu. This let simpleperf\n   generate on-cpu samples for cpu-clock event.\n2) Simpleperf also monitors sched:sched_switch event, which will generate a sched_switch sample\n   each time the monitored thread is scheduled off cpu.\n3) Simpleperf also records context switch records. So it knows when the thread is scheduled back on\n   a cpu.\n\nThe samples and context switch records collected by simpleperf for a thread are shown below:\n\n![simpleperf_trace_offcpu_sample_mode](simpleperf_trace_offcpu_sample_mode.png)\n\nHere we have two types of samples:\n1) on-cpu samples generated for cpu-clock event. The period value in each sample means how many\n   nanoseconds are spent on cpu (for the callchain of this sample).\n2) off-cpu (sched_switch) samples generated for sched:sched_switch event. The period value is\n   calculated as **Timestamp of the next switch on record** minus **Timestamp of the current sample**\n   by simpleperf. So the period value in each sample means how many nanoseconds are spent off cpu\n   (for the callchain of this sample).\n\n**note**: In reality, switch on records and samples may lost. To mitigate the loss of accuracy, we\ncalculate the period of an off-cpu sample as **Timestamp of the next switch on record or sample**\nminus **Timestamp of the current sample**.\n\nWhen reporting via python scripts, simpleperf_report_lib.py provides SetTraceOffCpuMode() method\nto control how to report the samples:\n1) on-cpu mode: only report on-cpu samples.\n2) off-cpu mode: only report off-cpu samples.\n3) on-off-cpu mode: report both on-cpu and off-cpu samples, which can be split by event name.\n4) mixed-on-off-cpu mode: report on-cpu and off-cpu samples under the same event name.\n\nIf not set, mixed-on-off-cpu mode will be used to report.\n\nWhen using report_html.py, inferno and report_sample.py, the report mode can be set by\n--trace-offcpu option.\n\nBelow are some examples recording and reporting trace offcpu profiles.\n\n```sh\n# Check if --trace-offcpu is supported by the kernel (should be available on kernel >= 4.2).\n$ simpleperf list --show-features\ntrace-offcpu\n...\n\n# Record with --trace-offcpu.\n$ simpleperf record -g -p 11904 --duration 10 --trace-offcpu -e cpu-clock\n\n# Record system wide with --trace-offcpu.\n$ simpleperf record -a -g --duration 3 --trace-offcpu -e cpu-clock\n\n# Record with --trace-offcpu using app_profiler.py.\n$ ./app_profiler.py -p com.google.samples.apps.sunflower \\\n    -r \"-g -e cpu-clock:u --duration 10 --trace-offcpu\"\n\n# Report on-cpu samples.\n$ ./report_html.py --trace-offcpu on-cpu\n# Report off-cpu samples.\n$ ./report_html.py --trace-offcpu off-cpu\n# Report on-cpu and off-cpu samples under different event names.\n$ ./report_html.py --trace-offcpu on-off-cpu\n# Report on-cpu and off-cpu samples under the same event name.\n$ ./report_html.py --trace-offcpu mixed-on-off-cpu\n```\n\n## The report command\n\nThe report command is used to report profiling data generated by the record command. The report\ncontains a table of sample entries. Each sample entry is a row in the report. The report command\ngroups samples belong to the same process, thread, library, function in the same sample entry. Then\nsort the sample entries based on the event count a sample entry has.\n\nBy passing options, we can decide how to filter out uninteresting samples, how to group samples\ninto sample entries, and where to find profiling data and binaries.\n\nBelow is an example. Records are grouped into 4 sample entries, each entry is a row. There are\nseveral columns, each column shows piece of information belonging to a sample entry. The first\ncolumn is Overhead, which shows the percentage of events inside the current sample entry in total\nevents. As the perf event is cpu-cycles, the overhead is the percentage of CPU cycles used in each\nfunction.\n\n```sh\n# Reports perf.data, using only records sampled in libsudo-game-jni.so, grouping records using\n# thread name(comm), process id(pid), thread id(tid), function name(symbol), and showing sample\n# count for each row.\n$ simpleperf report --dsos /data/app/com.example.sudogame-2/lib/arm64/libsudo-game-jni.so \\\n      --sort comm,pid,tid,symbol -n\nCmdline: /data/data/com.example.sudogame/simpleperf record -p 7394 --duration 10\nArch: arm64\nEvent: cpu-cycles (type 0, config 0)\nSamples: 28235\nEvent count: 546356211\n\nOverhead  Sample  Command    Pid   Tid   Symbol\n59.25%    16680   sudogame  7394  7394  checkValid(Board const&, int, int)\n20.42%    5620    sudogame  7394  7394  canFindSolution_r(Board&, int, int)\n13.82%    4088    sudogame  7394  7394  randomBlock_r(Board&, int, int, int, int, int)\n6.24%     1756    sudogame  7394  7394  @plt\n```\n\n### Set the path to read profiling data\n\nBy default, the report command reads profiling data from perf.data in the current directory.\nBut the path can be changed using -i.\n\n```sh\n$ simpleperf report -i data/perf2.data\n```\n\n### Set the path to find binaries\n\nTo report function symbols, simpleperf needs to read executable binaries used by the monitored\nprocesses to get symbol table and debug information. By default, the paths are the executable\nbinaries used by monitored processes while recording. However, these binaries may not exist when\nreporting or not contain symbol table and debug information. So we can use --symfs to redirect\nthe paths.\n\n```sh\n# In this case, when simpleperf wants to read executable binary /A/b, it reads file in /A/b.\n$ simpleperf report\n\n# In this case, when simpleperf wants to read executable binary /A/b, it prefers file in\n# /debug_dir/A/b to file in /A/b.\n$ simpleperf report --symfs /debug_dir\n\n# Read symbols for system libraries built locally. Note that this is not needed since Android O,\n# which ships symbols for system libraries on device.\n$ simpleperf report --symfs $ANDROID_PRODUCT_OUT/symbols\n```\n\n### Filter samples\n\nWhen reporting, it happens that not all records are of interest. The report command supports four\nfilters to select samples of interest.\n\n```sh\n# Report records in threads having name sudogame.\n$ simpleperf report --comms sudogame\n\n# Report records in process 7394 or 7395\n$ simpleperf report --pids 7394,7395\n\n# Report records in thread 7394 or 7395.\n$ simpleperf report --tids 7394,7395\n\n# Report records in libsudo-game-jni.so.\n$ simpleperf report --dsos /data/app/com.example.sudogame-2/lib/arm64/libsudo-game-jni.so\n```\n\n### Group samples into sample entries\n\nThe report command uses --sort to decide how to group sample entries.\n\n```sh\n# Group records based on their process id: records having the same process id are in the same\n# sample entry.\n$ simpleperf report --sort pid\n\n# Group records based on their thread id and thread comm: records having the same thread id and\n# thread name are in the same sample entry.\n$ simpleperf report --sort tid,comm\n\n# Group records based on their binary and function: records in the same binary and function are in\n# the same sample entry.\n$ simpleperf report --sort dso,symbol\n\n# Default option: --sort comm,pid,tid,dso,symbol. Group records in the same thread, and belong to\n# the same function in the same binary.\n$ simpleperf report\n```\n\n#### Report call graphs\n\nTo report a call graph, please make sure the profiling data is recorded with call graphs,\nas [here](#record-call-graphs).\n\n```\n$ simpleperf report -g\n```\n"
  },
  {
    "path": "doc/inferno.md",
    "content": "# Inferno\n\n![logo](./inferno_small.png)\n\n[TOC]\n\n## Description\n\nInferno is a flamegraph generator for native (C/C++) Android apps. It was\noriginally written to profile and improve surfaceflinger performance\n(Android compositor) but it can be used for any native Android application\n. You can see a sample report generated with Inferno\n[here](./report.html). Report are self-contained in HTML so they can be\nexchanged easily.\n\nNotice there is no concept of time in a flame graph since all callstack are\nmerged together. As a result, the width of a flamegraph represents 100% of\nthe number of samples and the height is related to the number of functions on\nthe stack when sampling occurred.\n\n\n![flamegraph sample](./main_thread_flamegraph.png)\n\nIn the flamegraph featured above you can see the main thread of SurfaceFlinger.\nIt is immediatly apparent that most of the CPU time is spent processing messages\n`android::SurfaceFlinger::onMessageReceived`. The most expensive task is to ask\n the screen to be refreshed as `android::DisplayDevice::prepare` shows in orange\n. This graphic division helps to see what part of the program is costly and\nwhere a developer's effort to improve performances should go.\n\n## Example of bottleneck\n\nA flamegraph give you instant vision on the CPU cycles cost centers but\nit can also be used to find specific offenders. To find them, look for\nplateaus. It is easier to see an example:\n\n![flamegraph sample](./bottleneck.png)\n\nIn the previous flamegraph, two\nplateaus (due to `android::BufferQueueCore::validateConsistencyLocked`)\nare immediately apparent.\n\n## How it works\n\nInferno relies on simpleperf to record the callstack of a native application\nthousands of times per second. Simpleperf takes care of unwinding the stack\neither using frame pointer (recommended) or dwarf. At the end of the recording\n`simpleperf` also symbolize all IPs automatically. The record are aggregated and\ndumps dumped to a file `perf.data`. This file is pulled from the Android device\nand processed on the host by Inferno. The callstacks are merged together to\nvisualize in which part of an app the CPU cycles are spent.\n\n## How to use it\n\nOpen a terminal and from `simpleperf/scripts` directory type:\n```\n./inferno.sh  (on Linux/Mac)\ninferno.bat (on Windows)\n```\n\nInferno will collect data, process them and automatically open your web browser\nto display the HTML report.\n\n## Parameters\n\nYou can select how long to sample for, the color of the node and many other\nthings. Use `-h` to get a list of all supported parameters.\n\n```\n./inferno.sh -h\n```\n\n## Troubleshooting\n\n### Messy flame graph\n\nA healthy flame graph features a single call site at its base (see [here](./report.html)).\nIf you don't see a unique call site like `_start` or `_start_thread` at the base\nfrom which all flames originate, something went wrong. : Stack unwinding may\nfail to reach the root callsite. These incomplete\ncallstack are impossible to merge properly. By default Inferno asks\n `simpleperf` to unwind the stack via the kernel and frame pointers. Try to\n perform unwinding with dwarf `-du`, you can further tune this setting.\n\n\n### No flames\n\nIf you see no flames at all or a mess of 1 level flame without a common base,\nthis may be because you compiled without frame pointers. Make sure there is no\n` -fomit-frame-pointer` in your build config. Alternatively, ask simpleperf to\ncollect data with dward unwinding `-du`.\n\n\n\n### High percentage of lost samples\n\nIf simpleperf reports a lot of lost sample it is probably because you are\nunwinding with `dwarf`. Dwarf unwinding involves copying the stack before it is\nprocessed. Try to use frame pointer unwinding which can be done by the kernel\nand it much faster.\n\nThe cost of frame pointer is negligible on arm64 parameter but considerable\n on arm 32-bit arch (due to register pressure). Use a 64-bit build for better\n profiling.\n\n### run-as: package not debuggable\n\nIf you cannot run as root, make sure the app is debuggable otherwise simpleperf\nwill not be able to profile it.\n"
  },
  {
    "path": "doc/jit_symbols.md",
    "content": "# JIT symbols\n\n[TOC]\n\n## Java JIT symbols\n\nOn Android >= P, simpleperf supports profiling Java code, no matter whether it is executed by\nthe interpreter, or JITed, or compiled into native instructions. So you don't need to do anything.\n\nFor details on Android O and N, see\n[android_application_profiling.md](./android_application_profiling.md#prepare-an-android-application).\n\n## Generic JIT symbols\n\nSimpleperf supports picking up symbols from per-pid symbol map files, somewhat similar to what\nLinux kernel perftool does. Application should create those files at specific locations.\n\n### Symbol map file location for application\n\nApplication should create symbol map files in its data directory.\n\nFor example, process `123` of application `foo.bar.baz` should create\n`/data/data/foo.bar.baz/perf-123.map`.\n\n### Symbol map file location for standalone program\n\nStandalone programs should create symbol map files in `/data/local/tmp`.\n\nFor example, standalone program process `123` should create `/data/local/tmp/perf-123.map`.\n\n### Symbol map file format\n\nSymbol map file is a text file.\n\nEvery line describes a new symbol. Line format is:\n```\n<symbol-absolute-address> <symbol-size> <symbol-name>\n```\n\nFor example:\n```\n0x10000000 0x16 jit_symbol_one\n0x20000000 0x332 jit_symbol_two\n0x20002004 0x8 jit_symbol_three\n```\n\n### Known issues\n\nCurrent implementation gets confused if memory pages where JIT symbols reside are reused by mapping\na file either before or after.\n\nFor example, if memory pages were first used by `dlopen(\"libfoo.so\")`, then freed by `dlclose`,\nthen allocated for JIT symbols - simpleperf will report symbols from `libfoo.so` instead.\n"
  },
  {
    "path": "doc/sample_filter.md",
    "content": "# Sample Filter\n\nSometimes we want to report samples only for selected processes, threads, libraries, or time\nranges. To filter samples, we can pass filter options to the report commands or scripts.\n\n\n## filter file format\n\nTo filter samples based on time ranges, simpleperf accepts a filter file when reporting. The filter\nfile is in text format, containing a list of lines. Each line is a filter command.\n\n```\nfilter_command1 command_args\nfilter_command2 command_args\n...\n```\n\n### clock command\n\n```\nCLOCK <clock_name>\n```\n\nSet the clock used to generate timestamps in the filter file. Supported clocks are: `monotonic`,\n`realtime`. By default it is monotonic. The clock here should be the same as the clock used in\nprofile data, which is set by `--clockid` in simpleperf record command.\n\n### global time filter commands\n\n```\nGLOBAL_BEGIN <begin_timestamp>\nGLOBAL_END <end_timestamp>\n```\n\nThe nearest pair of GLOBAL_BEGIN and GLOBAL_END commands makes a time range. When these commands\nare used, only samples in the time ranges are reported. Timestamps are 64-bit integers in\nnanoseconds.\n\n```\nGLOBAL_BEGIN 1000\nGLOBAL_END 2000\nGLOBAL_BEGIN 3000\nGLOBAL_BEGIN 4000\n```\n\nFor the example above, samples in time ranges [1000, 2000) and [3000, 4000) are reported.\n\n### process time filter commands\n\n```\nPROCESS_BEGIN <pid> <begin_timestamp>\nPROCESS_END <pid> <end_timestamp>\n```\n\nThe nearest pair of PROCESS_BEGIN and PROCESS_END commands for the same process makes a time\nrange. When these commands are used, each process has a list of time ranges, and only samples\nin the time ranges are reported.\n\n```\nPROCESS_BEGIN 1 1000\nPROCESS_BEGIN 2 2000\nPROCESS_END 1 3000\nPROCESS_END 2 4000\n```\n\nFor the example above, process 1 samples in time range [1000, 3000) and process 2 samples in time\nrange [2000, 4000) are reported.\n\n### thread time filter commands\n\n```\nTHREAD_BEGIN <tid> <begin_timestamp>\nTHREAD_END <tid> <end_timestamp>\n```\n\nThe nearest pair of THREAD_BEGIN and THREAD_END commands for the same thread makes a time\nrange. When these commands are used, each thread has a list of time ranges, and only samples in the\ntime ranges are reported.\n\n```\nTHREAD_BEGIN 1 1000\nTHREAD_BEGIN 2 2000\nTHREAD_END 1 3000\nTHREAD_END 2 4000\n```\n\nFor the example above, thread 1 samples in time range [1000, 3000) and thread 2 samples in time\nrange [2000, 4000) are reported.\n"
  },
  {
    "path": "doc/scripts_reference.md",
    "content": "# Scripts reference\n\n[TOC]\n\n## Record a profile\n\n### app_profiler.py\n\n`app_profiler.py` is used to record profiling data for Android applications and native executables.\n\n```sh\n# Record an Android application.\n$ ./app_profiler.py -p simpleperf.example.cpp\n\n# Record an Android application with Java code compiled into native instructions.\n$ ./app_profiler.py -p simpleperf.example.cpp --compile_java_code\n\n# Record the launch of an Activity of an Android application.\n$ ./app_profiler.py -p simpleperf.example.cpp -a .SleepActivity\n\n# Record a native process.\n$ ./app_profiler.py -np surfaceflinger\n\n# Record a native process given its pid.\n$ ./app_profiler.py --pid 11324\n\n# Record a command.\n$ ./app_profiler.py -cmd \\\n    \"dex2oat --dex-file=/data/local/tmp/app-debug.apk --oat-file=/data/local/tmp/a.oat\"\n\n# Record an Android application, and use -r to send custom options to the record command.\n$ ./app_profiler.py -p simpleperf.example.cpp \\\n    -r \"-e cpu-clock -g --duration 30\"\n\n# Record both on CPU time and off CPU time.\n$ ./app_profiler.py -p simpleperf.example.cpp \\\n    -r \"-e task-clock -g -f 1000 --duration 10 --trace-offcpu\"\n\n# Save profiling data in a custom file (like perf_custom.data) instead of perf.data.\n$ ./app_profiler.py -p simpleperf.example.cpp -o perf_custom.data\n```\n\n### Profile from launch of an application\n\nSometimes we want to profile the launch-time of an application. To support this, we added `--app` in\nthe record command. The `--app` option sets the package name of the Android application to profile.\nIf the app is not already running, the record command will poll for the app process in a loop with\nan interval of 1ms. So to profile from launch of an application, we can first start the record\ncommand with `--app`, then start the app. Below is an example.\n\n```sh\n$ ./run_simpleperf_on_device.py record --app simpleperf.example.cpp \\\n    -g --duration 1 -o /data/local/tmp/perf.data\n# Start the app manually or using the `am` command.\n```\n\nTo make it convenient to use, `app_profiler.py` supports using the `-a` option to start an Activity\nafter recording has started.\n\n```sh\n$ ./app_profiler.py -p simpleperf.example.cpp -a .MainActivity\n```\n\n### api_profiler.py\n\n`api_profiler.py` is used to control recording in application code. It does preparation work\nbefore recording, and collects profiling data files after recording.\n\n[Here](./android_application_profiling.md#control-recording-in-application-code) are the details.\n\n### run_simpleperf_without_usb_connection.py\n\n`run_simpleperf_without_usb_connection.py` records profiling data while the USB cable isn't\nconnected. Maybe `api_profiler.py` is more suitable, which also don't need USB cable when recording.\nBelow is an example.\n\n```sh\n$ ./run_simpleperf_without_usb_connection.py start -p simpleperf.example.cpp\n# After the command finishes successfully, unplug the USB cable, run the\n# SimpleperfExampleCpp app. After a few seconds, plug in the USB cable.\n$ ./run_simpleperf_without_usb_connection.py stop\n# It may take a while to stop recording. After that, the profiling data is collected in perf.data\n# on host.\n```\n\n### binary_cache_builder.py\n\nThe `binary_cache` directory is a directory holding binaries needed by a profiling data file. The\nbinaries are expected to be unstripped, having debug information and symbol tables. The\n`binary_cache` directory is used by report scripts to read symbols of binaries. It is also used by\n`report_html.py` to generate annotated source code and disassembly.\n\nBy default, `app_profiler.py` builds the binary_cache directory after recording. But we can also\nbuild `binary_cache` for existing profiling data files using `binary_cache_builder.py`. It is useful\nwhen you record profiling data using `simpleperf record` directly, to do system wide profiling or\nrecord without the USB cable connected.\n\n`binary_cache_builder.py` can either pull binaries from an Android device, or find binaries in\ndirectories on the host (via `-lib`).\n\n```sh\n# Generate binary_cache for perf.data, by pulling binaries from the device.\n$ ./binary_cache_builder.py\n\n# Generate binary_cache, by pulling binaries from the device and finding binaries in\n# SimpleperfExampleCpp.\n$ ./binary_cache_builder.py -lib path_of_SimpleperfExampleCpp\n```\n\n### run_simpleperf_on_device.py\n\nThis script pushes the `simpleperf` executable on the device, and run a simpleperf command on the\ndevice. It is more convenient than running adb commands manually.\n\n## Viewing the profile\n\n### report.py\n\nreport.py is a wrapper of the `report` command on the host. It accepts all options of the `report`\ncommand.\n\n```sh\n# Report call graph\n$ ./report.py -g\n\n# Report call graph in a GUI window implemented by Python Tk.\n$ ./report.py -g --gui\n```\n\n### report_html.py\n\n`report_html.py` generates `report.html` based on the profiling data. Then the `report.html` can show\nthe profiling result without depending on other files. So it can be shown in local browsers or\npassed to other machines. Depending on which command-line options are used, the content of the\n`report.html` can include: chart statistics, sample table, flamegraphs, annotated source code for\neach function, annotated disassembly for each function.\n\n```sh\n# Generate chart statistics, sample table and flamegraphs, based on perf.data.\n$ ./report_html.py\n\n# Add source code.\n$ ./report_html.py --add_source_code --source_dirs path_of_SimpleperfExampleCpp\n\n# Add disassembly.\n$ ./report_html.py --add_disassembly\n\n# Adding disassembly for all binaries can cost a lot of time. So we can choose to only add\n# disassembly for selected binaries.\n$ ./report_html.py --add_disassembly --binary_filter libgame.so\n\n# report_html.py accepts more than one recording data file.\n$ ./report_html.py -i perf1.data perf2.data\n```\n\nBelow is an example of generating html profiling results for SimpleperfExampleCpp.\n\n```sh\n$ ./app_profiler.py -p simpleperf.example.cpp\n$ ./report_html.py --add_source_code --source_dirs path_of_SimpleperfExampleCpp \\\n    --add_disassembly\n```\n\nAfter opening the generated [`report.html`](./report_html.html) in a browser, there are several tabs:\n\nThe first tab is \"Chart Statistics\". You can click the pie chart to show the time consumed by each\nprocess, thread, library and function.\n\nThe second tab is \"Sample Table\". It shows the time taken by each function. By clicking one row in\nthe table, we can jump to a new tab called \"Function\".\n\nThe third tab is \"Flamegraph\". It shows the graphs generated by [`inferno`](./inferno.md).\n\nThe fourth tab is \"Function\". It only appears when users click a row in the \"Sample Table\" tab.\nIt shows information of a function, including:\n\n1. A flamegraph showing functions called by that function.\n2. A flamegraph showing functions calling that function.\n3. Annotated source code of that function. It only appears when there are source code files for\n   that function.\n4. Annotated disassembly of that function. It only appears when there are binaries containing that\n   function.\n\n### inferno\n\n[`inferno`](./inferno.md) is a tool used to generate flamegraph in a html file.\n\n```sh\n# Generate flamegraph based on perf.data.\n# On Windows, use inferno.bat instead of ./inferno.sh.\n$ ./inferno.sh -sc --record_file perf.data\n\n# Record a native program and generate flamegraph.\n$ ./inferno.sh -np surfaceflinger\n```\n\n### purgatorio\n\n[`purgatorio`](../scripts/purgatorio/README.md) is a visualization tool to show samples in time order.\n\n### pprof_proto_generator.py\n\nIt converts a profiling data file into `pprof.proto`, a format used by [pprof](https://github.com/google/pprof).\n\n```sh\n# Convert perf.data in the current directory to pprof.proto format.\n$ ./pprof_proto_generator.py\n# Show report in pdf format.\n$ pprof -pdf pprof.profile\n\n# Show report in html format. To show disassembly, add --tools option like:\n#  --tools=objdump:<ndk_path>/toolchains/llvm/prebuilt/linux-x86_64/aarch64-linux-android/bin\n# To show annotated source or disassembly, select `top` in the view menu, click a function and\n# select `source` or `disassemble` in the view menu.\n$ pprof -http=:8080 pprof.profile\n```\n\n### gecko_profile_generator.py\n\nConverts `perf.data` to [Gecko Profile\nFormat](https://github.com/firefox-devtools/profiler/blob/main/docs-developer/gecko-profile-format.md),\nthe format read by https://profiler.firefox.com/.\n\nFirefox Profiler is a powerful general-purpose profiler UI which runs locally in\nany browser (not just Firefox), with:\n\n- Per-thread tracks\n- Flamegraphs\n- Search, focus for specific stacks\n- A time series view for seeing your samples in timestamp order\n- Filtering by thread and duration\n\nUsage:\n\n```\n# Record a profile of your application\n$ ./app_profiler.py -p simpleperf.example.cpp\n\n# Convert and gzip.\n$ ./gecko_profile_generator.py -i perf.data | gzip > gecko-profile.json.gz\n```\n\nThen open `gecko-profile.json.gz` in https://profiler.firefox.com/.\n\n### report_sample.py\n\n`report_sample.py` converts a profiling data file into the `perf script` text format output by\n`linux-perf-tool`.\n\nThis format can be imported into:\n\n- [FlameGraph](https://github.com/brendangregg/FlameGraph)\n- [Flamescope](https://github.com/Netflix/flamescope)\n- [Firefox\n  Profiler](https://github.com/firefox-devtools/profiler/blob/main/docs-user/guide-perf-profiling.md),\n  but prefer using `gecko_profile_generator.py`.\n- [Speedscope](https://github.com/jlfwong/speedscope/wiki/Importing-from-perf-(linux))\n\n```sh\n# Record a profile to perf.data\n$ ./app_profiler.py <args>\n\n# Convert perf.data in the current directory to a format used by FlameGraph.\n$ ./report_sample.py --symfs binary_cache >out.perf\n\n$ git clone https://github.com/brendangregg/FlameGraph.git\n$ FlameGraph/stackcollapse-perf.pl out.perf >out.folded\n$ FlameGraph/flamegraph.pl out.folded >a.svg\n```\n\n### stackcollapse.py\n\n`stackcollapse.py` converts a profiling data file (`perf.data`) to [Brendan\nGregg's \"Folded Stacks\"\nformat](https://queue.acm.org/detail.cfm?id=2927301#:~:text=The%20folded%20stack%2Dtrace%20format,trace%2C%20followed%20by%20a%20semicolon).\n\nFolded Stacks are lines of semicolon-delimited stack frames, root to leaf,\nfollowed by a count of events sampled in that stack, e.g.:\n\n```\nBusyThread;__start_thread;__pthread_start(void*);java.lang.Thread.run 17889729\n```\n\nAll similar stacks are aggregated and sample timestamps are unused.\n\nFolded Stacks format is readable by:\n\n- The [FlameGraph](https://github.com/brendangregg/FlameGraph) toolkit\n- [Inferno](https://github.com/jonhoo/inferno) (Rust port of FlameGraph)\n- [Speedscope](https://speedscope.app/)\n\nExample:\n\n```sh\n# Record a profile to perf.data\n$ ./app_profiler.py <args>\n\n# Convert to Folded Stacks format\n$ ./stackcollapse.py --kernel --jit | gzip > profile.folded.gz\n\n# Visualise with FlameGraph with Java Stacks and nanosecond times\n$ git clone https://github.com/brendangregg/FlameGraph.git\n$ gunzip -c profile.folded.gz \\\n    | FlameGraph/flamegraph.pl --color=java --countname=ns \\\n    > profile.svg\n```\n\n## simpleperf_report_lib.py\n\n`simpleperf_report_lib.py` is a Python library used to parse profiling data files generated by the\nrecord command. Internally, it uses libsimpleperf_report.so to do the work. Generally, for each\nprofiling data file, we create an instance of ReportLib, pass it the file path (via SetRecordFile).\nThen we can read all samples through GetNextSample(). For each sample, we can read its event info\n(via GetEventOfCurrentSample), symbol info (via GetSymbolOfCurrentSample) and call chain info\n(via GetCallChainOfCurrentSample). We can also get some global information, like record options\n(via GetRecordCmd), the arch of the device (via GetArch) and meta strings (via MetaInfo).\n\nExamples of using `simpleperf_report_lib.py` are in `report_sample.py`, `report_html.py`,\n`pprof_proto_generator.py` and `inferno/inferno.py`.\n"
  },
  {
    "path": "include/Resources.h",
    "content": "#pragma once\n#include \"cinder/CinderResources.h\"\n\n//#define RES_MY_RES\t\t\tCINDER_RESOURCE( ../resources/, image_name.png, 128, IMAGE )\n\n\r\n\r\n"
  },
  {
    "path": "include/item.def",
    "content": "ITEM_DEF(int, APP_WIDTH, 1920)\nITEM_DEF(int, APP_HEIGHT, 1080)\nITEM_DEF_MINMAX(int, PANEL_HEIGHT, 200, 100, 400)\nITEM_DEF_MINMAX(int, PANEL_TICK_T, 10, 1, 200)\nITEM_DEF_MINMAX(int, RANGE_START, 0, 0, 1000)\nITEM_DEF_MINMAX(int, RANGE_DURATION, 100, 1, 1000)\nITEM_DEF_MINMAX(float, BACKGROUND_GRAY, 0.3, 0, 1)\nITEM_DEF(float, REFRESH_SECONDS, 0.5)\nITEM_DEF(bool, SHOW_TOOL_TIP, true)\nITEM_DEF(int, DEVICE_ID, -1)\nITEM_DEF(string, APP_NAME, \"\")\nITEM_DEF(bool, AUTO_START, false)\nITEM_DEF(string, APP_FOLDER, \"game\")\nITEM_DEF(string, UE_CMD, \"stat unit\")\nITEM_DEF(bool, LIST_ALL_APP, false)\nITEM_DEF(bool, SUPPORT_NON_GAME, false)\nITEM_DEF(int, COLOR_MAP, 1)\n\nGROUP_DEF(visibility)\nITEM_DEF(bool, fps_visible, true)\nITEM_DEF(bool, frame_time_visible, false)\nITEM_DEF(bool, cpu_usage_visible, false)\nITEM_DEF(bool, core_usage_visible, true)\nITEM_DEF(bool, memory_usage_visible, false)\nITEM_DEF(bool, core_freq_visible, false)\nITEM_DEF(bool, temperature_visible, false)"
  },
  {
    "path": "simpleperf/__init__.py",
    "content": ""
  },
  {
    "path": "simpleperf/annotate.py",
    "content": "#!/usr/bin/env python3\n#\n# Copyright (C) 2016 The Android Open Source Project\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\"\"\"annotate.py: annotate source files based on perf.data.\n\"\"\"\n\nimport logging\nimport os\nimport os.path\nimport shutil\nfrom texttable import Texttable\nfrom typing import Dict, Union\n\nfrom simpleperf_report_lib import ReportLib\nfrom simpleperf_utils import (\n    Addr2Nearestline, BaseArgumentParser, BinaryFinder, extant_dir, flatten_arg_list, is_windows,\n    log_exit, ReadElf, SourceFileSearcher)\n\n\nclass SourceLine(object):\n    def __init__(self, file_id, function, line):\n        self.file = file_id\n        self.function = function\n        self.line = line\n\n    @property\n    def file_key(self):\n        return self.file\n\n    @property\n    def function_key(self):\n        return (self.file, self.function)\n\n    @property\n    def line_key(self):\n        return (self.file, self.line)\n\n\nclass Addr2Line(object):\n    \"\"\"collect information of how to map [dso_name, vaddr] to [source_file:line].\n    \"\"\"\n\n    def __init__(self, ndk_path, binary_cache_path, source_dirs):\n        binary_finder = BinaryFinder(binary_cache_path, ReadElf(ndk_path))\n        self.addr2line = Addr2Nearestline(ndk_path, binary_finder, True)\n        self.source_searcher = SourceFileSearcher(source_dirs)\n\n    def add_addr(self, dso_path: str, build_id: str, func_addr: int, addr: int):\n        self.addr2line.add_addr(dso_path, build_id, func_addr, addr)\n\n    def convert_addrs_to_lines(self):\n        self.addr2line.convert_addrs_to_lines(jobs=os.cpu_count())\n\n    def get_sources(self, dso_path, addr):\n        dso = self.addr2line.get_dso(dso_path)\n        if not dso:\n            return []\n        source = self.addr2line.get_addr_source(dso, addr)\n        if not source:\n            return []\n        result = []\n        for (source_file, source_line, function_name) in source:\n            source_file_path = self.source_searcher.get_real_path(source_file)\n            if not source_file_path:\n                source_file_path = source_file\n            result.append(SourceLine(source_file_path, function_name, source_line))\n        return result\n\n\nclass Period(object):\n    \"\"\"event count information. It can be used to represent event count\n       of a line, a function, a source file, or a binary. It contains two\n       parts: period and acc_period.\n       When used for a line, period is the event count occurred when running\n       that line, acc_period is the accumulated event count occurred when\n       running that line and functions called by that line. Same thing applies\n       when it is used for a function, a source file, or a binary.\n    \"\"\"\n\n    def __init__(self, period=0, acc_period=0):\n        self.period = period\n        self.acc_period = acc_period\n\n    def __iadd__(self, other):\n        self.period += other.period\n        self.acc_period += other.acc_period\n        return self\n\n\nclass DsoPeriod(object):\n    \"\"\"Period for each shared library\"\"\"\n\n    def __init__(self, dso_name):\n        self.dso_name = dso_name\n        self.period = Period()\n\n    def add_period(self, period):\n        self.period += period\n\n\nclass FilePeriod(object):\n    \"\"\"Period for each source file\"\"\"\n\n    def __init__(self, file_id):\n        self.file = file_id\n        self.period = Period()\n        # Period for each line in the file.\n        self.line_dict = {}\n        # Period for each function in the source file.\n        self.function_dict = {}\n\n    def add_period(self, period):\n        self.period += period\n\n    def add_line_period(self, line, period):\n        a = self.line_dict.get(line)\n        if a is None:\n            self.line_dict[line] = a = Period()\n        a += period\n\n    def add_function_period(self, function_name, function_start_line, period):\n        a = self.function_dict.get(function_name)\n        if not a:\n            if function_start_line is None:\n                function_start_line = -1\n            self.function_dict[function_name] = a = [function_start_line, Period()]\n        a[1] += period\n\n\nclass SourceFileAnnotator(object):\n    \"\"\"group code for annotating source files\"\"\"\n\n    def __init__(self, config):\n        # check config variables\n        config_names = ['perf_data_list', 'source_dirs', 'comm_filters', 'dso_filters', 'ndk_path']\n        for name in config_names:\n            if name not in config:\n                log_exit('config [%s] is missing' % name)\n        symfs_dir = 'binary_cache'\n        if not os.path.isdir(symfs_dir):\n            symfs_dir = None\n        kallsyms = 'binary_cache/kallsyms'\n        if not os.path.isfile(kallsyms):\n            kallsyms = None\n\n        # init member variables\n        self.config = config\n        self.symfs_dir = symfs_dir\n        self.kallsyms = kallsyms\n        self.comm_filter = set(config['comm_filters']) if config.get('comm_filters') else None\n        self.dso_filter = set(config['dso_filters']) if config.get('dso_filters') else None\n\n        config['annotate_dest_dir'] = 'annotated_files'\n        output_dir = config['annotate_dest_dir']\n        if os.path.isdir(output_dir):\n            shutil.rmtree(output_dir)\n        os.makedirs(output_dir)\n\n        self.addr2line = Addr2Line(self.config['ndk_path'], symfs_dir, config.get('source_dirs'))\n        self.period = 0\n        self.dso_periods = {}\n        self.file_periods = {}\n\n    def annotate(self):\n        self._collect_addrs()\n        self._convert_addrs_to_lines()\n        self._generate_periods()\n        self._write_summary()\n        self._annotate_files()\n\n    def _collect_addrs(self):\n        \"\"\"Read perf.data, collect all addresses we need to convert to\n           source file:line.\n        \"\"\"\n        for perf_data in self.config['perf_data_list']:\n            lib = ReportLib()\n            lib.SetRecordFile(perf_data)\n            if self.symfs_dir:\n                lib.SetSymfs(self.symfs_dir)\n            if self.kallsyms:\n                lib.SetKallsymsFile(self.kallsyms)\n            if self.config.get('sample_filter'):\n                lib.SetSampleFilter(self.config.get('sample_filter'))\n            while True:\n                sample = lib.GetNextSample()\n                if sample is None:\n                    lib.Close()\n                    break\n                if not self._filter_sample(sample):\n                    continue\n                symbols = []\n                symbols.append(lib.GetSymbolOfCurrentSample())\n                callchain = lib.GetCallChainOfCurrentSample()\n                for i in range(callchain.nr):\n                    symbols.append(callchain.entries[i].symbol)\n                for symbol in symbols:\n                    if self._filter_symbol(symbol):\n                        build_id = lib.GetBuildIdForPath(symbol.dso_name)\n                        self.addr2line.add_addr(symbol.dso_name, build_id, symbol.symbol_addr,\n                                                symbol.vaddr_in_file)\n                        self.addr2line.add_addr(symbol.dso_name, build_id, symbol.symbol_addr,\n                                                symbol.symbol_addr)\n\n    def _filter_sample(self, sample):\n        \"\"\"Return true if the sample can be used.\"\"\"\n        if self.comm_filter:\n            if sample.thread_comm not in self.comm_filter:\n                return False\n        return True\n\n    def _filter_symbol(self, symbol):\n        if not self.dso_filter or symbol.dso_name in self.dso_filter:\n            return True\n        return False\n\n    def _convert_addrs_to_lines(self):\n        self.addr2line.convert_addrs_to_lines()\n\n    def _generate_periods(self):\n        \"\"\"read perf.data, collect Period for all types:\n            binaries, source files, functions, lines.\n        \"\"\"\n        for perf_data in self.config['perf_data_list']:\n            lib = ReportLib()\n            lib.SetRecordFile(perf_data)\n            if self.symfs_dir:\n                lib.SetSymfs(self.symfs_dir)\n            if self.kallsyms:\n                lib.SetKallsymsFile(self.kallsyms)\n            if self.config.get('sample_filter'):\n                lib.SetSampleFilter(self.config.get('sample_filter'))\n            while True:\n                sample = lib.GetNextSample()\n                if sample is None:\n                    lib.Close()\n                    break\n                if not self._filter_sample(sample):\n                    continue\n                self._generate_periods_for_sample(lib, sample)\n\n    def _generate_periods_for_sample(self, lib, sample):\n        symbols = []\n        symbols.append(lib.GetSymbolOfCurrentSample())\n        callchain = lib.GetCallChainOfCurrentSample()\n        for i in range(callchain.nr):\n            symbols.append(callchain.entries[i].symbol)\n        # Each sample has a callchain, but its period is only used once\n        # to add period for each function/source_line/source_file/binary.\n        # For example, if more than one entry in the callchain hits a\n        # function, the event count of that function is only increased once.\n        # Otherwise, we may get periods > 100%.\n        is_sample_used = False\n        used_dso_dict = {}\n        used_file_dict = {}\n        used_function_dict = {}\n        used_line_dict = {}\n        period = Period(sample.period, sample.period)\n        for j, symbol in enumerate(symbols):\n            if j == 1:\n                period = Period(0, sample.period)\n            if not self._filter_symbol(symbol):\n                continue\n            is_sample_used = True\n            # Add period to dso.\n            self._add_dso_period(symbol.dso_name, period, used_dso_dict)\n            # Add period to source file.\n            sources = self.addr2line.get_sources(symbol.dso_name, symbol.vaddr_in_file)\n            for source in sources:\n                if source.file:\n                    self._add_file_period(source, period, used_file_dict)\n                    # Add period to line.\n                    if source.line:\n                        self._add_line_period(source, period, used_line_dict)\n            # Add period to function.\n            sources = self.addr2line.get_sources(symbol.dso_name, symbol.symbol_addr)\n            for source in sources:\n                if source.file:\n                    self._add_file_period(source, period, used_file_dict)\n                    if source.function:\n                        self._add_function_period(source, period, used_function_dict)\n\n        if is_sample_used:\n            self.period += sample.period\n\n    def _add_dso_period(self, dso_name: str, period: Period, used_dso_dict: Dict[str, bool]):\n        if dso_name not in used_dso_dict:\n            used_dso_dict[dso_name] = True\n            dso_period = self.dso_periods.get(dso_name)\n            if dso_period is None:\n                dso_period = self.dso_periods[dso_name] = DsoPeriod(dso_name)\n            dso_period.add_period(period)\n\n    def _add_file_period(self, source, period, used_file_dict):\n        if source.file_key not in used_file_dict:\n            used_file_dict[source.file_key] = True\n            file_period = self.file_periods.get(source.file)\n            if file_period is None:\n                file_period = self.file_periods[source.file] = FilePeriod(source.file)\n            file_period.add_period(period)\n\n    def _add_line_period(self, source, period, used_line_dict):\n        if source.line_key not in used_line_dict:\n            used_line_dict[source.line_key] = True\n            file_period = self.file_periods[source.file]\n            file_period.add_line_period(source.line, period)\n\n    def _add_function_period(self, source, period, used_function_dict):\n        if source.function_key not in used_function_dict:\n            used_function_dict[source.function_key] = True\n            file_period = self.file_periods[source.file]\n            file_period.add_function_period(source.function, source.line, period)\n\n    def _write_summary(self):\n        summary = os.path.join(self.config['annotate_dest_dir'], 'summary')\n        with open(summary, 'w') as f:\n            f.write('total period: %d\\n\\n' % self.period)\n            self._write_dso_summary(f)\n            self._write_file_summary(f)\n\n            file_periods = sorted(self.file_periods.values(),\n                                  key=lambda x: x.period.acc_period, reverse=True)\n            for file_period in file_periods:\n                self._write_function_line_summary(f, file_period)\n\n    def _write_dso_summary(self, summary_fh):\n        dso_periods = sorted(self.dso_periods.values(),\n                             key=lambda x: x.period.acc_period, reverse=True)\n        table = Texttable(max_width=self.config['summary_width'])\n        table.set_cols_align(['l', 'l', 'l'])\n        table.add_row(['Total', 'Self', 'DSO'])\n        for dso_period in dso_periods:\n            total_str = self._get_period_str(dso_period.period.acc_period)\n            self_str = self._get_period_str(dso_period.period.period)\n            table.add_row([total_str, self_str, dso_period.dso_name])\n        print(table.draw(), file=summary_fh)\n        print(file=summary_fh)\n\n    def _write_file_summary(self, summary_fh):\n        file_periods = sorted(self.file_periods.values(),\n                              key=lambda x: x.period.acc_period, reverse=True)\n        table = Texttable(max_width=self.config['summary_width'])\n        table.set_cols_align(['l', 'l', 'l'])\n        table.add_row(['Total', 'Self', 'Source File'])\n        for file_period in file_periods:\n            total_str = self._get_period_str(file_period.period.acc_period)\n            self_str = self._get_period_str(file_period.period.period)\n            table.add_row([total_str, self_str, file_period.file])\n        print(table.draw(), file=summary_fh)\n        print(file=summary_fh)\n\n    def _write_function_line_summary(self, summary_fh, file_period: FilePeriod):\n        table = Texttable(max_width=self.config['summary_width'])\n        table.set_cols_align(['l', 'l', 'l'])\n        table.add_row(['Total', 'Self', 'Function/Line in ' + file_period.file])\n        values = []\n        for func_name in file_period.function_dict.keys():\n            func_start_line, period = file_period.function_dict[func_name]\n            values.append((func_name, func_start_line, period))\n        values.sort(key=lambda x: x[2].acc_period, reverse=True)\n        for func_name, func_start_line, period in values:\n            total_str = self._get_period_str(period.acc_period)\n            self_str = self._get_period_str(period.period)\n            name = func_name + ' (line %d)' % func_start_line\n            table.add_row([total_str, self_str, name])\n        for line in sorted(file_period.line_dict.keys()):\n            period = file_period.line_dict[line]\n            total_str = self._get_period_str(period.acc_period)\n            self_str = self._get_period_str(period.period)\n            name = 'line %d' % line\n            table.add_row([total_str, self_str, name])\n\n        print(table.draw(), file=summary_fh)\n        print(file=summary_fh)\n\n    def _get_period_str(self, period: Union[Period, int]) -> str:\n        if isinstance(period, Period):\n            return 'Total %s, Self %s' % (\n                self._get_period_str(period.acc_period),\n                self._get_period_str(period.period))\n        if self.config['raw_period'] or self.period == 0:\n            return str(period)\n        return '%.2f%%' % (100.0 * period / self.period)\n\n    def _annotate_files(self):\n        \"\"\"Annotate Source files: add acc_period/period for each source file.\n           1. Annotate java source files, which have $JAVA_SRC_ROOT prefix.\n           2. Annotate c++ source files.\n        \"\"\"\n        dest_dir = self.config['annotate_dest_dir']\n        for key in self.file_periods:\n            from_path = key\n            if not os.path.isfile(from_path):\n                logging.warning(\"can't find source file for path %s\" % from_path)\n                continue\n            if from_path.startswith('/'):\n                to_path = os.path.join(dest_dir, from_path[1:])\n            elif is_windows() and ':\\\\' in from_path:\n                to_path = os.path.join(dest_dir, from_path.replace(':\\\\', os.sep))\n            else:\n                to_path = os.path.join(dest_dir, from_path)\n            is_java = from_path.endswith('.java')\n            self._annotate_file(from_path, to_path, self.file_periods[key], is_java)\n\n    def _annotate_file(self, from_path, to_path, file_period, is_java):\n        \"\"\"Annotate a source file.\n\n        Annotate a source file in three steps:\n          1. In the first line, show periods of this file.\n          2. For each function, show periods of this function.\n          3. For each line not hitting the same line as functions, show\n             line periods.\n        \"\"\"\n        logging.info('annotate file %s' % from_path)\n        with open(from_path, 'r') as rf:\n            lines = rf.readlines()\n\n        annotates = {}\n        for line in file_period.line_dict.keys():\n            annotates[line] = self._get_period_str(file_period.line_dict[line])\n        for func_name in file_period.function_dict.keys():\n            func_start_line, period = file_period.function_dict[func_name]\n            if func_start_line == -1:\n                continue\n            line = func_start_line - 1 if is_java else func_start_line\n            annotates[line] = '[func] ' + self._get_period_str(period)\n        annotates[1] = '[file] ' + self._get_period_str(file_period.period)\n\n        max_annotate_cols = 0\n        for key in annotates:\n            max_annotate_cols = max(max_annotate_cols, len(annotates[key]))\n\n        empty_annotate = ' ' * (max_annotate_cols + 6)\n\n        dirname = os.path.dirname(to_path)\n        if not os.path.isdir(dirname):\n            os.makedirs(dirname)\n        with open(to_path, 'w') as wf:\n            for line in range(1, len(lines) + 1):\n                annotate = annotates.get(line)\n                if annotate is None:\n                    if not lines[line-1].strip():\n                        annotate = ''\n                    else:\n                        annotate = empty_annotate\n                else:\n                    annotate = '/* ' + annotate + (\n                        ' ' * (max_annotate_cols - len(annotate))) + ' */'\n                wf.write(annotate)\n                wf.write(lines[line-1])\n\n\ndef main():\n    parser = BaseArgumentParser(description=\"\"\"\n        Annotate source files based on profiling data. It reads line information from binary_cache\n        generated by app_profiler.py or binary_cache_builder.py, and generate annotated source\n        files in annotated_files directory.\"\"\")\n    parser.add_argument('-i', '--perf_data_list', nargs='+', action='append', help=\"\"\"\n        The paths of profiling data. Default is perf.data.\"\"\")\n    parser.add_argument('-s', '--source_dirs', type=extant_dir, nargs='+', action='append', help=\"\"\"\n        Directories to find source files.\"\"\")\n    parser.add_argument('--ndk_path', type=extant_dir, help='Set the path of a ndk release.')\n    parser.add_argument('--raw-period', action='store_true',\n                        help='show raw period instead of percentage')\n    parser.add_argument('--summary-width', type=int, default=80, help='max width of summary file')\n    sample_filter_group = parser.add_argument_group('Sample filter options')\n    parser.add_sample_filter_options(sample_filter_group)\n    sample_filter_group.add_argument('--comm', nargs='+', action='append', help=\"\"\"\n        Use samples only in threads with selected names.\"\"\")\n    sample_filter_group.add_argument('--dso', nargs='+', action='append', help=\"\"\"\n        Use samples only in selected binaries.\"\"\")\n\n    args = parser.parse_args()\n    config = {}\n    config['perf_data_list'] = flatten_arg_list(args.perf_data_list)\n    if not config['perf_data_list']:\n        config['perf_data_list'].append('perf.data')\n    config['source_dirs'] = flatten_arg_list(args.source_dirs)\n    config['comm_filters'] = flatten_arg_list(args.comm)\n    config['dso_filters'] = flatten_arg_list(args.dso)\n    config['ndk_path'] = args.ndk_path\n    config['raw_period'] = args.raw_period\n    config['summary_width'] = args.summary_width\n    config['sample_filter'] = args.sample_filter\n\n    annotator = SourceFileAnnotator(config)\n    annotator.annotate()\n    logging.info('annotate finish successfully, please check result in annotated_files/.')\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "simpleperf/api_profiler.py",
    "content": "#!/usr/bin/env python3\n#\n# Copyright (C) 2019 The Android Open Source Project\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\"\"\"\n    This script is part of controlling simpleperf recording in user code. It is used to prepare\n    profiling environment (upload simpleperf to device and enable profiling) before recording\n    and collect recording data on host after recording.\n    Controlling simpleperf recording is done in below steps:\n    1. Add simpleperf Java API/C++ API to the app's source code. And call the API in user code.\n    2. Run `api_profiler.py prepare` to prepare profiling environment.\n    3. Run the app one or more times to generate recording data.\n    4. Run `api_profiler.py collect` to collect recording data on host.\n\"\"\"\n\nfrom argparse import Namespace\nimport logging\nimport os\nimport os.path\nimport shutil\nimport zipfile\n\nfrom simpleperf_utils import (AdbHelper, BaseArgumentParser,\n                              get_target_binary_path, log_exit, remove)\n\n\nclass ApiProfiler:\n    def __init__(self, args: Namespace):\n        self.args = args\n        self.adb = AdbHelper()\n\n    def prepare_recording(self):\n        self.enable_profiling_on_device()\n        self.upload_simpleperf_to_device()\n        self.run_simpleperf_prepare_cmd()\n\n    def enable_profiling_on_device(self):\n        android_version = self.adb.get_android_version()\n        if android_version >= 10:\n            self.adb.set_property('debug.perf_event_max_sample_rate',\n                                  str(self.args.max_sample_rate))\n            self.adb.set_property('debug.perf_cpu_time_max_percent', str(self.args.max_cpu_percent))\n            self.adb.set_property('debug.perf_event_mlock_kb', str(self.args.max_memory_in_kb))\n        self.adb.set_property('security.perf_harden', '0')\n\n    def upload_simpleperf_to_device(self):\n        device_arch = self.adb.get_device_arch()\n        simpleperf_binary = get_target_binary_path(device_arch, 'simpleperf')\n        self.adb.check_run(['push', simpleperf_binary, '/data/local/tmp'])\n        self.adb.check_run(['shell', 'chmod', 'a+x', '/data/local/tmp/simpleperf'])\n\n    def run_simpleperf_prepare_cmd(self):\n        cmd_args = ['shell', '/data/local/tmp/simpleperf', 'api-prepare', '--app', self.args.app]\n        if self.args.days:\n            cmd_args += ['--days', str(self.args.days)]\n        self.adb.check_run(cmd_args)\n\n    def collect_data(self):\n        if not os.path.isdir(self.args.out_dir):\n            os.makedirs(self.args.out_dir)\n        self.download_recording_data()\n        self.unzip_recording_data()\n\n    def download_recording_data(self):\n        \"\"\" download recording data to simpleperf_data.zip.\"\"\"\n        self.upload_simpleperf_to_device()\n        self.adb.check_run(['shell', '/data/local/tmp/simpleperf', 'api-collect',\n                            '--app', self.args.app, '-o', '/data/local/tmp/simpleperf_data.zip'])\n        self.adb.check_run(['pull', '/data/local/tmp/simpleperf_data.zip', self.args.out_dir])\n        self.adb.check_run(['shell', 'rm', '-rf', '/data/local/tmp/simpleperf_data'])\n\n    def unzip_recording_data(self):\n        zip_file_path = os.path.join(self.args.out_dir, 'simpleperf_data.zip')\n        with zipfile.ZipFile(zip_file_path, 'r') as zip_fh:\n            names = zip_fh.namelist()\n            logging.info('There are %d recording data files.' % len(names))\n            for name in names:\n                logging.info('recording file: %s' % os.path.join(self.args.out_dir, name))\n                zip_fh.extract(name, self.args.out_dir)\n        remove(zip_file_path)\n\n\ndef main():\n    parser = BaseArgumentParser(description=__doc__)\n    subparsers = parser.add_subparsers(title='actions', dest='command')\n\n    prepare_parser = subparsers.add_parser('prepare', help='Prepare recording on device.')\n    prepare_parser.add_argument('-p', '--app', required=True, help=\"\"\"\n                                The app package name of the app profiled.\"\"\")\n    prepare_parser.add_argument('-d', '--days', type=int, help=\"\"\"\n                                By default, the recording permission is reset after device reboot.\n                                But on Android >= 13, we can use --days to set how long we want the\n                                permission to persist. It can last after device reboot.\n                                \"\"\")\n    prepare_parser.add_argument('--max-sample-rate', type=int, default=100000, help=\"\"\"\n                                Set max sample rate (only on Android >= Q).\"\"\")\n    prepare_parser.add_argument('--max-cpu-percent', type=int, default=25, help=\"\"\"\n                                Set max cpu percent for recording (only on Android >= Q).\"\"\")\n    prepare_parser.add_argument('--max-memory-in-kb', type=int,\n                                default=(1024 + 1) * 4 * 8, help=\"\"\"\n                                Set max kernel buffer size for recording (only on Android >= Q).\n                                \"\"\")\n\n    collect_parser = subparsers.add_parser('collect', help='Collect recording data.')\n    collect_parser.add_argument('-p', '--app', required=True, help=\"\"\"\n                                The app package name of the app profiled.\"\"\")\n    collect_parser.add_argument('-o', '--out-dir', default='simpleperf_data', help=\"\"\"\n                                The directory to store recording data.\"\"\")\n    args = parser.parse_args()\n\n    if args.command == 'prepare':\n        ApiProfiler(args).prepare_recording()\n    elif args.command == 'collect':\n        ApiProfiler(args).collect_data()\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "simpleperf/app_profiler.py",
    "content": "#!/usr/bin/env python3\n#\n# Copyright (C) 2016 The Android Open Source Project\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\"\"\"app_profiler.py: Record cpu profiling data of an android app or native program.\n\n    It downloads simpleperf on device, uses it to collect profiling data on the selected app,\n    and pulls profiling data and related binaries on host.\n\"\"\"\n\nimport logging\nimport os\nimport os.path\nimport re\nimport subprocess\nimport sys\nimport time\n\nfrom simpleperf_utils import (\n    AdbHelper, BaseArgumentParser, bytes_to_str, extant_dir, get_script_dir, get_target_binary_path,\n    log_exit, ReadElf, remove, str_to_bytes)\n\nNATIVE_LIBS_DIR_ON_DEVICE = '/data/local/tmp/native_libs/'\n\nSHELL_PS_UID_PATTERN = re.compile(r'USER.*\\nu(\\d+)_.*')\n\n\nclass HostElfEntry(object):\n    \"\"\"Represent a native lib on host in NativeLibDownloader.\"\"\"\n\n    def __init__(self, path, name, score):\n        self.path = path\n        self.name = name\n        self.score = score\n\n    def __repr__(self):\n        return self.__str__()\n\n    def __str__(self):\n        return '[path: %s, name %s, score %s]' % (self.path, self.name, self.score)\n\n\nclass NativeLibDownloader(object):\n    \"\"\"Download native libs on device.\n\n    1. Collect info of all native libs in the native_lib_dir on host.\n    2. Check the available native libs in /data/local/tmp/native_libs on device.\n    3. Sync native libs on device.\n    \"\"\"\n\n    def __init__(self, ndk_path, device_arch, adb):\n        self.adb = adb\n        self.readelf = ReadElf(ndk_path)\n        self.device_arch = device_arch\n        self.need_archs = self._get_need_archs()\n        self.host_build_id_map = {}  # Map from build_id to HostElfEntry.\n        self.device_build_id_map = {}  # Map from build_id to relative_path on device.\n        # Map from filename to HostElfEntry for elf files without build id.\n        self.no_build_id_file_map = {}\n        self.name_count_map = {}  # Used to give a unique name for each library.\n        self.dir_on_device = NATIVE_LIBS_DIR_ON_DEVICE\n        self.build_id_list_file = 'build_id_list'\n\n    def _get_need_archs(self):\n        \"\"\"Return the archs of binaries needed on device.\"\"\"\n        if self.device_arch == 'arm64':\n            return ['arm', 'arm64']\n        if self.device_arch == 'arm':\n            return ['arm']\n        if self.device_arch == 'x86_64':\n            return ['x86', 'x86_64']\n        if self.device_arch == 'x86':\n            return ['x86']\n        return []\n\n    def collect_native_libs_on_host(self, native_lib_dir):\n        self.host_build_id_map.clear()\n        for root, _, files in os.walk(native_lib_dir):\n            for name in files:\n                if not name.endswith('.so'):\n                    continue\n                self.add_native_lib_on_host(os.path.join(root, name), name)\n\n    def add_native_lib_on_host(self, path, name):\n        arch = self.readelf.get_arch(path)\n        if arch not in self.need_archs:\n            return\n        sections = self.readelf.get_sections(path)\n        score = 0\n        if '.debug_info' in sections:\n            score = 3\n        elif '.gnu_debugdata' in sections:\n            score = 2\n        elif '.symtab' in sections:\n            score = 1\n        build_id = self.readelf.get_build_id(path)\n        if build_id:\n            entry = self.host_build_id_map.get(build_id)\n            if entry:\n                if entry.score < score:\n                    entry.path = path\n                    entry.score = score\n            else:\n                repeat_count = self.name_count_map.get(name, 0)\n                self.name_count_map[name] = repeat_count + 1\n                unique_name = name if repeat_count == 0 else name + '_' + str(repeat_count)\n                self.host_build_id_map[build_id] = HostElfEntry(path, unique_name, score)\n        else:\n            entry = self.no_build_id_file_map.get(name)\n            if entry:\n                if entry.score < score:\n                    entry.path = path\n                    entry.score = score\n            else:\n                self.no_build_id_file_map[name] = HostElfEntry(path, name, score)\n\n    def collect_native_libs_on_device(self):\n        self.device_build_id_map.clear()\n        self.adb.check_run(['shell', 'mkdir', '-p', self.dir_on_device])\n        if os.path.exists(self.build_id_list_file):\n            os.remove(self.build_id_list_file)\n        result, output = self.adb.run_and_return_output(['shell', 'ls', self.dir_on_device])\n        if not result:\n            return\n        file_set = set(output.strip().split())\n        if self.build_id_list_file not in file_set:\n            return\n        self.adb.run(['pull', self.dir_on_device + self.build_id_list_file])\n        if os.path.exists(self.build_id_list_file):\n            with open(self.build_id_list_file, 'rb') as fh:\n                for line in fh.readlines():\n                    line = bytes_to_str(line).strip()\n                    items = line.split('=')\n                    if len(items) == 2:\n                        build_id, filename = items\n                        if filename in file_set:\n                            self.device_build_id_map[build_id] = filename\n            remove(self.build_id_list_file)\n\n    def sync_native_libs_on_device(self):\n        # Push missing native libs on device.\n        for build_id in self.host_build_id_map:\n            if build_id not in self.device_build_id_map:\n                entry = self.host_build_id_map[build_id]\n                self.adb.check_run(['push', entry.path, self.dir_on_device + entry.name])\n        # Remove native libs not exist on host.\n        for build_id in self.device_build_id_map:\n            if build_id not in self.host_build_id_map:\n                name = self.device_build_id_map[build_id]\n                self.adb.run(['shell', 'rm', self.dir_on_device + name])\n        # Push new build_id_list on device.\n        with open(self.build_id_list_file, 'wb') as fh:\n            for build_id in self.host_build_id_map:\n                s = str_to_bytes('%s=%s\\n' % (build_id, self.host_build_id_map[build_id].name))\n                fh.write(s)\n        self.adb.check_run(['push', self.build_id_list_file,\n                            self.dir_on_device + self.build_id_list_file])\n        os.remove(self.build_id_list_file)\n\n        # Push elf files without build id on device.\n        for entry in self.no_build_id_file_map.values():\n            target = self.dir_on_device + entry.name\n\n            # Skip download if we have a file with the same name and size on device.\n            result, output = self.adb.run_and_return_output(['shell', 'ls', '-l', target])\n            if result:\n                items = output.split()\n                if len(items) > 5:\n                    try:\n                        file_size = int(items[4])\n                    except ValueError:\n                        file_size = 0\n                    if file_size == os.path.getsize(entry.path):\n                        continue\n            self.adb.check_run(['push', entry.path, target])\n\n\nclass ProfilerBase(object):\n    \"\"\"Base class of all Profilers.\"\"\"\n\n    def __init__(self, args):\n        self.args = args\n        self.adb = AdbHelper(enable_switch_to_root=not args.disable_adb_root)\n        self.is_root_device = self.adb.switch_to_root()\n        self.android_version = self.adb.get_android_version()\n        if self.android_version < 7:\n            log_exit(\"\"\"app_profiler.py isn't supported on Android < N, please switch to use\n                        simpleperf binary directly.\"\"\")\n        self.device_arch = self.adb.get_device_arch()\n        self.record_subproc = None\n\n    def profile(self):\n        logging.info('prepare profiling')\n        self.prepare()\n        logging.info('start profiling')\n        self.start()\n        self.wait_profiling()\n        logging.info('collect profiling data')\n        self.collect_profiling_data()\n        logging.info('profiling is finished.')\n\n    def prepare(self):\n        \"\"\"Prepare recording. \"\"\"\n        self.download_simpleperf()\n        if self.args.native_lib_dir:\n            self.download_libs()\n\n    def download_simpleperf(self):\n        simpleperf_binary = get_target_binary_path(self.device_arch, 'simpleperf')\n        self.adb.check_run(['push', simpleperf_binary, '/data/local/tmp'])\n        self.adb.check_run(['shell', 'chmod', 'a+x', '/data/local/tmp/simpleperf'])\n\n    def download_libs(self):\n        downloader = NativeLibDownloader(self.args.ndk_path, self.device_arch, self.adb)\n        downloader.collect_native_libs_on_host(self.args.native_lib_dir)\n        downloader.collect_native_libs_on_device()\n        downloader.sync_native_libs_on_device()\n\n    def start(self):\n        raise NotImplementedError\n\n    def start_profiling(self, target_args):\n        \"\"\"Start simpleperf reocrd process on device.\"\"\"\n        args = ['/data/local/tmp/simpleperf', 'record', '-o', '/data/local/tmp/perf.data',\n                self.args.record_options]\n        if self.adb.run(['shell', 'ls', NATIVE_LIBS_DIR_ON_DEVICE]):\n            args += ['--symfs', NATIVE_LIBS_DIR_ON_DEVICE]\n        args += ['--log', self.args.log]\n        args += target_args\n        adb_args = [self.adb.adb_path, 'shell'] + args\n        logging.info('run adb cmd: %s' % adb_args)\n        self.record_subproc = subprocess.Popen(adb_args)\n\n    def wait_profiling(self):\n        \"\"\"Wait until profiling finishes, or stop profiling when user presses Ctrl-C.\"\"\"\n        returncode = None\n        try:\n            returncode = self.record_subproc.wait()\n        except KeyboardInterrupt:\n            self.stop_profiling()\n            self.record_subproc = None\n            # Don't check return value of record_subproc. Because record_subproc also\n            # receives Ctrl-C, and always returns non-zero.\n            returncode = 0\n        logging.debug('profiling result [%s]' % (returncode == 0))\n        if returncode != 0:\n            log_exit('Failed to record profiling data.')\n\n    def stop_profiling(self):\n        \"\"\"Stop profiling by sending SIGINT to simpleperf, and wait until it exits\n           to make sure perf.data is completely generated.\"\"\"\n        has_killed = False\n        while True:\n            (result, _) = self.adb.run_and_return_output(['shell', 'pidof', 'simpleperf'])\n            if not result:\n                break\n            if not has_killed:\n                has_killed = True\n                self.adb.run_and_return_output(['shell', 'pkill', '-l', '2', 'simpleperf'])\n            time.sleep(1)\n\n    def collect_profiling_data(self):\n        self.adb.check_run_and_return_output(['pull', '/data/local/tmp/perf.data',\n                                              self.args.perf_data_path])\n        if not self.args.skip_collect_binaries:\n            binary_cache_args = [sys.executable,\n                                 os.path.join(get_script_dir(), 'binary_cache_builder.py')]\n            binary_cache_args += ['-i', self.args.perf_data_path, '--log', self.args.log]\n            if self.args.native_lib_dir:\n                binary_cache_args += ['-lib', self.args.native_lib_dir]\n            if self.args.disable_adb_root:\n                binary_cache_args += ['--disable_adb_root']\n            if self.args.ndk_path:\n                binary_cache_args += ['--ndk_path', self.args.ndk_path]\n            subprocess.check_call(binary_cache_args)\n\n\nclass AppProfiler(ProfilerBase):\n    \"\"\"Profile an Android app.\"\"\"\n\n    def prepare(self):\n        super(AppProfiler, self).prepare()\n        if self.args.compile_java_code:\n            self.compile_java_code()\n\n    def compile_java_code(self):\n        self.kill_app_process()\n        # Fully compile Java code on Android >= N.\n        self.adb.set_property('debug.generate-debug-info', 'true')\n        self.adb.check_run(['shell', 'cmd', 'package', 'compile', '-f', '-m', 'speed',\n                            self.args.app])\n\n    def kill_app_process(self):\n        if self.find_app_process():\n            self.adb.check_run(['shell', 'am', 'force-stop', self.args.app])\n            count = 0\n            while True:\n                time.sleep(1)\n                pid = self.find_app_process()\n                if not pid:\n                    break\n                count += 1\n                if count >= 5:\n                    logging.info('unable to kill %s, skipping...' % self.args.app)\n                    break\n                # When testing on Android N, `am force-stop` sometimes can't kill\n                # com.example.simpleperf.simpleperfexampleofkotlin. So use kill when this happens.\n                if count >= 3:\n                    self.run_in_app_dir(['kill', '-9', str(pid)])\n\n    def find_app_process(self):\n        result, pidof_output = self.adb.run_and_return_output(\n            ['shell', 'pidof', self.args.app])\n        if not result:\n            return None\n        result, current_user = self.adb.run_and_return_output(\n            ['shell', 'am', 'get-current-user'])\n        if not result:\n            return None\n        pids = pidof_output.split()\n        for pid in pids:\n            result, ps_output = self.adb.run_and_return_output(\n                ['shell', 'ps', '-p', pid, '-o', 'USER'])\n            if not result:\n              return None\n            uid = SHELL_PS_UID_PATTERN.search(ps_output).group(1)\n            if uid == current_user.strip():\n              return int(pid)\n        return None\n\n    def run_in_app_dir(self, args):\n        if self.is_root_device:\n            adb_args = ['shell', 'cd /data/data/' + self.args.app + ' && ' + (' '.join(args))]\n        else:\n            adb_args = ['shell', 'run-as', self.args.app] + args\n        return self.adb.run_and_return_output(adb_args)\n\n    def start(self):\n        if self.args.activity or self.args.test:\n            self.kill_app_process()\n        self.start_profiling(['--app', self.args.app])\n        if self.args.activity:\n            self.start_activity()\n        elif self.args.test:\n            self.start_test()\n        # else: no need to start an activity or test.\n\n    def start_activity(self):\n        activity = self.args.app + '/' + self.args.activity\n        result = self.adb.run(['shell', 'am', 'start', '-n', activity])\n        if not result:\n            self.record_subproc.terminate()\n            log_exit(\"Can't start activity %s\" % activity)\n\n    def start_test(self):\n        runner = self.args.app + '/androidx.test.runner.AndroidJUnitRunner'\n        result = self.adb.run(['shell', 'am', 'instrument', '-e', 'class',\n                               self.args.test, runner])\n        if not result:\n            self.record_subproc.terminate()\n            log_exit(\"Can't start instrumentation test  %s\" % self.args.test)\n\n\nclass NativeProgramProfiler(ProfilerBase):\n    \"\"\"Profile a native program.\"\"\"\n\n    def start(self):\n        logging.info('Waiting for native process %s' % self.args.native_program)\n        while True:\n            (result, pid) = self.adb.run_and_return_output(['shell', 'pidof',\n                                                            self.args.native_program])\n            if not result:\n                # Wait for 1 millisecond.\n                time.sleep(0.001)\n            else:\n                self.start_profiling(['-p', str(int(pid))])\n                break\n\n\nclass NativeCommandProfiler(ProfilerBase):\n    \"\"\"Profile running a native command.\"\"\"\n\n    def start(self):\n        self.start_profiling([self.args.cmd])\n\n\nclass NativeProcessProfiler(ProfilerBase):\n    \"\"\"Profile processes given their pids.\"\"\"\n\n    def start(self):\n        self.start_profiling(['-p', ','.join(self.args.pid)])\n\n\nclass NativeThreadProfiler(ProfilerBase):\n    \"\"\"Profile threads given their tids.\"\"\"\n\n    def start(self):\n        self.start_profiling(['-t', ','.join(self.args.tid)])\n\n\nclass SystemWideProfiler(ProfilerBase):\n    \"\"\"Profile system wide.\"\"\"\n\n    def start(self):\n        self.start_profiling(['-a'])\n\n\ndef main():\n    parser = BaseArgumentParser(description=__doc__)\n\n    target_group = parser.add_argument_group(title='Select profiling target'\n                                             ).add_mutually_exclusive_group(required=True)\n    target_group.add_argument('-p', '--app', help=\"\"\"Profile an Android app, given the package name.\n                              Like `-p com.example.android.myapp`.\"\"\")\n\n    target_group.add_argument('-np', '--native_program', help=\"\"\"Profile a native program running on\n                              the Android device. Like `-np surfaceflinger`.\"\"\")\n\n    target_group.add_argument('-cmd', help=\"\"\"Profile running a command on the Android device.\n                              Like `-cmd \"pm -l\"`.\"\"\")\n\n    target_group.add_argument('--pid', nargs='+', help=\"\"\"Profile native processes running on device\n                              given their process ids.\"\"\")\n\n    target_group.add_argument('--tid', nargs='+', help=\"\"\"Profile native threads running on device\n                              given their thread ids.\"\"\")\n\n    target_group.add_argument('--system_wide', action='store_true', help=\"\"\"Profile system wide.\"\"\")\n\n    app_target_group = parser.add_argument_group(title='Extra options for profiling an app')\n    app_target_group.add_argument('--compile_java_code', action='store_true', help=\"\"\"Used with -p.\n                                  On Android N and Android O, we need to compile Java code into\n                                  native instructions to profile Java code. Android O also needs\n                                  wrap.sh in the apk to use the native instructions.\"\"\")\n\n    app_start_group = app_target_group.add_mutually_exclusive_group()\n    app_start_group.add_argument('-a', '--activity', help=\"\"\"Used with -p. Profile the launch time\n                                 of an activity in an Android app. The app will be started or\n                                 restarted to run the activity. Like `-a .MainActivity`.\"\"\")\n\n    app_start_group.add_argument('-t', '--test', help=\"\"\"Used with -p. Profile the launch time of an\n                                 instrumentation test in an Android app. The app will be started or\n                                 restarted to run the instrumentation test. Like\n                                 `-t test_class_name`.\"\"\")\n\n    record_group = parser.add_argument_group('Select recording options')\n    record_group.add_argument('-r', '--record_options',\n                              default='-e task-clock:u -f 1000 -g --duration 10', help=\"\"\"Set\n                              recording options for `simpleperf record` command. Use\n                              `run_simpleperf_on_device.py record -h` to see all accepted options.\n                              Default is \"-e task-clock:u -f 1000 -g --duration 10\".\"\"\")\n\n    record_group.add_argument('-lib', '--native_lib_dir', type=extant_dir,\n                              help=\"\"\"When profiling an Android app containing native libraries,\n                                      the native libraries are usually stripped and lake of symbols\n                                      and debug information to provide good profiling result. By\n                                      using -lib, you tell app_profiler.py the path storing\n                                      unstripped native libraries, and app_profiler.py will search\n                                      all shared libraries with suffix .so in the directory. Then\n                                      the native libraries will be downloaded on device and\n                                      collected in build_cache.\"\"\")\n\n    record_group.add_argument('-o', '--perf_data_path', default='perf.data',\n                              help='The path to store profiling data. Default is perf.data.')\n\n    record_group.add_argument('-nb', '--skip_collect_binaries', action='store_true',\n                              help=\"\"\"By default we collect binaries used in profiling data from\n                                      device to binary_cache directory. It can be used to annotate\n                                      source code and disassembly. This option skips it.\"\"\")\n\n    other_group = parser.add_argument_group('Other options')\n    other_group.add_argument('--ndk_path', type=extant_dir,\n                             help=\"\"\"Set the path of a ndk release. app_profiler.py needs some\n                                     tools in ndk, like readelf.\"\"\")\n\n    other_group.add_argument('--disable_adb_root', action='store_true',\n                             help=\"\"\"Force adb to run in non root mode. By default, app_profiler.py\n                                     will try to switch to root mode to be able to profile released\n                                     Android apps.\"\"\")\n\n    def check_args(args):\n        if (not args.app) and (args.compile_java_code or args.activity or args.test):\n            log_exit('--compile_java_code, -a, -t can only be used when profiling an Android app.')\n\n    args = parser.parse_args()\n    check_args(args)\n    if args.app:\n        profiler = AppProfiler(args)\n    elif args.native_program:\n        profiler = NativeProgramProfiler(args)\n    elif args.cmd:\n        profiler = NativeCommandProfiler(args)\n    elif args.pid:\n        profiler = NativeProcessProfiler(args)\n    elif args.tid:\n        profiler = NativeThreadProfiler(args)\n    elif args.system_wide:\n        profiler = SystemWideProfiler(args)\n    profiler.profile()\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "simpleperf/binary_cache_builder.py",
    "content": "#!/usr/bin/env python3\n#\n# Copyright (C) 2016 The Android Open Source Project\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\"\"\"binary_cache_builder.py: read perf.data, collect binaries needed by\n    it, and put them in binary_cache.\n\"\"\"\n\nfrom dataclasses import dataclass\nimport logging\nimport os\nimport os.path\nfrom pathlib import Path\nimport shutil\nfrom typing import List, Optional, Union\n\nfrom simpleperf_report_lib import ReportLib\nfrom simpleperf_utils import (\n    AdbHelper, BaseArgumentParser, extant_dir, extant_file, flatten_arg_list,\n    ReadElf, str_to_bytes)\n\n\ndef is_jit_symfile(dso_name):\n    return dso_name.split('/')[-1].startswith('TemporaryFile')\n\n\nclass BinaryCacheBuilder(object):\n    \"\"\"Collect all binaries needed by perf.data in binary_cache.\"\"\"\n\n    def __init__(self, ndk_path: Optional[str], disable_adb_root: bool):\n        self.adb = AdbHelper(enable_switch_to_root=not disable_adb_root)\n        self.readelf = ReadElf(ndk_path)\n        self.binary_cache_dir = 'binary_cache'\n        if not os.path.isdir(self.binary_cache_dir):\n            os.makedirs(self.binary_cache_dir)\n        self.binaries = {}\n\n    def build_binary_cache(self, perf_data_path: str, symfs_dirs: List[Union[Path, str]]):\n        self.collect_used_binaries(perf_data_path)\n        self.copy_binaries_from_symfs_dirs(symfs_dirs)\n        if self.adb.is_device_available():\n            self.pull_binaries_from_device()\n            self._pull_kernel_symbols()\n        self.create_build_id_list()\n\n    def collect_used_binaries(self, perf_data_path):\n        \"\"\"read perf.data, collect all used binaries and their build id (if available).\"\"\"\n        # A dict mapping from binary name to build_id\n        binaries = {}\n        lib = ReportLib()\n        lib.SetRecordFile(perf_data_path)\n        lib.SetLogSeverity('error')\n        while True:\n            sample = lib.GetNextSample()\n            if sample is None:\n                lib.Close()\n                break\n            symbols = [lib.GetSymbolOfCurrentSample()]\n            callchain = lib.GetCallChainOfCurrentSample()\n            for i in range(callchain.nr):\n                symbols.append(callchain.entries[i].symbol)\n\n            for symbol in symbols:\n                dso_name = symbol.dso_name\n                if dso_name not in binaries:\n                    if is_jit_symfile(dso_name):\n                        continue\n                    name = 'vmlinux' if dso_name == '[kernel.kallsyms]' else dso_name\n                    binaries[name] = lib.GetBuildIdForPath(dso_name)\n        self.binaries = binaries\n\n    def copy_binaries_from_symfs_dirs(self, symfs_dirs: List[Union[Path, str]]):\n        \"\"\"collect all files in symfs_dirs.\"\"\"\n        if not symfs_dirs:\n            return\n\n        # It is possible that the path of the binary in symfs_dirs doesn't match\n        # the one recorded in perf.data. For example, a file in symfs_dirs might\n        # be \"debug/arm/obj/armeabi-v7a/libsudo-game-jni.so\", but the path in\n        # perf.data is \"/data/app/xxxx/lib/arm/libsudo-game-jni.so\". So we match\n        # binaries if they have the same filename (like libsudo-game-jni.so)\n        # and same build_id.\n\n        # Map from filename to binary paths.\n        filename_dict = {}\n        for binary in self.binaries:\n            index = binary.rfind('/')\n            filename = binary[index+1:]\n            paths = filename_dict.get(filename)\n            if paths is None:\n                filename_dict[filename] = paths = []\n            paths.append(binary)\n\n        # Walk through all files in symfs_dirs, and copy matching files to build_cache.\n        for symfs_dir in symfs_dirs:\n            for root, _, files in os.walk(symfs_dir):\n                for filename in files:\n                    paths = filename_dict.get(filename)\n                    if not paths:\n                        continue\n                    build_id = self._read_build_id(os.path.join(root, filename))\n                    for binary in paths:\n                        expected_build_id = self.binaries.get(binary)\n                        if expected_build_id == build_id:\n                            self._copy_to_binary_cache(os.path.join(root, filename),\n                                                       expected_build_id, binary)\n                            break\n\n    def _copy_to_binary_cache(self, from_path, expected_build_id, target_file):\n        if target_file[0] == '/':\n            target_file = target_file[1:]\n        target_file = target_file.replace('/', os.sep)\n        target_file = os.path.join(self.binary_cache_dir, target_file)\n        if not self._need_to_copy(from_path, target_file, expected_build_id):\n            # The existing file in binary_cache can provide more information, so no need to copy.\n            return\n        target_dir = os.path.dirname(target_file)\n        if not os.path.isdir(target_dir):\n            os.makedirs(target_dir)\n        logging.info('copy to binary_cache: %s to %s' % (from_path, target_file))\n        shutil.copy(from_path, target_file)\n\n    def _need_to_copy(self, source_file, target_file, expected_build_id):\n        if not os.path.isfile(target_file):\n            return True\n        if self._read_build_id(target_file) != expected_build_id:\n            return True\n        return self._get_file_stripped_level(source_file) < self._get_file_stripped_level(\n            target_file)\n\n    def _get_file_stripped_level(self, file_path):\n        \"\"\"Return stripped level of an ELF file. Larger value means more stripped.\"\"\"\n        sections = self.readelf.get_sections(file_path)\n        if '.debug_line' in sections:\n            return 0\n        if '.symtab' in sections:\n            return 1\n        return 2\n\n    def pull_binaries_from_device(self):\n        \"\"\"pull binaries needed in perf.data to binary_cache.\"\"\"\n        for binary in self.binaries:\n            build_id = self.binaries[binary]\n            if not binary.startswith('/') or binary == \"//anon\" or binary.startswith(\"/dev/\"):\n                # [kernel.kallsyms] or unknown, or something we can't find binary.\n                continue\n            binary_cache_file = binary[1:].replace('/', os.sep)\n            binary_cache_file = os.path.join(self.binary_cache_dir, binary_cache_file)\n            self._check_and_pull_binary(binary, build_id, binary_cache_file)\n\n    def _check_and_pull_binary(self, binary, expected_build_id, binary_cache_file):\n        \"\"\"If the binary_cache_file exists and has the expected_build_id, there\n           is no need to pull the binary from device. Otherwise, pull it.\n        \"\"\"\n        need_pull = True\n        if os.path.isfile(binary_cache_file):\n            need_pull = False\n            if expected_build_id:\n                build_id = self._read_build_id(binary_cache_file)\n                if expected_build_id != build_id:\n                    need_pull = True\n        if need_pull:\n            target_dir = os.path.dirname(binary_cache_file)\n            if not os.path.isdir(target_dir):\n                os.makedirs(target_dir)\n            if os.path.isfile(binary_cache_file):\n                os.remove(binary_cache_file)\n            logging.info('pull file to binary_cache: %s to %s' % (binary, binary_cache_file))\n            self._pull_file_from_device(binary, binary_cache_file)\n        else:\n            logging.info('use current file in binary_cache: %s' % binary_cache_file)\n\n    def _read_build_id(self, file_path):\n        \"\"\"read build id of a binary on host.\"\"\"\n        return self.readelf.get_build_id(file_path)\n\n    def _pull_file_from_device(self, device_path, host_path):\n        if self.adb.run(['pull', device_path, host_path]):\n            return True\n        # In non-root device, we can't pull /data/app/XXX/base.odex directly.\n        # Instead, we can first copy the file to /data/local/tmp, then pull it.\n        filename = device_path[device_path.rfind('/')+1:]\n        if (self.adb.run(['shell', 'cp', device_path, '/data/local/tmp']) and\n                self.adb.run(['pull', '/data/local/tmp/' + filename, host_path])):\n            self.adb.run(['shell', 'rm', '/data/local/tmp/' + filename])\n            return True\n        logging.warning('failed to pull %s from device' % device_path)\n        return False\n\n    def _pull_kernel_symbols(self):\n        file_path = os.path.join(self.binary_cache_dir, 'kallsyms')\n        if os.path.isfile(file_path):\n            os.remove(file_path)\n        if self.adb.switch_to_root():\n            self.adb.run(['shell', 'echo', '0', '>/proc/sys/kernel/kptr_restrict'])\n            self.adb.run(['pull', '/proc/kallsyms', file_path])\n\n    def create_build_id_list(self):\n        \"\"\" Create build_id_list. So report scripts can find a binary by its build_id instead of\n            path.\n        \"\"\"\n        build_id_list_path = os.path.join(self.binary_cache_dir, 'build_id_list')\n        with open(build_id_list_path, 'wb') as fh:\n            for root, _, files in os.walk(self.binary_cache_dir):\n                for filename in files:\n                    path = os.path.join(root, filename)\n                    relative_path = path[len(self.binary_cache_dir) + 1:]\n                    build_id = self._read_build_id(path)\n                    if build_id:\n                        line = f'{build_id}={relative_path}\\n'\n                        fh.write(str_to_bytes(line))\n\n\ndef main():\n    parser = BaseArgumentParser(description=\"\"\"\n        Pull binaries needed by perf.data from device to binary_cache directory.\"\"\")\n    parser.add_argument('-i', '--perf_data_path', default='perf.data', type=extant_file, help=\"\"\"\n        The path of profiling data.\"\"\")\n    parser.add_argument('-lib', '--native_lib_dir', type=extant_dir, nargs='+', help=\"\"\"\n        Path to find debug version of native shared libraries used in the app.\"\"\", action='append')\n    parser.add_argument('--disable_adb_root', action='store_true', help=\"\"\"\n        Force adb to run in non root mode.\"\"\")\n    parser.add_argument('--ndk_path', nargs=1, help='Find tools in the ndk path.')\n    args = parser.parse_args()\n    ndk_path = None if not args.ndk_path else args.ndk_path[0]\n    builder = BinaryCacheBuilder(ndk_path, args.disable_adb_root)\n    symfs_dirs = flatten_arg_list(args.native_lib_dir)\n    builder.build_binary_cache(args.perf_data_path, symfs_dirs)\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "simpleperf/clean_reports.bat",
    "content": "rm *.html\r\nrm *.data"
  },
  {
    "path": "simpleperf/debug_unwind_reporter.py",
    "content": "#!/usr/bin/env python3\n#\n# Copyright (C) 2017 The Android Open Source Project\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\"\"\"debug_unwind_reporter.py: report failed dwarf unwinding cases generated by debug-unwind cmd.\n\nBelow is an example using debug_unwind_reporter.py:\n1. Record with \"-g --keep-failed-unwinding-debug-info\" option on device.\n    $ simpleperf record -g --keep-failed-unwinding-debug-info --app com.google.sample.tunnel \\\\\n        --duration 10\n    The generated perf.data can be used for normal reporting. But it also contains stack data\n    and binaries for debugging failed unwinding cases.\n\n2. Generate report with debug-unwind cmd.\n    $ simpleperf debug-unwind -i perf.data --generate-report -o report.txt\n    The report contains details for each failed unwinding case. It is usually too long to\n    parse manually. That's why we need debug_unwind_reporter.py.\n\n3. Use debug_unwind_reporter.py to parse the report.\n    $ simpleperf debug-unwind -i report.txt --summary\n    $ simpleperf debug-unwind -i report.txt --include-error-code 1\n    ...\n\"\"\"\n\nimport argparse\nfrom collections import Counter, defaultdict\nfrom simpleperf_utils import BaseArgumentParser\nfrom texttable import Texttable\nfrom typing import Dict, Iterator, List\n\n\nclass CallChainNode:\n    def __init__(self):\n        self.dso = ''\n        self.symbol = ''\n\n\nclass Sample:\n    \"\"\" A failed unwinding case \"\"\"\n\n    def __init__(self, raw_lines: List[str]):\n        self.raw_lines = raw_lines\n        self.sample_time = 0\n        self.error_code = 0\n        self.callchain: List[CallChainNode] = []\n        self.parse()\n\n    def parse(self):\n        for line in self.raw_lines:\n            key, value = line.split(': ', 1)\n            if key == 'sample_time':\n                self.sample_time = int(value)\n            elif key == 'unwinding_error_code':\n                self.error_code = int(value)\n            elif key.startswith('dso'):\n                callchain_id = int(key.rsplit('_', 1)[1])\n                self._get_callchain_node(callchain_id).dso = value\n            elif key.startswith('symbol'):\n                callchain_id = int(key.rsplit('_', 1)[1])\n                self._get_callchain_node(callchain_id).symbol = value\n\n    def _get_callchain_node(self, callchain_id: int) -> CallChainNode:\n        callchain_id -= 1\n        if callchain_id == len(self.callchain):\n            self.callchain.append(CallChainNode())\n        return self.callchain[callchain_id]\n\n\nclass SampleFilter:\n    def match(self, sample: Sample) -> bool:\n        raise Exception('unimplemented')\n\n\nclass CompleteCallChainFilter(SampleFilter):\n    def match(self, sample: Sample) -> bool:\n        for node in sample.callchain:\n            if node.dso.endswith('libc.so') and (node.symbol in ('__libc_init', '__start_thread')):\n                return True\n        return False\n\n\nclass ErrorCodeFilter(SampleFilter):\n    def __init__(self, error_code: List[int]):\n        self.error_code = set(error_code)\n\n    def match(self, sample: Sample) -> bool:\n        return sample.error_code in self.error_code\n\n\nclass EndDsoFilter(SampleFilter):\n    def __init__(self, end_dso: List[str]):\n        self.end_dso = set(end_dso)\n\n    def match(self, sample: Sample) -> bool:\n        return sample.callchain[-1].dso in self.end_dso\n\n\nclass EndSymbolFilter(SampleFilter):\n    def __init__(self, end_symbol: List[str]):\n        self.end_symbol = set(end_symbol)\n\n    def match(self, sample: Sample) -> bool:\n        return sample.callchain[-1].symbol in self.end_symbol\n\n\nclass SampleTimeFilter(SampleFilter):\n    def __init__(self, sample_time: List[int]):\n        self.sample_time = set(sample_time)\n\n    def match(self, sample: Sample) -> bool:\n        return sample.sample_time in self.sample_time\n\n\nclass ReportInput:\n    def __init__(self):\n        self.exclude_filters: List[SampleFilter] = []\n        self.include_filters: List[SampleFilter] = []\n\n    def set_filters(self, args: argparse.Namespace):\n        if not args.show_callchain_fixed_by_joiner:\n            self.exclude_filters.append(CompleteCallChainFilter())\n        if args.exclude_error_code:\n            self.exclude_filters.append(ErrorCodeFilter(args.exclude_error_code))\n        if args.exclude_end_dso:\n            self.exclude_filters.append(EndDsoFilter(args.exclude_end_dso))\n        if args.exclude_end_symbol:\n            self.exclude_filters.append(EndSymbolFilter(args.exclude_end_symbol))\n        if args.exclude_sample_time:\n            self.exclude_filters.append(SampleTimeFilter(args.exclude_sample_time))\n\n        if args.include_error_code:\n            self.include_filters.append(ErrorCodeFilter(args.include_error_code))\n        if args.include_end_dso:\n            self.include_filters.append(EndDsoFilter(args.include_end_dso))\n        if args.include_end_symbol:\n            self.include_filters.append(EndSymbolFilter(args.include_end_symbol))\n        if args.include_sample_time:\n            self.include_filters.append(SampleTimeFilter(args.include_sample_time))\n\n    def get_samples(self, input_file: str) -> Iterator[Sample]:\n        sample_lines: List[str] = []\n        in_sample = False\n        with open(input_file, 'r') as fh:\n            for line in fh.readlines():\n                line = line.rstrip()\n                if line.startswith('sample_time:'):\n                    in_sample = True\n                elif not line:\n                    if in_sample:\n                        in_sample = False\n                        sample = Sample(sample_lines)\n                        sample_lines = []\n                        if self.filter_sample(sample):\n                            yield sample\n                if in_sample:\n                    sample_lines.append(line)\n\n    def filter_sample(self, sample: Sample) -> bool:\n        \"\"\" Return true if the input sample passes filters. \"\"\"\n        for exclude_filter in self.exclude_filters:\n            if exclude_filter.match(sample):\n                return False\n        for include_filter in self.include_filters:\n            if not include_filter.match(sample):\n                return False\n        return True\n\n\nclass ReportOutput:\n    def report(self, sample: Sample):\n        pass\n\n    def end_report(self):\n        pass\n\n\nclass ReportOutputDetails(ReportOutput):\n    def report(self, sample: Sample):\n        for line in sample.raw_lines:\n            print(line)\n        print()\n\n\nclass ReportOutputSummary(ReportOutput):\n    def __init__(self):\n        self.error_code_counter = Counter()\n        self.symbol_counters: Dict[int, Counter] = defaultdict(Counter)\n\n    def report(self, sample: Sample):\n        symbol_key = (sample.callchain[-1].dso, sample.callchain[-1].symbol)\n        self.symbol_counters[sample.error_code][symbol_key] += 1\n        self.error_code_counter[sample.error_code] += 1\n\n    def end_report(self):\n        self.draw_error_code_table()\n        self.draw_symbol_table()\n\n    def draw_error_code_table(self):\n        table = Texttable()\n        table.set_cols_align(['l', 'c'])\n        table.add_row(['Count', 'Error Code'])\n        for error_code, count in self.error_code_counter.most_common():\n            table.add_row([count, error_code])\n        print(table.draw())\n\n    def draw_symbol_table(self):\n        table = Texttable()\n        table.set_cols_align(['l', 'c', 'l', 'l'])\n        table.add_row(['Count', 'Error Code', 'Dso', 'Symbol'])\n        for error_code, _ in self.error_code_counter.most_common():\n            symbol_counter = self.symbol_counters[error_code]\n            for symbol_key, count in symbol_counter.most_common():\n                dso, symbol = symbol_key\n                table.add_row([count, error_code, dso, symbol])\n        print(table.draw())\n\n\ndef get_args() -> argparse.Namespace:\n    parser = BaseArgumentParser(description=__doc__)\n    parser.add_argument('-i', '--input-file', required=True,\n                        help='report file generated by debug-unwind cmd')\n    parser.add_argument(\n        '--show-callchain-fixed-by-joiner', action='store_true',\n        help=\"\"\"By default, we don't show failed unwinding cases fixed by callchain joiner.\n                Use this option to show them.\"\"\")\n    parser.add_argument('--summary', action='store_true',\n                        help='show summary instead of case details')\n    parser.add_argument('--exclude-error-code', metavar='error_code', type=int, nargs='+',\n                        help='exclude cases with selected error code')\n    parser.add_argument('--exclude-end-dso', metavar='dso', nargs='+',\n                        help='exclude cases ending at selected binary')\n    parser.add_argument('--exclude-end-symbol', metavar='symbol', nargs='+',\n                        help='exclude cases ending at selected symbol')\n    parser.add_argument('--exclude-sample-time', metavar='time', type=int,\n                        nargs='+', help='exclude cases with selected sample time')\n    parser.add_argument('--include-error-code', metavar='error_code', type=int,\n                        nargs='+', help='include cases with selected error code')\n    parser.add_argument('--include-end-dso', metavar='dso', nargs='+',\n                        help='include cases ending at selected binary')\n    parser.add_argument('--include-end-symbol', metavar='symbol', nargs='+',\n                        help='include cases ending at selected symbol')\n    parser.add_argument('--include-sample-time', metavar='time', type=int,\n                        nargs='+', help='include cases with selected sample time')\n    return parser.parse_args()\n\n\ndef main():\n    args = get_args()\n    report_input = ReportInput()\n    report_input.set_filters(args)\n    report_output = ReportOutputSummary() if args.summary else ReportOutputDetails()\n    for sample in report_input.get_samples(args.input_file):\n        report_output.report(sample)\n    report_output.end_report()\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "simpleperf/gecko_profile_generator.py",
    "content": "#!/usr/bin/env python3\n#\n# Copyright (C) 2021 The Android Open Source Project\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\"\"\"gecko_profile_generator.py: converts perf.data to Gecko Profile Format,\n    which can be read by https://profiler.firefox.com/.\n\n  Example:\n    ./app_profiler.py\n    ./gecko_profile_generator.py | gzip > gecko-profile.json.gz\n\n  Then open gecko-profile.json.gz in https://profiler.firefox.com/\n\"\"\"\n\nimport json\nimport sys\n\nfrom dataclasses import dataclass, field\nfrom simpleperf_report_lib import ReportLib\nfrom simpleperf_utils import BaseArgumentParser, flatten_arg_list\nfrom typing import List, Dict, Optional, NamedTuple, Set, Tuple\n\n\nStringID = int\nStackID = int\nFrameID = int\nCategoryID = int\nMilliseconds = float\nGeckoProfile = Dict\n\n\n# https://github.com/firefox-devtools/profiler/blob/53970305b51b9b472e26d7457fee1d66cd4e2737/src/types/gecko-profile.js#L156\nclass Frame(NamedTuple):\n    string_id: StringID\n    relevantForJS: bool\n    innerWindowID: int\n    implementation: None\n    optimizations: None\n    line: None\n    column: None\n    category: CategoryID\n    subcategory: int\n\n\n# https://github.com/firefox-devtools/profiler/blob/53970305b51b9b472e26d7457fee1d66cd4e2737/src/types/gecko-profile.js#L216\nclass Stack(NamedTuple):\n    prefix_id: Optional[StackID]\n    frame_id: FrameID\n    category_id: CategoryID\n\n\n# https://github.com/firefox-devtools/profiler/blob/53970305b51b9b472e26d7457fee1d66cd4e2737/src/types/gecko-profile.js#L90\nclass Sample(NamedTuple):\n    stack_id: Optional[StackID]\n    time_ms: Milliseconds\n    responsiveness: int\n\n\n# Schema: https://github.com/firefox-devtools/profiler/blob/53970305b51b9b472e26d7457fee1d66cd4e2737/src/types/profile.js#L425\n# Colors must be defined in:\n# https://github.com/firefox-devtools/profiler/blob/50124adbfa488adba6e2674a8f2618cf34b59cd2/res/css/categories.css\nCATEGORIES = [\n    {\n        \"name\": 'User',\n        # Follow Brendan Gregg's Flamegraph convention: yellow for userland\n        # https://github.com/brendangregg/FlameGraph/blob/810687f180f3c4929b5d965f54817a5218c9d89b/flamegraph.pl#L419\n        \"color\": 'yellow',\n        \"subcategories\": ['Other']\n    },\n    {\n        \"name\": 'Kernel',\n        # Follow Brendan Gregg's Flamegraph convention: orange for kernel\n        # https://github.com/brendangregg/FlameGraph/blob/810687f180f3c4929b5d965f54817a5218c9d89b/flamegraph.pl#L417\n        \"color\": 'orange',\n        \"subcategories\": ['Other']\n    },\n    {\n        \"name\": 'Native',\n        # Follow Brendan Gregg's Flamegraph convention: yellow for userland\n        # https://github.com/brendangregg/FlameGraph/blob/810687f180f3c4929b5d965f54817a5218c9d89b/flamegraph.pl#L419\n        \"color\": 'yellow',\n        \"subcategories\": ['Other']\n    },\n    {\n        \"name\": 'DEX',\n        # Follow Brendan Gregg's Flamegraph convention: green for Java/JIT\n        # https://github.com/brendangregg/FlameGraph/blob/810687f180f3c4929b5d965f54817a5218c9d89b/flamegraph.pl#L411\n        \"color\": 'green',\n        \"subcategories\": ['Other']\n    },\n    {\n        \"name\": 'OAT',\n        # Follow Brendan Gregg's Flamegraph convention: green for Java/JIT\n        # https://github.com/brendangregg/FlameGraph/blob/810687f180f3c4929b5d965f54817a5218c9d89b/flamegraph.pl#L411\n        \"color\": 'green',\n        \"subcategories\": ['Other']\n    },\n    # Not used by this exporter yet, but some Firefox Profiler code assumes\n    # there is an 'Other' category by searching for a category with\n    # color=grey, so include this.\n    {\n        \"name\": 'Other',\n        \"color\": 'grey',\n        \"subcategories\": ['Other']\n    },\n]\n\n\n@dataclass\nclass Thread:\n    \"\"\"A builder for a profile of a single thread.\n\n    Attributes:\n      comm: Thread command-line (name).\n      pid: process ID of containing process.\n      tid: thread ID.\n      samples: Timeline of profile samples.\n      frameTable: interned stack frame ID -> stack frame.\n      stringTable: interned string ID -> string.\n      stringMap: interned string -> string ID.\n      stackTable: interned stack ID -> stack.\n      stackMap: (stack prefix ID, leaf stack frame ID) -> interned Stack ID.\n      frameMap: Stack Frame string -> interned Frame ID.\n    \"\"\"\n    comm: str\n    pid: int\n    tid: int\n    samples: List[Sample] = field(default_factory=list)\n    frameTable: List[Frame] = field(default_factory=list)\n    stringTable: List[str] = field(default_factory=list)\n    # TODO: this is redundant with frameTable, could we remove this?\n    stringMap: Dict[str, int] = field(default_factory=dict)\n    stackTable: List[Stack] = field(default_factory=list)\n    stackMap: Dict[Tuple[Optional[int], int], int] = field(default_factory=dict)\n    frameMap: Dict[str, int] = field(default_factory=dict)\n\n    def _intern_stack(self, frame_id: int, prefix_id: Optional[int]) -> int:\n        \"\"\"Gets a matching stack, or saves the new stack. Returns a Stack ID.\"\"\"\n        key = (prefix_id, frame_id)\n        stack_id = self.stackMap.get(key)\n        if stack_id is not None:\n            return stack_id\n        stack_id = len(self.stackTable)\n        self.stackTable.append(Stack(prefix_id=prefix_id,\n                                     frame_id=frame_id,\n                                     category_id=0))\n        self.stackMap[key] = stack_id\n        return stack_id\n\n    def _intern_string(self, string: str) -> int:\n        \"\"\"Gets a matching string, or saves the new string. Returns a String ID.\"\"\"\n        string_id = self.stringMap.get(string)\n        if string_id is not None:\n            return string_id\n        string_id = len(self.stringTable)\n        self.stringTable.append(string)\n        self.stringMap[string] = string_id\n        return string_id\n\n    def _intern_frame(self, frame_str: str) -> int:\n        \"\"\"Gets a matching stack frame, or saves the new frame. Returns a Frame ID.\"\"\"\n        frame_id = self.frameMap.get(frame_str)\n        if frame_id is not None:\n            return frame_id\n        frame_id = len(self.frameTable)\n        self.frameMap[frame_str] = frame_id\n        string_id = self._intern_string(frame_str)\n\n        category = 0\n        # Heuristic: kernel code contains \"kallsyms\" as the library name.\n        if \"kallsyms\" in frame_str or \".ko\" in frame_str:\n            category = 1\n        elif \".so\" in frame_str:\n            category = 2\n        elif \".vdex\" in frame_str:\n            category = 3\n        elif \".oat\" in frame_str:\n            category = 4\n\n        self.frameTable.append(Frame(\n            string_id=string_id,\n            relevantForJS=False,\n            innerWindowID=0,\n            implementation=None,\n            optimizations=None,\n            line=None,\n            column=None,\n            category=category,\n            subcategory=0,\n        ))\n        return frame_id\n\n    def _add_sample(self, comm: str, stack: List[str], time_ms: Milliseconds) -> None:\n        \"\"\"Add a timestamped stack trace sample to the thread builder.\n\n        Args:\n          comm: command-line (name) of the thread at this sample\n          stack: sampled stack frames. Root first, leaf last.\n          time_ms: timestamp of sample in milliseconds\n        \"\"\"\n        # Unix threads often don't set their name immediately upon creation.\n        # Use the last name\n        if self.comm != comm:\n            self.comm = comm\n\n        prefix_stack_id = None\n        for frame in stack:\n            frame_id = self._intern_frame(frame)\n            prefix_stack_id = self._intern_stack(frame_id, prefix_stack_id)\n\n        self.samples.append(Sample(stack_id=prefix_stack_id,\n                                   time_ms=time_ms,\n                                   responsiveness=0))\n\n    def _to_json_dict(self) -> Dict:\n        \"\"\"Converts this Thread to GeckoThread JSON format.\"\"\"\n        # The samples aren't guaranteed to be in order. Sort them by time.\n        self.samples.sort(key=lambda s: s.time_ms)\n\n        # Gecko profile format is row-oriented data as List[List],\n        # And a schema for interpreting each index.\n        # Schema:\n        # https://github.com/firefox-devtools/profiler/blob/main/docs-developer/gecko-profile-format.md\n        # https://github.com/firefox-devtools/profiler/blob/53970305b51b9b472e26d7457fee1d66cd4e2737/src/types/gecko-profile.js#L230\n        return {\n            \"tid\": self.tid,\n            \"pid\": self.pid,\n            \"name\": self.comm,\n            # https://github.com/firefox-devtools/profiler/blob/53970305b51b9b472e26d7457fee1d66cd4e2737/src/types/gecko-profile.js#L51\n            \"markers\": {\n                \"schema\": {\n                    \"name\": 0,\n                    \"startTime\": 1,\n                    \"endTime\": 2,\n                    \"phase\": 3,\n                    \"category\": 4,\n                    \"data\": 5,\n                },\n                \"data\": [],\n            },\n            # https://github.com/firefox-devtools/profiler/blob/53970305b51b9b472e26d7457fee1d66cd4e2737/src/types/gecko-profile.js#L90\n            \"samples\": {\n                \"schema\": {\n                    \"stack\": 0,\n                    \"time\": 1,\n                    \"responsiveness\": 2,\n                },\n                \"data\": self.samples\n            },\n            # https://github.com/firefox-devtools/profiler/blob/53970305b51b9b472e26d7457fee1d66cd4e2737/src/types/gecko-profile.js#L156\n            \"frameTable\": {\n                \"schema\": {\n                    \"location\": 0,\n                    \"relevantForJS\": 1,\n                    \"innerWindowID\": 2,\n                    \"implementation\": 3,\n                    \"optimizations\": 4,\n                    \"line\": 5,\n                    \"column\": 6,\n                    \"category\": 7,\n                    \"subcategory\": 8,\n                },\n                \"data\": self.frameTable,\n            },\n            # https://github.com/firefox-devtools/profiler/blob/53970305b51b9b472e26d7457fee1d66cd4e2737/src/types/gecko-profile.js#L216\n            \"stackTable\": {\n                \"schema\": {\n                    \"prefix\": 0,\n                    \"frame\": 1,\n                    \"category\": 2,\n                },\n                \"data\": self.stackTable,\n            },\n            \"stringTable\": self.stringTable,\n            \"registerTime\": 0,\n            \"unregisterTime\": None,\n            \"processType\": \"default\",\n        }\n\n\ndef _gecko_profile(\n        record_file: str,\n        symfs_dir: Optional[str],\n        kallsyms_file: Optional[str],\n        proguard_mapping_file: List[str],\n        comm_filter: Set[str],\n        sample_filter: Optional[str]) -> GeckoProfile:\n    \"\"\"convert a simpleperf profile to gecko format\"\"\"\n    lib = ReportLib()\n\n    lib.ShowIpForUnknownSymbol()\n    for file_path in proguard_mapping_file:\n        lib.AddProguardMappingFile(file_path)\n    if symfs_dir is not None:\n        lib.SetSymfs(symfs_dir)\n    lib.SetRecordFile(record_file)\n    if kallsyms_file is not None:\n        lib.SetKallsymsFile(kallsyms_file)\n    if sample_filter:\n        lib.SetSampleFilter(sample_filter)\n\n    arch = lib.GetArch()\n    meta_info = lib.MetaInfo()\n    record_cmd = lib.GetRecordCmd()\n\n    # Map from tid to Thread\n    threadMap: Dict[int, Thread] = {}\n\n    while True:\n        sample = lib.GetNextSample()\n        if sample is None:\n            lib.Close()\n            break\n        if comm_filter:\n            if sample.thread_comm not in comm_filter:\n                continue\n        event = lib.GetEventOfCurrentSample()\n        symbol = lib.GetSymbolOfCurrentSample()\n        callchain = lib.GetCallChainOfCurrentSample()\n        sample_time_ms = sample.time / 1000000\n\n        stack = ['%s (in %s)' % (symbol.symbol_name, symbol.dso_name)]\n        for i in range(callchain.nr):\n            entry = callchain.entries[i]\n            stack.append('%s (in %s)' % (entry.symbol.symbol_name, entry.symbol.dso_name))\n        # We want root first, leaf last.\n        stack.reverse()\n\n        # add thread sample\n        thread = threadMap.get(sample.tid)\n        if thread is None:\n            thread = Thread(comm=sample.thread_comm, pid=sample.pid, tid=sample.tid)\n            threadMap[sample.tid] = thread\n        thread._add_sample(\n            comm=sample.thread_comm,\n            stack=stack,\n            # We are being a bit fast and loose here with time here.  simpleperf\n            # uses CLOCK_MONOTONIC by default, which doesn't use the normal unix\n            # epoch, but rather some arbitrary time. In practice, this doesn't\n            # matter, the Firefox Profiler normalises all the timestamps to begin at\n            # the minimum time.  Consider fixing this in future, if needed, by\n            # setting `simpleperf record --clockid realtime`.\n            time_ms=sample_time_ms)\n\n    threads = [thread._to_json_dict() for thread in threadMap.values()]\n\n    profile_timestamp = meta_info.get('timestamp')\n    end_time_ms = (int(profile_timestamp) * 1000) if profile_timestamp else 0\n\n    # Schema: https://github.com/firefox-devtools/profiler/blob/53970305b51b9b472e26d7457fee1d66cd4e2737/src/types/gecko-profile.js#L305\n    gecko_profile_meta = {\n        \"interval\": 1,\n        \"processType\": 0,\n        \"product\": record_cmd,\n        \"device\": meta_info.get(\"product_props\"),\n        \"platform\": meta_info.get(\"android_build_fingerprint\"),\n        \"stackwalk\": 1,\n        \"debug\": 0,\n        \"gcpoison\": 0,\n        \"asyncstack\": 1,\n        # The profile timestamp is actually the end time, not the start time.\n        # This is close enough for our purposes; I mostly just want to know which\n        # day the profile was taken! Consider fixing this in future, if needed,\n        # by setting `simpleperf record --clockid realtime` and taking the minimum\n        # sample time.\n        \"startTime\": end_time_ms,\n        \"shutdownTime\": None,\n        \"version\": 24,\n        \"presymbolicated\": True,\n        \"categories\": CATEGORIES,\n        \"markerSchema\": [],\n        \"abi\": arch,\n        \"oscpu\": meta_info.get(\"android_build_fingerprint\"),\n    }\n\n    # Schema:\n    # https://github.com/firefox-devtools/profiler/blob/53970305b51b9b472e26d7457fee1d66cd4e2737/src/types/gecko-profile.js#L377\n    # https://github.com/firefox-devtools/profiler/blob/main/docs-developer/gecko-profile-format.md\n    return {\n        \"meta\": gecko_profile_meta,\n        \"libs\": [],\n        \"threads\": threads,\n        \"processes\": [],\n        \"pausedRanges\": [],\n    }\n\n\ndef main() -> None:\n    parser = BaseArgumentParser(description=__doc__)\n    parser.add_argument('--symfs',\n                        help='Set the path to find binaries with symbols and debug info.')\n    parser.add_argument('--kallsyms', help='Set the path to find kernel symbols.')\n    parser.add_argument('-i', '--record_file', nargs='?', default='perf.data',\n                        help='Default is perf.data.')\n    parser.add_argument(\n        '--proguard-mapping-file', nargs='+',\n        help='Add proguard mapping file to de-obfuscate symbols',\n        default=[])\n    sample_filter_group = parser.add_argument_group('Sample filter options')\n    parser.add_sample_filter_options(sample_filter_group)\n    sample_filter_group.add_argument('--comm', nargs='+', action='append', help=\"\"\"\n      Use samples only in threads with selected names.\"\"\")\n    args = parser.parse_args()\n    profile = _gecko_profile(\n        record_file=args.record_file,\n        symfs_dir=args.symfs,\n        kallsyms_file=args.kallsyms,\n        proguard_mapping_file=args.proguard_mapping_file,\n        comm_filter=set(flatten_arg_list(args.comm)),\n        sample_filter=args.sample_filter)\n\n    json.dump(profile, sys.stdout, sort_keys=True)\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "simpleperf/pprof_proto_generator.py",
    "content": "#!/usr/bin/env python3\n#\n# Copyright (C) 2017 The Android Open Source Project\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\"\"\"pprof_proto_generator.py: read perf.data, generate pprof.profile, which can be\n    used by pprof.\n\n  Example:\n    ./app_profiler.py\n    ./pprof_proto_generator.py\n    pprof -text pprof.profile\n\"\"\"\n\nimport logging\nimport os\nimport os.path\nimport re\nimport sys\n\nfrom simpleperf_report_lib import ReportLib\nfrom simpleperf_utils import (Addr2Nearestline, BaseArgumentParser, BinaryFinder, extant_dir,\n                              flatten_arg_list, log_exit, ReadElf, ToolFinder)\ntry:\n    import profile_pb2\nexcept ImportError:\n    log_exit('google.protobuf module is missing. Please install it first.')\n\n\n# Some units of common event names\nEVENT_UNITS = {\n    'cpu-clock': 'nanoseconds',\n    'cpu-cycles': 'cpu-cycles',\n    'instructions': 'instructions',\n    'task-clock': 'nanoseconds',\n}\n\n\ndef load_pprof_profile(filename):\n    profile = profile_pb2.Profile()\n    with open(filename, \"rb\") as f:\n        profile.ParseFromString(f.read())\n    return profile\n\n\ndef store_pprof_profile(filename, profile):\n    with open(filename, 'wb') as f:\n        f.write(profile.SerializeToString())\n\n\nclass PprofProfilePrinter(object):\n\n    def __init__(self, profile):\n        self.profile = profile\n        self.string_table = profile.string_table\n\n    def show(self):\n        p = self.profile\n        sub_space = '  '\n        print('Profile {')\n        print('%d sample_types' % len(p.sample_type))\n        for i in range(len(p.sample_type)):\n            print('sample_type[%d] = ' % i, end='')\n            self.show_value_type(p.sample_type[i])\n        print('%d samples' % len(p.sample))\n        for i in range(len(p.sample)):\n            print('sample[%d]:' % i)\n            self.show_sample(p.sample[i], sub_space)\n        print('%d mappings' % len(p.mapping))\n        for i in range(len(p.mapping)):\n            print('mapping[%d]:' % i)\n            self.show_mapping(p.mapping[i], sub_space)\n        print('%d locations' % len(p.location))\n        for i in range(len(p.location)):\n            print('location[%d]:' % i)\n            self.show_location(p.location[i], sub_space)\n        for i in range(len(p.function)):\n            print('function[%d]:' % i)\n            self.show_function(p.function[i], sub_space)\n        print('%d strings' % len(p.string_table))\n        for i in range(len(p.string_table)):\n            print('string[%d]: %s' % (i, p.string_table[i]))\n        print('drop_frames: %s' % self.string(p.drop_frames))\n        print('keep_frames: %s' % self.string(p.keep_frames))\n        print('time_nanos: %u' % p.time_nanos)\n        print('duration_nanos: %u' % p.duration_nanos)\n        print('period_type: ', end='')\n        self.show_value_type(p.period_type)\n        print('period: %u' % p.period)\n        for i in range(len(p.comment)):\n            print('comment[%d] = %s' % (i, self.string(p.comment[i])))\n        print('default_sample_type: %d' % p.default_sample_type)\n        print('} // Profile')\n        print()\n\n    def show_value_type(self, value_type, space=''):\n        print('%sValueType(typeID=%d, unitID=%d, type=%s, unit=%s)' %\n              (space, value_type.type, value_type.unit,\n               self.string(value_type.type), self.string(value_type.unit)))\n\n    def show_sample(self, sample, space=''):\n        sub_space = space + '  '\n        for i in range(len(sample.location_id)):\n            print('%slocation_id[%d]: id %d' % (space, i, sample.location_id[i]))\n            self.show_location_id(sample.location_id[i], sub_space)\n        for i in range(len(sample.value)):\n            print('%svalue[%d] = %d' % (space, i, sample.value[i]))\n        for i in range(len(sample.label)):\n            print('%slabel[%d] = %s:%s' % (space, i, self.string(sample.label[i].key),\n                                           self.string(sample.label[i].str)))\n\n    def show_location_id(self, location_id, space=''):\n        location = self.profile.location[location_id - 1]\n        self.show_location(location, space)\n\n    def show_location(self, location, space=''):\n        sub_space = space + '  '\n        print('%sid: %d' % (space, location.id))\n        print('%smapping_id: %d' % (space, location.mapping_id))\n        self.show_mapping_id(location.mapping_id, sub_space)\n        print('%saddress: %x' % (space, location.address))\n        for i in range(len(location.line)):\n            print('%sline[%d]:' % (space, i))\n            self.show_line(location.line[i], sub_space)\n\n    def show_mapping_id(self, mapping_id, space=''):\n        mapping = self.profile.mapping[mapping_id - 1]\n        self.show_mapping(mapping, space)\n\n    def show_mapping(self, mapping, space=''):\n        print('%sid: %d' % (space, mapping.id))\n        print('%smemory_start: %x' % (space, mapping.memory_start))\n        print('%smemory_limit: %x' % (space, mapping.memory_limit))\n        print('%sfile_offset: %x' % (space, mapping.file_offset))\n        print('%sfilename: %s(%d)' % (space, self.string(mapping.filename),\n                                      mapping.filename))\n        print('%sbuild_id: %s(%d)' % (space, self.string(mapping.build_id),\n                                      mapping.build_id))\n        print('%shas_functions: %s' % (space, mapping.has_functions))\n        print('%shas_filenames: %s' % (space, mapping.has_filenames))\n        print('%shas_line_numbers: %s' % (space, mapping.has_line_numbers))\n        print('%shas_inline_frames: %s' % (space, mapping.has_inline_frames))\n\n    def show_line(self, line, space=''):\n        sub_space = space + '  '\n        print('%sfunction_id: %d' % (space, line.function_id))\n        self.show_function_id(line.function_id, sub_space)\n        print('%sline: %d' % (space, line.line))\n\n    def show_function_id(self, function_id, space=''):\n        function = self.profile.function[function_id - 1]\n        self.show_function(function, space)\n\n    def show_function(self, function, space=''):\n        print('%sid: %d' % (space, function.id))\n        print('%sname: %s' % (space, self.string(function.name)))\n        print('%ssystem_name: %s' % (space, self.string(function.system_name)))\n        print('%sfilename: %s' % (space, self.string(function.filename)))\n        print('%sstart_line: %d' % (space, function.start_line))\n\n    def string(self, string_id):\n        return self.string_table[string_id]\n\n\nclass Label(object):\n    def __init__(self, key_id: int, str_id: int):\n        # See profile.Label.key\n        self.key_id = key_id\n        # See profile.Label.str\n        self.str_id = str_id\n\n\nclass Sample(object):\n\n    def __init__(self):\n        self.location_ids = []\n        self.values = {}\n        self.labels = []\n\n    def add_location_id(self, location_id):\n        self.location_ids.append(location_id)\n\n    def add_value(self, sample_type_id, value):\n        self.values[sample_type_id] = self.values.get(sample_type_id, 0) + value\n\n    def add_values(self, values):\n        for sample_type_id, value in values.items():\n            self.add_value(sample_type_id, value)\n\n    @property\n    def key(self):\n        return tuple(self.location_ids)\n\n\nclass Location(object):\n\n    def __init__(self, mapping_id, address, vaddr_in_dso):\n        self.id = -1  # unset\n        self.mapping_id = mapping_id\n        self.address = address\n        self.vaddr_in_dso = vaddr_in_dso\n        self.lines = []\n\n    @property\n    def key(self):\n        return (self.mapping_id, self.address)\n\n\nclass Line(object):\n\n    def __init__(self):\n        self.function_id = 0\n        self.line = 0\n\n\nclass Mapping(object):\n\n    def __init__(self, start, end, pgoff, filename_id, build_id_id):\n        self.id = -1  # unset\n        self.memory_start = start\n        self.memory_limit = end\n        self.file_offset = pgoff\n        self.filename_id = filename_id\n        self.build_id_id = build_id_id\n\n    @property\n    def key(self):\n        return (\n            self.memory_start,\n            self.memory_limit,\n            self.file_offset,\n            self.filename_id,\n            self.build_id_id)\n\n\nclass Function(object):\n\n    def __init__(self, name_id, dso_name_id, vaddr_in_dso):\n        self.id = -1  # unset\n        self.name_id = name_id\n        self.dso_name_id = dso_name_id\n        self.vaddr_in_dso = vaddr_in_dso\n        self.source_filename_id = 0\n        self.start_line = 0\n\n    @property\n    def key(self):\n        return (self.name_id, self.dso_name_id)\n\n\n# pylint: disable=no-member\nclass PprofProfileGenerator(object):\n\n    def __init__(self, config):\n        self.config = config\n        self.lib = None\n\n        config['binary_cache_dir'] = 'binary_cache'\n        if not os.path.isdir(config['binary_cache_dir']):\n            config['binary_cache_dir'] = None\n        self.comm_filter = set(config['comm_filters']) if config.get('comm_filters') else None\n        self.dso_filter = set(config['dso_filters']) if config.get('dso_filters') else None\n        self.max_chain_length = config['max_chain_length']\n        self.profile = profile_pb2.Profile()\n        self.profile.string_table.append('')\n        self.string_table = {}\n        self.sample_types = {}\n        self.sample_map = {}\n        self.sample_list = []\n        self.location_map = {}\n        self.location_list = []\n        self.mapping_map = {}\n        self.mapping_list = []\n        self.function_map = {}\n        self.function_list = []\n\n        # Map from dso_name in perf.data to (binary path, build_id).\n        self.binary_map = {}\n        self.read_elf = ReadElf(self.config['ndk_path'])\n        self.binary_finder = BinaryFinder(config['binary_cache_dir'], self.read_elf)\n\n    def load_record_file(self, record_file):\n        self.lib = ReportLib()\n        self.lib.SetRecordFile(record_file)\n\n        if self.config['binary_cache_dir']:\n            self.lib.SetSymfs(self.config['binary_cache_dir'])\n            kallsyms = os.path.join(self.config['binary_cache_dir'], 'kallsyms')\n            if os.path.isfile(kallsyms):\n                self.lib.SetKallsymsFile(kallsyms)\n\n        if self.config.get('show_art_frames'):\n            self.lib.ShowArtFrames()\n        for file_path in self.config['proguard_mapping_file'] or []:\n            self.lib.AddProguardMappingFile(file_path)\n        if self.config.get('sample_filter'):\n            self.lib.SetSampleFilter(self.config['sample_filter'])\n\n        comments = [\n            \"Simpleperf Record Command:\\n\" + self.lib.GetRecordCmd(),\n            \"Converted to pprof with:\\n\" + \" \".join(sys.argv),\n            \"Architecture:\\n\" + self.lib.GetArch(),\n        ]\n        for comment in comments:\n            self.profile.comment.append(self.get_string_id(comment))\n\n        numbers_re = re.compile(r\"\\d+\")\n\n        # Process all samples in perf.data, aggregate samples.\n        while True:\n            report_sample = self.lib.GetNextSample()\n            if report_sample is None:\n                self.lib.Close()\n                self.lib = None\n                break\n            event = self.lib.GetEventOfCurrentSample()\n            symbol = self.lib.GetSymbolOfCurrentSample()\n            callchain = self.lib.GetCallChainOfCurrentSample()\n\n            if not self._filter_report_sample(report_sample):\n                continue\n\n            sample_type_id = self.get_sample_type_id(event.name)\n            sample = Sample()\n            sample.add_value(sample_type_id, 1)\n            sample.add_value(sample_type_id + 1, report_sample.period)\n            sample.labels.append(Label(\n                self.get_string_id(\"thread\"),\n                self.get_string_id(report_sample.thread_comm)))\n            # Heuristic: threadpools doing similar work are often named as\n            # name-1, name-2, name-3. Combine threadpools into one label\n            # \"name-%d\" if they only differ by a number.\n            sample.labels.append(Label(\n                self.get_string_id(\"threadpool\"),\n                self.get_string_id(\n                    numbers_re.sub(\"%d\", report_sample.thread_comm))))\n            sample.labels.append(Label(\n                self.get_string_id(\"pid\"),\n                self.get_string_id(str(report_sample.pid))))\n            sample.labels.append(Label(\n                self.get_string_id(\"tid\"),\n                self.get_string_id(str(report_sample.tid))))\n            if self._filter_symbol(symbol):\n                location_id = self.get_location_id(report_sample.ip, symbol)\n                sample.add_location_id(location_id)\n            for i in range(max(0, callchain.nr - self.max_chain_length), callchain.nr):\n                entry = callchain.entries[i]\n                if self._filter_symbol(symbol):\n                    location_id = self.get_location_id(entry.ip, entry.symbol)\n                    sample.add_location_id(location_id)\n            if sample.location_ids:\n                self.add_sample(sample)\n\n    def gen(self, jobs: int):\n        # 1. Generate line info for locations and functions.\n        self.gen_source_lines(jobs)\n\n        # 2. Produce samples/locations/functions in profile.\n        for sample in self.sample_list:\n            self.gen_profile_sample(sample)\n        for mapping in self.mapping_list:\n            self.gen_profile_mapping(mapping)\n        for location in self.location_list:\n            self.gen_profile_location(location)\n        for function in self.function_list:\n            self.gen_profile_function(function)\n\n        return self.profile\n\n    def _filter_report_sample(self, sample):\n        \"\"\"Return true if the sample can be used.\"\"\"\n        if self.comm_filter:\n            if sample.thread_comm not in self.comm_filter:\n                return False\n        return True\n\n    def _filter_symbol(self, symbol):\n        if not self.dso_filter or symbol.dso_name in self.dso_filter:\n            return True\n        return False\n\n    def get_string_id(self, str_value):\n        if not str_value:\n            return 0\n        str_id = self.string_table.get(str_value)\n        if str_id is not None:\n            return str_id\n        str_id = len(self.string_table) + 1\n        self.string_table[str_value] = str_id\n        self.profile.string_table.append(str_value)\n        return str_id\n\n    def get_string(self, str_id):\n        return self.profile.string_table[str_id]\n\n    def get_sample_type_id(self, name):\n        sample_type_id = self.sample_types.get(name)\n        if sample_type_id is not None:\n            return sample_type_id\n        sample_type_id = len(self.profile.sample_type)\n        sample_type = self.profile.sample_type.add()\n        sample_type.type = self.get_string_id(name + '_samples')\n        sample_type.unit = self.get_string_id('samples')\n        sample_type = self.profile.sample_type.add()\n        sample_type.type = self.get_string_id(name)\n        units = EVENT_UNITS.get(name, 'count')\n        sample_type.unit = self.get_string_id(units)\n        self.sample_types[name] = sample_type_id\n        return sample_type_id\n\n    def get_location_id(self, ip, symbol):\n        binary_path, build_id = self.get_binary(symbol.dso_name)\n        mapping_id = self.get_mapping_id(symbol.mapping[0], binary_path, build_id)\n        location = Location(mapping_id, ip, symbol.vaddr_in_file)\n        function_id = self.get_function_id(symbol.symbol_name, binary_path, symbol.symbol_addr)\n        if function_id:\n            # Add Line only when it has a valid function id, see http://b/36988814.\n            # Default line info only contains the function name\n            line = Line()\n            line.function_id = function_id\n            location.lines.append(line)\n\n        exist_location = self.location_map.get(location.key)\n        if exist_location:\n            return exist_location.id\n        # location_id starts from 1\n        location.id = len(self.location_list) + 1\n        self.location_list.append(location)\n        self.location_map[location.key] = location\n        return location.id\n\n    def get_mapping_id(self, report_mapping, filename, build_id):\n        filename_id = self.get_string_id(filename)\n        build_id_id = self.get_string_id(build_id)\n        mapping = Mapping(report_mapping.start, report_mapping.end,\n                          report_mapping.pgoff, filename_id, build_id_id)\n        exist_mapping = self.mapping_map.get(mapping.key)\n        if exist_mapping:\n            return exist_mapping.id\n        # mapping_id starts from 1\n        mapping.id = len(self.mapping_list) + 1\n        self.mapping_list.append(mapping)\n        self.mapping_map[mapping.key] = mapping\n        return mapping.id\n\n    def get_binary(self, dso_name):\n        \"\"\" Return (binary_path, build_id) for a given dso_name. \"\"\"\n        value = self.binary_map.get(dso_name)\n        if value:\n            return value\n\n        binary_path = dso_name\n        build_id = self.lib.GetBuildIdForPath(dso_name)\n        # Try elf_path in binary cache.\n        elf_path = self.binary_finder.find_binary(dso_name, build_id)\n        if elf_path:\n            binary_path = str(elf_path)\n\n        # The build ids in perf.data are padded to 20 bytes, but pprof needs without padding.\n        build_id = ReadElf.unpad_build_id(build_id)\n        self.binary_map[dso_name] = (binary_path, build_id)\n        return (binary_path, build_id)\n\n    def get_mapping(self, mapping_id):\n        return self.mapping_list[mapping_id - 1] if mapping_id > 0 else None\n\n    def get_function_id(self, name, dso_name, vaddr_in_file):\n        if name == 'unknown':\n            return 0\n        function = Function(self.get_string_id(name), self.get_string_id(dso_name), vaddr_in_file)\n        exist_function = self.function_map.get(function.key)\n        if exist_function:\n            return exist_function.id\n        # function_id starts from 1\n        function.id = len(self.function_list) + 1\n        self.function_list.append(function)\n        self.function_map[function.key] = function\n        return function.id\n\n    def get_function(self, function_id):\n        return self.function_list[function_id - 1] if function_id > 0 else None\n\n    def add_sample(self, sample):\n        exist_sample = self.sample_map.get(sample.key)\n        if exist_sample:\n            exist_sample.add_values(sample.values)\n        else:\n            self.sample_list.append(sample)\n            self.sample_map[sample.key] = sample\n\n    def gen_source_lines(self, jobs: int):\n        # 1. Create Addr2line instance\n        if not self.config.get('binary_cache_dir'):\n            logging.info(\"Can't generate line information because binary_cache is missing.\")\n            return\n        if not ToolFinder.find_tool_path('llvm-symbolizer', self.config['ndk_path']):\n            logging.info(\"Can't generate line information because can't find llvm-symbolizer.\")\n            return\n        # We have changed dso names to paths in binary_cache in self.get_binary(). So no need to\n        # pass binary_cache_dir to BinaryFinder.\n        binary_finder = BinaryFinder(None, self.read_elf)\n        addr2line = Addr2Nearestline(self.config['ndk_path'], binary_finder, True)\n\n        # 2. Put all needed addresses to it.\n        for location in self.location_list:\n            mapping = self.get_mapping(location.mapping_id)\n            dso_name = self.get_string(mapping.filename_id)\n            if location.lines:\n                function = self.get_function(location.lines[0].function_id)\n                addr2line.add_addr(dso_name, None, function.vaddr_in_dso, location.vaddr_in_dso)\n        for function in self.function_list:\n            dso_name = self.get_string(function.dso_name_id)\n            addr2line.add_addr(dso_name, None, function.vaddr_in_dso, function.vaddr_in_dso)\n\n        # 3. Generate source lines.\n        addr2line.convert_addrs_to_lines(jobs)\n\n        # 4. Annotate locations and functions.\n        for location in self.location_list:\n            if not location.lines:\n                continue\n            mapping = self.get_mapping(location.mapping_id)\n            dso_name = self.get_string(mapping.filename_id)\n            dso = addr2line.get_dso(dso_name)\n            if not dso:\n                continue\n            sources = addr2line.get_addr_source(dso, location.vaddr_in_dso)\n            if not sources:\n                continue\n            for i, source in enumerate(sources):\n                source_file, source_line, function_name = source\n                if i == 0:\n                    # Don't override original function name from report library, which is more\n                    # accurate when proguard mapping file is given.\n                    function_id = location.lines[0].function_id\n                    # Clear default line info.\n                    location.lines.clear()\n                else:\n                    function_id = self.get_function_id(function_name, dso_name, 0)\n                if function_id == 0:\n                    continue\n                location.lines.append(self.add_line(source_file, source_line, function_id))\n\n        for function in self.function_list:\n            dso_name = self.get_string(function.dso_name_id)\n            if function.vaddr_in_dso:\n                dso = addr2line.get_dso(dso_name)\n                if not dso:\n                    continue\n                sources = addr2line.get_addr_source(dso, function.vaddr_in_dso)\n                if sources:\n                    source_file, source_line, _ = sources[0]\n                    function.source_filename_id = self.get_string_id(source_file)\n                    function.start_line = source_line\n\n    def add_line(self, source_file, source_line, function_id):\n        line = Line()\n        function = self.get_function(function_id)\n        function.source_filename_id = self.get_string_id(source_file)\n        line.function_id = function_id\n        line.line = source_line\n        return line\n\n    def gen_profile_sample(self, sample):\n        profile_sample = self.profile.sample.add()\n        profile_sample.location_id.extend(sample.location_ids)\n        sample_type_count = len(self.sample_types) * 2\n        values = [0] * sample_type_count\n        for sample_type_id in sample.values:\n            values[sample_type_id] = sample.values[sample_type_id]\n        profile_sample.value.extend(values)\n\n        for l in sample.labels:\n            label = profile_sample.label.add()\n            label.key = l.key_id\n            label.str = l.str_id\n\n    def gen_profile_mapping(self, mapping):\n        profile_mapping = self.profile.mapping.add()\n        profile_mapping.id = mapping.id\n        profile_mapping.memory_start = mapping.memory_start\n        profile_mapping.memory_limit = mapping.memory_limit\n        profile_mapping.file_offset = mapping.file_offset\n        profile_mapping.filename = mapping.filename_id\n        profile_mapping.build_id = mapping.build_id_id\n        profile_mapping.has_filenames = True\n        profile_mapping.has_functions = True\n        if self.config.get('binary_cache_dir'):\n            profile_mapping.has_line_numbers = True\n            profile_mapping.has_inline_frames = True\n        else:\n            profile_mapping.has_line_numbers = False\n            profile_mapping.has_inline_frames = False\n\n    def gen_profile_location(self, location):\n        profile_location = self.profile.location.add()\n        profile_location.id = location.id\n        profile_location.mapping_id = location.mapping_id\n        profile_location.address = location.address\n        for i in range(len(location.lines)):\n            line = profile_location.line.add()\n            line.function_id = location.lines[i].function_id\n            line.line = location.lines[i].line\n\n    def gen_profile_function(self, function):\n        profile_function = self.profile.function.add()\n        profile_function.id = function.id\n        profile_function.name = function.name_id\n        profile_function.system_name = function.name_id\n        profile_function.filename = function.source_filename_id\n        profile_function.start_line = function.start_line\n\n\ndef main():\n    parser = BaseArgumentParser(description='Generate pprof profile data in pprof.profile.')\n    parser.add_argument('--show', nargs='?', action='append', help='print existing pprof.profile.')\n    parser.add_argument('-i', '--record_file', nargs='+', default=['perf.data'], help=\"\"\"\n        Set profiling data file to report. Default is perf.data\"\"\")\n    parser.add_argument('-o', '--output_file', default='pprof.profile', help=\"\"\"\n        The path of generated pprof profile data.\"\"\")\n    parser.add_argument('--max_chain_length', type=int, default=1000000000, help=\"\"\"\n        Maximum depth of samples to be converted.\"\"\")  # Large value as infinity standin.\n    parser.add_argument('--ndk_path', type=extant_dir, help='Set the path of a ndk release.')\n    parser.add_argument('--show_art_frames', action='store_true',\n                        help='Show frames of internal methods in the ART Java interpreter.')\n    parser.add_argument(\n        '--proguard-mapping-file', nargs='+',\n        help='Add proguard mapping file to de-obfuscate symbols')\n    parser.add_argument(\n        '-j', '--jobs', type=int, default=os.cpu_count(),\n        help='Use multithreading to speed up source code annotation.')\n    sample_filter_group = parser.add_argument_group('Sample filter options')\n    parser.add_sample_filter_options(sample_filter_group)\n    sample_filter_group.add_argument('--comm', nargs='+', action='append', help=\"\"\"\n        Use samples only in threads with selected names.\"\"\")\n    sample_filter_group.add_argument('--dso', nargs='+', action='append', help=\"\"\"\n        Use samples only in selected binaries.\"\"\")\n\n    args = parser.parse_args()\n    if args.show:\n        show_file = args.show[0] if args.show[0] else 'pprof.profile'\n        profile = load_pprof_profile(show_file)\n        printer = PprofProfilePrinter(profile)\n        printer.show()\n        return\n\n    config = {}\n    config['output_file'] = args.output_file\n    config['comm_filters'] = flatten_arg_list(args.comm)\n    config['dso_filters'] = flatten_arg_list(args.dso)\n    config['ndk_path'] = args.ndk_path\n    config['show_art_frames'] = args.show_art_frames\n    config['max_chain_length'] = args.max_chain_length\n    config['proguard_mapping_file'] = args.proguard_mapping_file\n    config['sample_filter'] = args.sample_filter\n    generator = PprofProfileGenerator(config)\n    for record_file in args.record_file:\n        generator.load_record_file(record_file)\n    profile = generator.gen(args.jobs)\n    store_pprof_profile(config['output_file'], profile)\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "simpleperf/profile_pb2.py",
    "content": "# Generated by the protocol buffer compiler.  DO NOT EDIT!\n# source: profile.proto\n\nimport sys\n_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))\nfrom google.protobuf import descriptor as _descriptor\nfrom google.protobuf import message as _message\nfrom google.protobuf import reflection as _reflection\nfrom google.protobuf import symbol_database as _symbol_database\nfrom google.protobuf import descriptor_pb2\n# @@protoc_insertion_point(imports)\n\n_sym_db = _symbol_database.Default()\n\n\n\n\nDESCRIPTOR = _descriptor.FileDescriptor(\n  name='profile.proto',\n  package='perftools.profiles',\n  syntax='proto3',\n  serialized_pb=_b('\\n\\rprofile.proto\\x12\\x12perftools.profiles\\\"\\xd5\\x03\\n\\x07Profile\\x12\\x32\\n\\x0bsample_type\\x18\\x01 \\x03(\\x0b\\x32\\x1d.perftools.profiles.ValueType\\x12*\\n\\x06sample\\x18\\x02 \\x03(\\x0b\\x32\\x1a.perftools.profiles.Sample\\x12,\\n\\x07mapping\\x18\\x03 \\x03(\\x0b\\x32\\x1b.perftools.profiles.Mapping\\x12.\\n\\x08location\\x18\\x04 \\x03(\\x0b\\x32\\x1c.perftools.profiles.Location\\x12.\\n\\x08\\x66unction\\x18\\x05 \\x03(\\x0b\\x32\\x1c.perftools.profiles.Function\\x12\\x14\\n\\x0cstring_table\\x18\\x06 \\x03(\\t\\x12\\x13\\n\\x0b\\x64rop_frames\\x18\\x07 \\x01(\\x03\\x12\\x13\\n\\x0bkeep_frames\\x18\\x08 \\x01(\\x03\\x12\\x12\\n\\ntime_nanos\\x18\\t \\x01(\\x03\\x12\\x16\\n\\x0e\\x64uration_nanos\\x18\\n \\x01(\\x03\\x12\\x32\\n\\x0bperiod_type\\x18\\x0b \\x01(\\x0b\\x32\\x1d.perftools.profiles.ValueType\\x12\\x0e\\n\\x06period\\x18\\x0c \\x01(\\x03\\x12\\x0f\\n\\x07\\x63omment\\x18\\r \\x03(\\x03\\x12\\x1b\\n\\x13\\x64\\x65\\x66\\x61ult_sample_type\\x18\\x0e \\x01(\\x03\\\"\\'\\n\\tValueType\\x12\\x0c\\n\\x04type\\x18\\x01 \\x01(\\x03\\x12\\x0c\\n\\x04unit\\x18\\x02 \\x01(\\x03\\\"V\\n\\x06Sample\\x12\\x13\\n\\x0blocation_id\\x18\\x01 \\x03(\\x04\\x12\\r\\n\\x05value\\x18\\x02 \\x03(\\x03\\x12(\\n\\x05label\\x18\\x03 \\x03(\\x0b\\x32\\x19.perftools.profiles.Label\\\".\\n\\x05Label\\x12\\x0b\\n\\x03key\\x18\\x01 \\x01(\\x03\\x12\\x0b\\n\\x03str\\x18\\x02 \\x01(\\x03\\x12\\x0b\\n\\x03num\\x18\\x03 \\x01(\\x03\\\"\\xdd\\x01\\n\\x07Mapping\\x12\\n\\n\\x02id\\x18\\x01 \\x01(\\x04\\x12\\x14\\n\\x0cmemory_start\\x18\\x02 \\x01(\\x04\\x12\\x14\\n\\x0cmemory_limit\\x18\\x03 \\x01(\\x04\\x12\\x13\\n\\x0b\\x66ile_offset\\x18\\x04 \\x01(\\x04\\x12\\x10\\n\\x08\\x66ilename\\x18\\x05 \\x01(\\x03\\x12\\x10\\n\\x08\\x62uild_id\\x18\\x06 \\x01(\\x03\\x12\\x15\\n\\rhas_functions\\x18\\x07 \\x01(\\x08\\x12\\x15\\n\\rhas_filenames\\x18\\x08 \\x01(\\x08\\x12\\x18\\n\\x10has_line_numbers\\x18\\t \\x01(\\x08\\x12\\x19\\n\\x11has_inline_frames\\x18\\n \\x01(\\x08\\\"c\\n\\x08Location\\x12\\n\\n\\x02id\\x18\\x01 \\x01(\\x04\\x12\\x12\\n\\nmapping_id\\x18\\x02 \\x01(\\x04\\x12\\x0f\\n\\x07\\x61\\x64\\x64ress\\x18\\x03 \\x01(\\x04\\x12&\\n\\x04line\\x18\\x04 \\x03(\\x0b\\x32\\x18.perftools.profiles.Line\\\")\\n\\x04Line\\x12\\x13\\n\\x0b\\x66unction_id\\x18\\x01 \\x01(\\x04\\x12\\x0c\\n\\x04line\\x18\\x02 \\x01(\\x03\\\"_\\n\\x08\\x46unction\\x12\\n\\n\\x02id\\x18\\x01 \\x01(\\x04\\x12\\x0c\\n\\x04name\\x18\\x02 \\x01(\\x03\\x12\\x13\\n\\x0bsystem_name\\x18\\x03 \\x01(\\x03\\x12\\x10\\n\\x08\\x66ilename\\x18\\x04 \\x01(\\x03\\x12\\x12\\n\\nstart_line\\x18\\x05 \\x01(\\x03\\x42-\\n\\x1d\\x63om.google.perftools.profilesB\\x0cProfileProtob\\x06proto3')\n)\n_sym_db.RegisterFileDescriptor(DESCRIPTOR)\n\n\n\n\n_PROFILE = _descriptor.Descriptor(\n  name='Profile',\n  full_name='perftools.profiles.Profile',\n  filename=None,\n  file=DESCRIPTOR,\n  containing_type=None,\n  fields=[\n    _descriptor.FieldDescriptor(\n      name='sample_type', full_name='perftools.profiles.Profile.sample_type', index=0,\n      number=1, type=11, cpp_type=10, label=3,\n      has_default_value=False, default_value=[],\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='sample', full_name='perftools.profiles.Profile.sample', index=1,\n      number=2, type=11, cpp_type=10, label=3,\n      has_default_value=False, default_value=[],\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='mapping', full_name='perftools.profiles.Profile.mapping', index=2,\n      number=3, type=11, cpp_type=10, label=3,\n      has_default_value=False, default_value=[],\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='location', full_name='perftools.profiles.Profile.location', index=3,\n      number=4, type=11, cpp_type=10, label=3,\n      has_default_value=False, default_value=[],\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='function', full_name='perftools.profiles.Profile.function', index=4,\n      number=5, type=11, cpp_type=10, label=3,\n      has_default_value=False, default_value=[],\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='string_table', full_name='perftools.profiles.Profile.string_table', index=5,\n      number=6, type=9, cpp_type=9, label=3,\n      has_default_value=False, default_value=[],\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='drop_frames', full_name='perftools.profiles.Profile.drop_frames', index=6,\n      number=7, type=3, cpp_type=2, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='keep_frames', full_name='perftools.profiles.Profile.keep_frames', index=7,\n      number=8, type=3, cpp_type=2, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='time_nanos', full_name='perftools.profiles.Profile.time_nanos', index=8,\n      number=9, type=3, cpp_type=2, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='duration_nanos', full_name='perftools.profiles.Profile.duration_nanos', index=9,\n      number=10, type=3, cpp_type=2, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='period_type', full_name='perftools.profiles.Profile.period_type', index=10,\n      number=11, type=11, cpp_type=10, label=1,\n      has_default_value=False, default_value=None,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='period', full_name='perftools.profiles.Profile.period', index=11,\n      number=12, type=3, cpp_type=2, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='comment', full_name='perftools.profiles.Profile.comment', index=12,\n      number=13, type=3, cpp_type=2, label=3,\n      has_default_value=False, default_value=[],\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='default_sample_type', full_name='perftools.profiles.Profile.default_sample_type', index=13,\n      number=14, type=3, cpp_type=2, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n  ],\n  extensions=[\n  ],\n  nested_types=[],\n  enum_types=[\n  ],\n  options=None,\n  is_extendable=False,\n  syntax='proto3',\n  extension_ranges=[],\n  oneofs=[\n  ],\n  serialized_start=38,\n  serialized_end=507,\n)\n\n\n_VALUETYPE = _descriptor.Descriptor(\n  name='ValueType',\n  full_name='perftools.profiles.ValueType',\n  filename=None,\n  file=DESCRIPTOR,\n  containing_type=None,\n  fields=[\n    _descriptor.FieldDescriptor(\n      name='type', full_name='perftools.profiles.ValueType.type', index=0,\n      number=1, type=3, cpp_type=2, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='unit', full_name='perftools.profiles.ValueType.unit', index=1,\n      number=2, type=3, cpp_type=2, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n  ],\n  extensions=[\n  ],\n  nested_types=[],\n  enum_types=[\n  ],\n  options=None,\n  is_extendable=False,\n  syntax='proto3',\n  extension_ranges=[],\n  oneofs=[\n  ],\n  serialized_start=509,\n  serialized_end=548,\n)\n\n\n_SAMPLE = _descriptor.Descriptor(\n  name='Sample',\n  full_name='perftools.profiles.Sample',\n  filename=None,\n  file=DESCRIPTOR,\n  containing_type=None,\n  fields=[\n    _descriptor.FieldDescriptor(\n      name='location_id', full_name='perftools.profiles.Sample.location_id', index=0,\n      number=1, type=4, cpp_type=4, label=3,\n      has_default_value=False, default_value=[],\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='value', full_name='perftools.profiles.Sample.value', index=1,\n      number=2, type=3, cpp_type=2, label=3,\n      has_default_value=False, default_value=[],\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='label', full_name='perftools.profiles.Sample.label', index=2,\n      number=3, type=11, cpp_type=10, label=3,\n      has_default_value=False, default_value=[],\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n  ],\n  extensions=[\n  ],\n  nested_types=[],\n  enum_types=[\n  ],\n  options=None,\n  is_extendable=False,\n  syntax='proto3',\n  extension_ranges=[],\n  oneofs=[\n  ],\n  serialized_start=550,\n  serialized_end=636,\n)\n\n\n_LABEL = _descriptor.Descriptor(\n  name='Label',\n  full_name='perftools.profiles.Label',\n  filename=None,\n  file=DESCRIPTOR,\n  containing_type=None,\n  fields=[\n    _descriptor.FieldDescriptor(\n      name='key', full_name='perftools.profiles.Label.key', index=0,\n      number=1, type=3, cpp_type=2, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='str', full_name='perftools.profiles.Label.str', index=1,\n      number=2, type=3, cpp_type=2, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='num', full_name='perftools.profiles.Label.num', index=2,\n      number=3, type=3, cpp_type=2, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n  ],\n  extensions=[\n  ],\n  nested_types=[],\n  enum_types=[\n  ],\n  options=None,\n  is_extendable=False,\n  syntax='proto3',\n  extension_ranges=[],\n  oneofs=[\n  ],\n  serialized_start=638,\n  serialized_end=684,\n)\n\n\n_MAPPING = _descriptor.Descriptor(\n  name='Mapping',\n  full_name='perftools.profiles.Mapping',\n  filename=None,\n  file=DESCRIPTOR,\n  containing_type=None,\n  fields=[\n    _descriptor.FieldDescriptor(\n      name='id', full_name='perftools.profiles.Mapping.id', index=0,\n      number=1, type=4, cpp_type=4, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='memory_start', full_name='perftools.profiles.Mapping.memory_start', index=1,\n      number=2, type=4, cpp_type=4, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='memory_limit', full_name='perftools.profiles.Mapping.memory_limit', index=2,\n      number=3, type=4, cpp_type=4, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='file_offset', full_name='perftools.profiles.Mapping.file_offset', index=3,\n      number=4, type=4, cpp_type=4, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='filename', full_name='perftools.profiles.Mapping.filename', index=4,\n      number=5, type=3, cpp_type=2, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='build_id', full_name='perftools.profiles.Mapping.build_id', index=5,\n      number=6, type=3, cpp_type=2, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='has_functions', full_name='perftools.profiles.Mapping.has_functions', index=6,\n      number=7, type=8, cpp_type=7, label=1,\n      has_default_value=False, default_value=False,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='has_filenames', full_name='perftools.profiles.Mapping.has_filenames', index=7,\n      number=8, type=8, cpp_type=7, label=1,\n      has_default_value=False, default_value=False,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='has_line_numbers', full_name='perftools.profiles.Mapping.has_line_numbers', index=8,\n      number=9, type=8, cpp_type=7, label=1,\n      has_default_value=False, default_value=False,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='has_inline_frames', full_name='perftools.profiles.Mapping.has_inline_frames', index=9,\n      number=10, type=8, cpp_type=7, label=1,\n      has_default_value=False, default_value=False,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n  ],\n  extensions=[\n  ],\n  nested_types=[],\n  enum_types=[\n  ],\n  options=None,\n  is_extendable=False,\n  syntax='proto3',\n  extension_ranges=[],\n  oneofs=[\n  ],\n  serialized_start=687,\n  serialized_end=908,\n)\n\n\n_LOCATION = _descriptor.Descriptor(\n  name='Location',\n  full_name='perftools.profiles.Location',\n  filename=None,\n  file=DESCRIPTOR,\n  containing_type=None,\n  fields=[\n    _descriptor.FieldDescriptor(\n      name='id', full_name='perftools.profiles.Location.id', index=0,\n      number=1, type=4, cpp_type=4, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='mapping_id', full_name='perftools.profiles.Location.mapping_id', index=1,\n      number=2, type=4, cpp_type=4, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='address', full_name='perftools.profiles.Location.address', index=2,\n      number=3, type=4, cpp_type=4, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='line', full_name='perftools.profiles.Location.line', index=3,\n      number=4, type=11, cpp_type=10, label=3,\n      has_default_value=False, default_value=[],\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n  ],\n  extensions=[\n  ],\n  nested_types=[],\n  enum_types=[\n  ],\n  options=None,\n  is_extendable=False,\n  syntax='proto3',\n  extension_ranges=[],\n  oneofs=[\n  ],\n  serialized_start=910,\n  serialized_end=1009,\n)\n\n\n_LINE = _descriptor.Descriptor(\n  name='Line',\n  full_name='perftools.profiles.Line',\n  filename=None,\n  file=DESCRIPTOR,\n  containing_type=None,\n  fields=[\n    _descriptor.FieldDescriptor(\n      name='function_id', full_name='perftools.profiles.Line.function_id', index=0,\n      number=1, type=4, cpp_type=4, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='line', full_name='perftools.profiles.Line.line', index=1,\n      number=2, type=3, cpp_type=2, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n  ],\n  extensions=[\n  ],\n  nested_types=[],\n  enum_types=[\n  ],\n  options=None,\n  is_extendable=False,\n  syntax='proto3',\n  extension_ranges=[],\n  oneofs=[\n  ],\n  serialized_start=1011,\n  serialized_end=1052,\n)\n\n\n_FUNCTION = _descriptor.Descriptor(\n  name='Function',\n  full_name='perftools.profiles.Function',\n  filename=None,\n  file=DESCRIPTOR,\n  containing_type=None,\n  fields=[\n    _descriptor.FieldDescriptor(\n      name='id', full_name='perftools.profiles.Function.id', index=0,\n      number=1, type=4, cpp_type=4, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='name', full_name='perftools.profiles.Function.name', index=1,\n      number=2, type=3, cpp_type=2, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='system_name', full_name='perftools.profiles.Function.system_name', index=2,\n      number=3, type=3, cpp_type=2, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='filename', full_name='perftools.profiles.Function.filename', index=3,\n      number=4, type=3, cpp_type=2, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n    _descriptor.FieldDescriptor(\n      name='start_line', full_name='perftools.profiles.Function.start_line', index=4,\n      number=5, type=3, cpp_type=2, label=1,\n      has_default_value=False, default_value=0,\n      message_type=None, enum_type=None, containing_type=None,\n      is_extension=False, extension_scope=None,\n      options=None),\n  ],\n  extensions=[\n  ],\n  nested_types=[],\n  enum_types=[\n  ],\n  options=None,\n  is_extendable=False,\n  syntax='proto3',\n  extension_ranges=[],\n  oneofs=[\n  ],\n  serialized_start=1054,\n  serialized_end=1149,\n)\n\n_PROFILE.fields_by_name['sample_type'].message_type = _VALUETYPE\n_PROFILE.fields_by_name['sample'].message_type = _SAMPLE\n_PROFILE.fields_by_name['mapping'].message_type = _MAPPING\n_PROFILE.fields_by_name['location'].message_type = _LOCATION\n_PROFILE.fields_by_name['function'].message_type = _FUNCTION\n_PROFILE.fields_by_name['period_type'].message_type = _VALUETYPE\n_SAMPLE.fields_by_name['label'].message_type = _LABEL\n_LOCATION.fields_by_name['line'].message_type = _LINE\nDESCRIPTOR.message_types_by_name['Profile'] = _PROFILE\nDESCRIPTOR.message_types_by_name['ValueType'] = _VALUETYPE\nDESCRIPTOR.message_types_by_name['Sample'] = _SAMPLE\nDESCRIPTOR.message_types_by_name['Label'] = _LABEL\nDESCRIPTOR.message_types_by_name['Mapping'] = _MAPPING\nDESCRIPTOR.message_types_by_name['Location'] = _LOCATION\nDESCRIPTOR.message_types_by_name['Line'] = _LINE\nDESCRIPTOR.message_types_by_name['Function'] = _FUNCTION\n\nProfile = _reflection.GeneratedProtocolMessageType('Profile', (_message.Message,), dict(\n  DESCRIPTOR = _PROFILE,\n  __module__ = 'profile_pb2'\n  # @@protoc_insertion_point(class_scope:perftools.profiles.Profile)\n  ))\n_sym_db.RegisterMessage(Profile)\n\nValueType = _reflection.GeneratedProtocolMessageType('ValueType', (_message.Message,), dict(\n  DESCRIPTOR = _VALUETYPE,\n  __module__ = 'profile_pb2'\n  # @@protoc_insertion_point(class_scope:perftools.profiles.ValueType)\n  ))\n_sym_db.RegisterMessage(ValueType)\n\nSample = _reflection.GeneratedProtocolMessageType('Sample', (_message.Message,), dict(\n  DESCRIPTOR = _SAMPLE,\n  __module__ = 'profile_pb2'\n  # @@protoc_insertion_point(class_scope:perftools.profiles.Sample)\n  ))\n_sym_db.RegisterMessage(Sample)\n\nLabel = _reflection.GeneratedProtocolMessageType('Label', (_message.Message,), dict(\n  DESCRIPTOR = _LABEL,\n  __module__ = 'profile_pb2'\n  # @@protoc_insertion_point(class_scope:perftools.profiles.Label)\n  ))\n_sym_db.RegisterMessage(Label)\n\nMapping = _reflection.GeneratedProtocolMessageType('Mapping', (_message.Message,), dict(\n  DESCRIPTOR = _MAPPING,\n  __module__ = 'profile_pb2'\n  # @@protoc_insertion_point(class_scope:perftools.profiles.Mapping)\n  ))\n_sym_db.RegisterMessage(Mapping)\n\nLocation = _reflection.GeneratedProtocolMessageType('Location', (_message.Message,), dict(\n  DESCRIPTOR = _LOCATION,\n  __module__ = 'profile_pb2'\n  # @@protoc_insertion_point(class_scope:perftools.profiles.Location)\n  ))\n_sym_db.RegisterMessage(Location)\n\nLine = _reflection.GeneratedProtocolMessageType('Line', (_message.Message,), dict(\n  DESCRIPTOR = _LINE,\n  __module__ = 'profile_pb2'\n  # @@protoc_insertion_point(class_scope:perftools.profiles.Line)\n  ))\n_sym_db.RegisterMessage(Line)\n\nFunction = _reflection.GeneratedProtocolMessageType('Function', (_message.Message,), dict(\n  DESCRIPTOR = _FUNCTION,\n  __module__ = 'profile_pb2'\n  # @@protoc_insertion_point(class_scope:perftools.profiles.Function)\n  ))\n_sym_db.RegisterMessage(Function)\n\n\nDESCRIPTOR.has_options = True\nDESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\\n\\035com.google.perftools.profilesB\\014ProfileProto'))\n# @@protoc_insertion_point(module_scope)\n"
  },
  {
    "path": "simpleperf/report.py",
    "content": "#!/usr/bin/env python3\n#\n# Copyright (C) 2015 The Android Open Source Project\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\"\"\"Simpleperf gui reporter: provide gui interface for simpleperf report command.\n\nThere are two ways to use gui reporter. One way is to pass it a report file\ngenerated by simpleperf report command, and reporter will display it. The\nother ways is to pass it any arguments you want to use when calling\nsimpleperf report command. The reporter will call `simpleperf report` to\ngenerate report file, and display it.\n\"\"\"\n\nimport logging\nimport os\nimport os.path\nimport re\nimport subprocess\nimport sys\n\ntry:\n    from tkinter import *\n    from tkinter.font import Font\n    from tkinter.ttk import *\nexcept ImportError:\n    from Tkinter import *\n    from tkFont import Font\n    from ttk import *\n\nfrom simpleperf_utils import *\n\nPAD_X = 3\nPAD_Y = 3\n\n\nclass CallTreeNode(object):\n\n    \"\"\"Representing a node in call-graph.\"\"\"\n\n    def __init__(self, percentage, function_name):\n        self.percentage = percentage\n        self.call_stack = [function_name]\n        self.children = []\n\n    def add_call(self, function_name):\n        self.call_stack.append(function_name)\n\n    def add_child(self, node):\n        self.children.append(node)\n\n    def __str__(self):\n        strs = self.dump()\n        return '\\n'.join(strs)\n\n    def dump(self):\n        strs = []\n        strs.append('CallTreeNode percentage = %.2f' % self.percentage)\n        for function_name in self.call_stack:\n            strs.append(' %s' % function_name)\n        for child in self.children:\n            child_strs = child.dump()\n            strs.extend(['  ' + x for x in child_strs])\n        return strs\n\n\nclass ReportItem(object):\n\n    \"\"\"Representing one item in report, may contain a CallTree.\"\"\"\n\n    def __init__(self, raw_line):\n        self.raw_line = raw_line\n        self.call_tree = None\n\n    def __str__(self):\n        strs = []\n        strs.append('ReportItem (raw_line %s)' % self.raw_line)\n        if self.call_tree is not None:\n            strs.append('%s' % self.call_tree)\n        return '\\n'.join(strs)\n\n\nclass EventReport(object):\n\n    \"\"\"Representing report for one event attr.\"\"\"\n\n    def __init__(self, common_report_context):\n        self.context = common_report_context[:]\n        self.title_line = None\n        self.report_items = []\n\n\ndef parse_event_reports(lines):\n    # Parse common report context\n    common_report_context = []\n    line_id = 0\n    while line_id < len(lines):\n        line = lines[line_id]\n        if not line or line.find('Event:') == 0:\n            break\n        common_report_context.append(line)\n        line_id += 1\n\n    event_reports = []\n    in_report_context = True\n    cur_event_report = EventReport(common_report_context)\n    cur_report_item = None\n    call_tree_stack = {}\n    vertical_columns = []\n    last_node = None\n\n    has_skipped_callgraph = False\n\n    for line in lines[line_id:]:\n        if not line:\n            in_report_context = not in_report_context\n            if in_report_context:\n                cur_event_report = EventReport(common_report_context)\n            continue\n\n        if in_report_context:\n            cur_event_report.context.append(line)\n            if line.find('Event:') == 0:\n                event_reports.append(cur_event_report)\n            continue\n\n        if cur_event_report.title_line is None:\n            cur_event_report.title_line = line\n        elif not line[0].isspace():\n            cur_report_item = ReportItem(line)\n            cur_event_report.report_items.append(cur_report_item)\n            # Each report item can have different column depths.\n            vertical_columns = []\n        else:\n            for i in range(len(line)):\n                if line[i] == '|':\n                    if not vertical_columns or vertical_columns[-1] < i:\n                        vertical_columns.append(i)\n\n            if not line.strip('| \\t'):\n                continue\n            if 'skipped in brief callgraph mode' in line:\n                has_skipped_callgraph = True\n                continue\n\n            if line.find('-') == -1:\n                line = line.strip('| \\t')\n                function_name = line\n                last_node.add_call(function_name)\n            else:\n                pos = line.find('-')\n                depth = -1\n                for i in range(len(vertical_columns)):\n                    if pos >= vertical_columns[i]:\n                        depth = i\n                assert depth != -1\n\n                line = line.strip('|- \\t')\n                m = re.search(r'^([\\d\\.]+)%[-\\s]+(.+)$', line)\n                if m:\n                    percentage = float(m.group(1))\n                    function_name = m.group(2)\n                else:\n                    percentage = 100.0\n                    function_name = line\n\n                node = CallTreeNode(percentage, function_name)\n                if depth == 0:\n                    cur_report_item.call_tree = node\n                else:\n                    call_tree_stack[depth - 1].add_child(node)\n                call_tree_stack[depth] = node\n                last_node = node\n\n    if has_skipped_callgraph:\n        logging.warning('some callgraphs are skipped in brief callgraph mode')\n\n    return event_reports\n\n\nclass ReportWindow(object):\n\n    \"\"\"A window used to display report file.\"\"\"\n\n    def __init__(self, main, report_context, title_line, report_items):\n        frame = Frame(main)\n        frame.pack(fill=BOTH, expand=1)\n\n        font = Font(family='courier', size=12)\n\n        # Report Context\n        for line in report_context:\n            label = Label(frame, text=line, font=font)\n            label.pack(anchor=W, padx=PAD_X, pady=PAD_Y)\n\n        # Space\n        label = Label(frame, text='', font=font)\n        label.pack(anchor=W, padx=PAD_X, pady=PAD_Y)\n\n        # Title\n        label = Label(frame, text='  ' + title_line, font=font)\n        label.pack(anchor=W, padx=PAD_X, pady=PAD_Y)\n\n        # Report Items\n        report_frame = Frame(frame)\n        report_frame.pack(fill=BOTH, expand=1)\n\n        yscrollbar = Scrollbar(report_frame)\n        yscrollbar.pack(side=RIGHT, fill=Y)\n        xscrollbar = Scrollbar(report_frame, orient=HORIZONTAL)\n        xscrollbar.pack(side=BOTTOM, fill=X)\n\n        tree = Treeview(report_frame, columns=[title_line], show='')\n        tree.pack(side=LEFT, fill=BOTH, expand=1)\n        tree.tag_configure('set_font', font=font)\n\n        tree.config(yscrollcommand=yscrollbar.set)\n        yscrollbar.config(command=tree.yview)\n        tree.config(xscrollcommand=xscrollbar.set)\n        xscrollbar.config(command=tree.xview)\n\n        self.display_report_items(tree, report_items)\n\n    def display_report_items(self, tree, report_items):\n        for report_item in report_items:\n            prefix_str = '+ ' if report_item.call_tree is not None else '  '\n            id = tree.insert(\n                '',\n                'end',\n                None,\n                values=[\n                    prefix_str +\n                    report_item.raw_line],\n                tag='set_font')\n            if report_item.call_tree is not None:\n                self.display_call_tree(tree, id, report_item.call_tree, 1)\n\n    def display_call_tree(self, tree, parent_id, node, indent):\n        id = parent_id\n        indent_str = '    ' * indent\n\n        if node.percentage != 100.0:\n            percentage_str = '%.2f%% ' % node.percentage\n        else:\n            percentage_str = ''\n\n        for i in range(len(node.call_stack)):\n            s = indent_str\n            s += '+ ' if node.children and i == len(node.call_stack) - 1 else '  '\n            s += percentage_str if i == 0 else ' ' * len(percentage_str)\n            s += node.call_stack[i]\n            child_open = False if i == len(node.call_stack) - 1 and indent > 1 else True\n            id = tree.insert(id, 'end', None, values=[s], open=child_open,\n                             tag='set_font')\n\n        for child in node.children:\n            self.display_call_tree(tree, id, child, indent + 1)\n\n\ndef display_report_file(report_file, self_kill_after_sec):\n    fh = open(report_file, 'r')\n    lines = fh.readlines()\n    fh.close()\n\n    lines = [x.rstrip() for x in lines]\n    event_reports = parse_event_reports(lines)\n\n    if event_reports:\n        root = Tk()\n        for i in range(len(event_reports)):\n            report = event_reports[i]\n            parent = root if i == 0 else Toplevel(root)\n            ReportWindow(parent, report.context, report.title_line, report.report_items)\n        if self_kill_after_sec:\n            root.after(self_kill_after_sec * 1000, lambda: root.destroy())\n        root.mainloop()\n\n\ndef call_simpleperf_report(args, show_gui, self_kill_after_sec):\n    simpleperf_path = get_host_binary_path('simpleperf')\n    if not show_gui:\n        subprocess.check_call([simpleperf_path, 'report'] + args)\n    else:\n        report_file = 'perf.report'\n        subprocess.check_call([simpleperf_path, 'report', '--full-callgraph'] + args +\n                              ['-o', report_file])\n        display_report_file(report_file, self_kill_after_sec=self_kill_after_sec)\n\n\ndef get_simpleperf_report_help_msg():\n    simpleperf_path = get_host_binary_path('simpleperf')\n    args = [simpleperf_path, 'report', '-h']\n    proc = subprocess.Popen(args, stdout=subprocess.PIPE)\n    (stdoutdata, _) = proc.communicate()\n    stdoutdata = bytes_to_str(stdoutdata)\n    return stdoutdata[stdoutdata.find('\\n') + 1:]\n\n\ndef main():\n    self_kill_after_sec = 0\n    args = sys.argv[1:]\n    if args and args[0] == \"--self-kill-for-testing\":\n        self_kill_after_sec = 1\n        args = args[1:]\n    if len(args) == 1 and os.path.isfile(args[0]):\n        display_report_file(args[0], self_kill_after_sec=self_kill_after_sec)\n\n    i = 0\n    args_for_report_cmd = []\n    show_gui = False\n    while i < len(args):\n        if args[i] == '-h' or args[i] == '--help':\n            print('report.py   A python wrapper for simpleperf report command.')\n            print('Options supported by simpleperf report command:')\n            print(get_simpleperf_report_help_msg())\n            print('\\nOptions supported by report.py:')\n            print('--gui   Show report result in a gui window.')\n            print('\\nIt also supports showing a report generated by simpleperf report cmd:')\n            print('\\n  python report.py report_file')\n            sys.exit(0)\n        elif args[i] == '--gui':\n            show_gui = True\n            i += 1\n        else:\n            args_for_report_cmd.append(args[i])\n            i += 1\n\n    call_simpleperf_report(args_for_report_cmd, show_gui, self_kill_after_sec)\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "simpleperf/report_firefox.bat",
    "content": "python gecko_profile_generator.py | gzip > firefox_profile.json.gz\r\nstart \"\" https://profiler.firefox.com/"
  },
  {
    "path": "simpleperf/report_gui.bat",
    "content": "python report.py --gui"
  },
  {
    "path": "simpleperf/report_html.bat",
    "content": "python report_html.py --ndk_path %~dp0\\ndk --add_source_code --source_dirs ^\r\nz:\\UE4\\GameProjects\\AtelierClient\\Source\\Atelier\\AIModule\\ ^\r\nz:\\UE4\\GameProjects\\AtelierClient\\Source\\Atelier\\Anim\\ ^\r\nz:\\UE4\\GameProjects\\AtelierClient\\Source\\Atelier\\Battle\\ ^\r\nz:\\UE4\\GameProjects\\AtelierClient\\Source\\Atelier\\Camera\\ ^\r\nz:\\UE4\\GameProjects\\AtelierClient\\Source\\Atelier\\Character\\ ^\r\nz:\\UE4\\GameProjects\\AtelierClient\\Source\\Atelier\\ChatSystem\\ ^\r\nz:\\UE4\\GameProjects\\AtelierClient\\Source\\Atelier\\Common\\ ^\r\nz:\\UE4\\GameProjects\\AtelierClient\\Source\\Atelier\\CommonCode\\ ^\r\nz:\\UE4\\GameProjects\\AtelierClient\\Source\\Atelier\\CoreBase\\ ^\r\nz:\\UE4\\GameProjects\\AtelierClient\\Source\\Atelier\\GameInstanceSubsystem\\ ^\r\nz:\\UE4\\GameProjects\\AtelierClient\\Source\\Atelier\\GameplayDebugger\\ ^\r\nz:\\UE4\\GameProjects\\AtelierClient\\Source\\Atelier\\Kismet\\ ^\r\nz:\\UE4\\GameProjects\\AtelierClient\\Source\\Atelier\\LevelSequence\\ ^\r\nz:\\UE4\\GameProjects\\AtelierClient\\Source\\Atelier\\Lua\\ ^\r\nz:\\UE4\\GameProjects\\AtelierClient\\Source\\Atelier\\LuaWrapper\\ ^\r\nz:\\UE4\\GameProjects\\AtelierClient\\Source\\Atelier\\Model\\ ^\r\nz:\\UE4\\GameProjects\\AtelierClient\\Source\\Atelier\\Platform\\ ^\r\nz:\\UE4\\GameProjects\\AtelierClient\\Source\\Atelier\\Stage\\ ^\r\nz:\\UE4\\GameProjects\\AtelierClient\\Source\\Atelier\\System\\ ^\r\nz:\\UE4\\GameProjects\\AtelierClient\\Source\\Atelier\\UI\\ ^\r\nz:\\UE4\\GameProjects\\AtelierClient\\Source\\Atelier\\Utilities\\ ^\r\nz:\\UE4\\Engine\\Source\\Runtime\\Engine\\Public\\ ^\r\nz:\\UE4\\Engine\\Source\\Runtime\\Engine\\Private\\ ^\r\nz:\\UE4\\Engine\\Source\\Runtime\\Engine\\Classes\\GameFramework\\ ^\r\nz:\\UE4\\Engine\\Source\\Runtime\\AnimGraphRuntime\\Private\\ ^\r\nz:\\UE4\\Engine\\Source\\Runtime\\AnimGraphRuntime\\Public\\"
  },
  {
    "path": "simpleperf/report_html.js",
    "content": "/*\n * Copyright (C) 2017 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use strict';\n\n// Use IIFE to avoid leaking names to other scripts.\n(function () {\n\nfunction getTimeInMs() {\n    return new Date().getTime();\n}\n\nclass TimeLog {\n    constructor() {\n        this.start = getTimeInMs();\n    }\n\n    log(name) {\n        let end = getTimeInMs();\n        console.log(name, end - this.start, 'ms');\n        this.start = end;\n    }\n}\n\nclass ProgressBar {\n    constructor() {\n        let str = `\n            <div class=\"modal\" tabindex=\"-1\" role=\"dialog\">\n                <div class=\"modal-dialog\" role=\"document\">\n                    <div class=\"modal-content\">\n                        <div class=\"modal-header\"><h5 class=\"modal-title\">Loading page...</h5></div>\n                        <div class=\"modal-body\">\n                            <div class=\"progress\">\n                                <div class=\"progress-bar\" role=\"progressbar\"\n                                    style=\"width: 0%\" aria-valuenow=\"0\" aria-valuemin=\"0\"\n                                    aria-valuemax=\"100\">0%</div>\n                            </div>\n                        </div>\n                    </div>\n                </div>\n            </div>\n        `;\n        this.modal = $(str).appendTo($('body'));\n        this.progress = 0;\n        this.shownCallback = null;\n        this.modal.on('shown.bs.modal', () => this._onShown());\n        // Shorten progress bar update time.\n        this.modal.find('.progress-bar').css('transition-duration', '0ms');\n        this.shown = false;\n    }\n\n    // progress is [0-100]. Return a Promise resolved when the update is shown.\n    updateAsync(text, progress) {\n        progress = parseInt(progress);  // Truncate float number to integer.\n        return this.showAsync().then(() => {\n            if (text) {\n                this.modal.find('.modal-title').text(text);\n            }\n            this.progress = progress;\n            this.modal.find('.progress-bar').css('width', progress + '%')\n                    .attr('aria-valuenow', progress).text(progress + '%');\n            // Leave 100ms for the progess bar to update.\n            return createPromise((resolve) => setTimeout(resolve, 100));\n        });\n    }\n\n    showAsync() {\n        if (this.shown) {\n            return createPromise();\n        }\n        return createPromise((resolve) => {\n            this.shownCallback = resolve;\n            this.modal.modal({\n                show: true,\n                keyboard: false,\n                backdrop: false,\n            });\n        });\n    }\n\n    _onShown() {\n        this.shown = true;\n        if (this.shownCallback) {\n            let callback = this.shownCallback;\n            this.shownCallback = null;\n            callback();\n        }\n    }\n\n    hide() {\n        this.shown = false;\n        this.modal.modal('hide');\n    }\n}\n\nfunction openHtml(name, attrs={}) {\n    let s = `<${name} `;\n    for (let key in attrs) {\n        s += `${key}=\"${attrs[key]}\" `;\n    }\n    s += '>';\n    return s;\n}\n\nfunction closeHtml(name) {\n    return `</${name}>`;\n}\n\nfunction getHtml(name, attrs={}) {\n    let text;\n    if ('text' in attrs) {\n        text = attrs.text;\n        delete attrs.text;\n    }\n    let s = openHtml(name, attrs);\n    if (text) {\n        s += text;\n    }\n    s += closeHtml(name);\n    return s;\n}\n\nfunction getTableRow(cols, colName, attrs={}) {\n    let s = openHtml('tr', attrs);\n    for (let col of cols) {\n        s += `<${colName}>${col}</${colName}>`;\n    }\n    s += '</tr>';\n    return s;\n}\n\nfunction getProcessName(pid) {\n    let name = gProcesses[pid];\n    return name ? `${pid} (${name})`: pid.toString();\n}\n\nfunction getThreadName(tid) {\n    let name = gThreads[tid];\n    return name ? `${tid} (${name})`: tid.toString();\n}\n\nfunction getLibName(libId) {\n    return gLibList[libId];\n}\n\nfunction getFuncName(funcId) {\n    return gFunctionMap[funcId].f;\n}\n\nfunction getLibNameOfFunction(funcId) {\n    return getLibName(gFunctionMap[funcId].l);\n}\n\nfunction getFuncSourceRange(funcId) {\n    let func = gFunctionMap[funcId];\n    if (func.hasOwnProperty('s')) {\n        return {fileId: func.s[0], startLine: func.s[1], endLine: func.s[2]};\n    }\n    return null;\n}\n\nfunction getFuncDisassembly(funcId) {\n    let func = gFunctionMap[funcId];\n    return func.hasOwnProperty('d') ? func.d : null;\n}\n\nfunction getSourceFilePath(sourceFileId) {\n    return gSourceFiles[sourceFileId].path;\n}\n\nfunction getSourceCode(sourceFileId) {\n    return gSourceFiles[sourceFileId].code;\n}\n\nfunction isClockEvent(eventInfo) {\n    return eventInfo.eventName.includes('task-clock') ||\n            eventInfo.eventName.includes('cpu-clock');\n}\n\nlet createId = function() {\n    let currentId = 0;\n    return () => `id${++currentId}`;\n}();\n\nclass TabManager {\n    constructor(divContainer) {\n        let id = createId();\n        divContainer.append(`<ul class=\"nav nav-pills mb-3 mt-3 ml-3\" id=\"${id}\" role=\"tablist\">\n            </ul><hr/><div class=\"tab-content\" id=\"${id}Content\"></div>`);\n        this.ul = divContainer.find(`#${id}`);\n        this.content = divContainer.find(`#${id}Content`);\n        // Map from title to [tabObj, drawn=false|true].\n        this.tabs = new Map();\n        this.tabActiveCallback = null;\n    }\n\n    addTab(title, tabObj) {\n        let id = createId();\n        this.content.append(`<div class=\"tab-pane\" id=\"${id}\" role=\"tabpanel\"\n            aria-labelledby=\"${id}-tab\"></div>`);\n        this.ul.append(`\n            <li class=\"nav-item\">\n                <a class=\"nav-link\" id=\"${id}-tab\" data-toggle=\"pill\" href=\"#${id}\" role=\"tab\"\n                    aria-controls=\"${id}\" aria-selected=\"false\">${title}</a>\n            </li>`);\n        tabObj.init(this.content.find(`#${id}`));\n        this.tabs.set(title, [tabObj, false]);\n        this.ul.find(`#${id}-tab`).on('shown.bs.tab', () => this.onTabActive(title));\n        return tabObj;\n    }\n\n    setActiveAsync(title) {\n        let tabObj = this.findTab(title);\n        return createPromise((resolve) => {\n            this.tabActiveCallback = resolve;\n            let id = tabObj.div.attr('id') + '-tab';\n            this.ul.find(`#${id}`).tab('show');\n        });\n    }\n\n    onTabActive(title) {\n        let array = this.tabs.get(title);\n        let tabObj = array[0];\n        let drawn = array[1];\n        if (!drawn) {\n            tabObj.draw();\n            array[1] = true;\n        }\n        if (this.tabActiveCallback) {\n            let callback = this.tabActiveCallback;\n            this.tabActiveCallback = null;\n            callback();\n        }\n    }\n\n    findTab(title) {\n        let array = this.tabs.get(title);\n        return array ? array[0] : null;\n    }\n}\n\nfunction createEventTabs(id) {\n    let ul = `<ul class=\"nav nav-pills mb-3 mt-3 ml-3\" id=\"${id}\" role=\"tablist\">`;\n    let content = `<div class=\"tab-content\" id=\"${id}Content\">`;\n    for (let i = 0; i < gSampleInfo.length; ++i) {\n        let subId = id + '_' + i;\n        let title = gSampleInfo[i].eventName;\n        ul += `\n            <li class=\"nav-item\">\n                <a class=\"nav-link\" id=\"${subId}-tab\" data-toggle=\"pill\" href=\"#${subId}\" role=\"tab\"\n                aria-controls=\"${subId}\" aria-selected=\"${i == 0 ? \"true\" : \"false\"}\">${title}</a>\n            </li>`;\n        content += `\n            <div class=\"tab-pane\" id=\"${subId}\" role=\"tabpanel\" aria-labelledby=\"${subId}-tab\">\n            </div>`;\n    }\n    ul += '</ul>';\n    content += '</div>';\n    return ul + content;\n}\n\nfunction createViewsForEvents(div, createViewCallback) {\n    let views = [];\n    if (gSampleInfo.length == 1) {\n        views.push(createViewCallback(div, gSampleInfo[0]));\n    } else if (gSampleInfo.length > 1) {\n        // If more than one event, draw them in tabs.\n        let id = createId();\n        div.append(createEventTabs(id));\n        for (let i = 0; i < gSampleInfo.length; ++i) {\n            let subId = id + '_' + i;\n            views.push(createViewCallback(div.find(`#${subId}`), gSampleInfo[i]));\n        }\n        div.find(`#${id}_0-tab`).tab('show');\n    }\n    return views;\n}\n\n// Return a promise to draw views.\nfunction drawViewsAsync(views, totalProgress, drawViewCallback) {\n    if (views.length == 0) {\n        return createPromise();\n    }\n    let drawPos = 0;\n    let eachProgress = totalProgress / views.length;\n    function drawAsync() {\n        if (drawPos == views.length) {\n            return createPromise();\n        }\n        return drawViewCallback(views[drawPos++], eachProgress).then(drawAsync);\n    }\n    return drawAsync();\n}\n\n// Show global information retrieved from the record file, including:\n//   record time\n//   machine type\n//   Android version\n//   record cmdline\n//   total samples\nclass RecordFileView {\n    constructor(divContainer) {\n        this.div = $('<div>');\n        this.div.appendTo(divContainer);\n    }\n\n    draw() {\n        google.charts.setOnLoadCallback(() => this.realDraw());\n    }\n\n    realDraw() {\n        this.div.empty();\n        // Draw a table of 'Name', 'Value'.\n        let rows = [];\n        if (gRecordInfo.recordTime) {\n            rows.push(['Record Time', gRecordInfo.recordTime]);\n        }\n        if (gRecordInfo.machineType) {\n            rows.push(['Machine Type', gRecordInfo.machineType]);\n        }\n        if (gRecordInfo.androidVersion) {\n            rows.push(['Android Version', gRecordInfo.androidVersion]);\n        }\n        if (gRecordInfo.androidBuildFingerprint) {\n            rows.push(['Build Fingerprint', gRecordInfo.androidBuildFingerprint]);\n        }\n        if (gRecordInfo.kernelVersion) {\n            rows.push(['Kernel Version', gRecordInfo.kernelVersion]);\n        }\n        if (gRecordInfo.recordCmdline) {\n            rows.push(['Record cmdline', gRecordInfo.recordCmdline]);\n        }\n        rows.push(['Total Samples', '' + gRecordInfo.totalSamples]);\n\n        let data = new google.visualization.DataTable();\n        data.addColumn('string', '');\n        data.addColumn('string', '');\n        data.addRows(rows);\n        for (let i = 0; i < rows.length; ++i) {\n            data.setProperty(i, 0, 'className', 'boldTableCell');\n        }\n        let table = new google.visualization.Table(this.div.get(0));\n        table.draw(data, {\n            width: '100%',\n            sort: 'disable',\n            allowHtml: true,\n            cssClassNames: {\n                'tableCell': 'tableCell',\n            },\n        });\n    }\n}\n\n// Show pieChart of event count percentage of each process, thread, library and function.\nclass ChartView {\n    constructor(divContainer, eventInfo) {\n        this.div = $('<div>').appendTo(divContainer);\n        this.eventInfo = eventInfo;\n        this.processInfo = null;\n        this.threadInfo = null;\n        this.libInfo = null;\n        this.states = {\n            SHOW_EVENT_INFO: 1,\n            SHOW_PROCESS_INFO: 2,\n            SHOW_THREAD_INFO: 3,\n            SHOW_LIB_INFO: 4,\n        };\n        if (isClockEvent(this.eventInfo)) {\n            this.getSampleWeight = function (eventCount) {\n                return (eventCount / 1000000.0).toFixed(3) + ' ms';\n            };\n        } else {\n            this.getSampleWeight = (eventCount) => '' + eventCount;\n        }\n    }\n\n    _getState() {\n        if (this.libInfo) {\n            return this.states.SHOW_LIB_INFO;\n        }\n        if (this.threadInfo) {\n            return this.states.SHOW_THREAD_INFO;\n        }\n        if (this.processInfo) {\n            return this.states.SHOW_PROCESS_INFO;\n        }\n        return this.states.SHOW_EVENT_INFO;\n    }\n\n    _goBack() {\n        let state = this._getState();\n        if (state == this.states.SHOW_PROCESS_INFO) {\n            this.processInfo = null;\n        } else if (state == this.states.SHOW_THREAD_INFO) {\n            this.threadInfo = null;\n        } else if (state == this.states.SHOW_LIB_INFO) {\n            this.libInfo = null;\n        }\n        this.draw();\n    }\n\n    _selectHandler(chart) {\n        let selectedItem = chart.getSelection()[0];\n        if (selectedItem) {\n            let state = this._getState();\n            if (state == this.states.SHOW_EVENT_INFO) {\n                this.processInfo = this.eventInfo.processes[selectedItem.row];\n            } else if (state == this.states.SHOW_PROCESS_INFO) {\n                this.threadInfo = this.processInfo.threads[selectedItem.row];\n            } else if (state == this.states.SHOW_THREAD_INFO) {\n                this.libInfo = this.threadInfo.libs[selectedItem.row];\n            }\n            this.draw();\n        }\n    }\n\n    draw() {\n        google.charts.setOnLoadCallback(() => this.realDraw());\n    }\n\n    realDraw() {\n        this.div.empty();\n        this._drawTitle();\n        this._drawPieChart();\n    }\n\n    _drawTitle() {\n        // Draw a table of 'Name', 'Event Count'.\n        let rows = [];\n        rows.push(['Event Type: ' + this.eventInfo.eventName,\n                   this.getSampleWeight(this.eventInfo.eventCount)]);\n        if (this.processInfo) {\n            rows.push(['Process: ' + getProcessName(this.processInfo.pid),\n                       this.getSampleWeight(this.processInfo.eventCount)]);\n        }\n        if (this.threadInfo) {\n            rows.push(['Thread: ' + getThreadName(this.threadInfo.tid),\n                       this.getSampleWeight(this.threadInfo.eventCount)]);\n        }\n        if (this.libInfo) {\n            rows.push(['Library: ' + getLibName(this.libInfo.libId),\n                       this.getSampleWeight(this.libInfo.eventCount)]);\n        }\n        let data = new google.visualization.DataTable();\n        data.addColumn('string', '');\n        data.addColumn('string', '');\n        data.addRows(rows);\n        for (let i = 0; i < rows.length; ++i) {\n            data.setProperty(i, 0, 'className', 'boldTableCell');\n        }\n        let wrapperDiv = $('<div>');\n        wrapperDiv.appendTo(this.div);\n        let table = new google.visualization.Table(wrapperDiv.get(0));\n        table.draw(data, {\n            width: '100%',\n            sort: 'disable',\n            allowHtml: true,\n            cssClassNames: {\n                'tableCell': 'tableCell',\n            },\n        });\n        if (this._getState() != this.states.SHOW_EVENT_INFO) {\n            $('<button type=\"button\" class=\"btn btn-primary\">Back</button>').appendTo(this.div)\n                .click(() => this._goBack());\n        }\n    }\n\n    _drawPieChart() {\n        let state = this._getState();\n        let title = null;\n        let firstColumn = null;\n        let rows = [];\n        let thisObj = this;\n        function getItem(name, eventCount, totalEventCount) {\n            let sampleWeight = thisObj.getSampleWeight(eventCount);\n            let percent = (eventCount * 100.0 / totalEventCount).toFixed(2) + '%';\n            return [name, eventCount, getHtml('pre', {text: name}) +\n                        getHtml('b', {text: `${sampleWeight} (${percent})`})];\n        }\n\n        if (state == this.states.SHOW_EVENT_INFO) {\n            title = 'Processes in event type ' + this.eventInfo.eventName;\n            firstColumn = 'Process';\n            for (let process of this.eventInfo.processes) {\n                rows.push(getItem('Process: ' + getProcessName(process.pid), process.eventCount,\n                                  this.eventInfo.eventCount));\n            }\n        } else if (state == this.states.SHOW_PROCESS_INFO) {\n            title = 'Threads in process ' + getProcessName(this.processInfo.pid);\n            firstColumn = 'Thread';\n            for (let thread of this.processInfo.threads) {\n                rows.push(getItem('Thread: ' + getThreadName(thread.tid), thread.eventCount,\n                                  this.processInfo.eventCount));\n            }\n        } else if (state == this.states.SHOW_THREAD_INFO) {\n            title = 'Libraries in thread ' + getThreadName(this.threadInfo.tid);\n            firstColumn = 'Library';\n            for (let lib of this.threadInfo.libs) {\n                rows.push(getItem('Library: ' + getLibName(lib.libId), lib.eventCount,\n                                  this.threadInfo.eventCount));\n            }\n        } else if (state == this.states.SHOW_LIB_INFO) {\n            title = 'Functions in library ' + getLibName(this.libInfo.libId);\n            firstColumn = 'Function';\n            for (let func of this.libInfo.functions) {\n                rows.push(getItem('Function: ' + getFuncName(func.f), func.c[1],\n                                  this.libInfo.eventCount));\n            }\n        }\n        let data = new google.visualization.DataTable();\n        data.addColumn('string', firstColumn);\n        data.addColumn('number', 'EventCount');\n        data.addColumn({type: 'string', role: 'tooltip', p: {html: true}});\n        data.addRows(rows);\n\n        let wrapperDiv = $('<div>');\n        wrapperDiv.appendTo(this.div);\n        let chart = new google.visualization.PieChart(wrapperDiv.get(0));\n        chart.draw(data, {\n            title: title,\n            width: 1000,\n            height: 600,\n            tooltip: {isHtml: true},\n        });\n        google.visualization.events.addListener(chart, 'select', () => this._selectHandler(chart));\n    }\n}\n\n\nclass ChartStatTab {\n    init(div) {\n        this.div = div;\n    }\n\n    draw() {\n        new RecordFileView(this.div).draw();\n        let views = createViewsForEvents(this.div, (div, eventInfo) => {\n            return new ChartView(div, eventInfo);\n        });\n        for (let view of views) {\n            view.draw();\n        }\n    }\n}\n\n\nclass SampleTableTab {\n    init(div) {\n        this.div = div;\n    }\n\n    draw() {\n        let views = [];\n        createPromise()\n            .then(updateProgress('Draw SampleTable...', 0))\n            .then(wait(() => {\n                this.div.empty();\n                views = createViewsForEvents(this.div, (div, eventInfo) => {\n                    return new SampleTableView(div, eventInfo);\n                });\n            }))\n            .then(() => drawViewsAsync(views, 100, (view, progress) => view.drawAsync(progress)))\n            .then(hideProgress());\n    }\n}\n\n// Select the way to show sample weight in SampleTableTab.\n// 1. Show percentage of event count.\n// 2. Show event count (For cpu-clock and task-clock events, it is time in ms).\nclass SampleTableWeightSelectorView {\n    constructor(divContainer, eventInfo, onSelectChange) {\n        let options = new Map();\n        options.set('percent', 'Show percentage of event count');\n        options.set('event_count', 'Show event count');\n        if (isClockEvent(eventInfo)) {\n            options.set('event_count_in_ms', 'Show event count in milliseconds');\n        }\n        let buttons = [];\n        options.forEach((value, key) => {\n            buttons.push(`<button type=\"button\" class=\"dropdown-item\" key=\"${key}\">${value}\n                          </button>`);\n        });\n        this.curOption = 'percent';\n        this.eventCount = eventInfo.eventCount;\n        let id = createId();\n        let str = `\n            <div class=\"dropdown\">\n                <button type=\"button\" class=\"btn btn-primary dropdown-toggle\" id=\"${id}\"\n                    data-toggle=\"dropdown\" aria-haspopup=\"true\" aria-expanded=\"false\"\n                    >${options.get(this.curOption)}</button>\n                <div class=\"dropdown-menu\" aria-labelledby=\"${id}\">${buttons.join('')}</div>\n            </div>\n        `;\n        divContainer.append(str);\n        divContainer.children().last().on('hidden.bs.dropdown', (e) => {\n            if (e.clickEvent) {\n                let button = $(e.clickEvent.target);\n                let newOption = button.attr('key');\n                if (newOption && this.curOption != newOption) {\n                    this.curOption = newOption;\n                    divContainer.find(`#${id}`).text(options.get(this.curOption));\n                    onSelectChange();\n                }\n            }\n        });\n    }\n\n    getSampleWeightFunction() {\n        if (this.curOption == 'percent') {\n            return (eventCount) => (eventCount * 100.0 / this.eventCount).toFixed(2) + '%';\n        }\n        if (this.curOption == 'event_count') {\n            return (eventCount) => '' + eventCount;\n        }\n        if (this.curOption == 'event_count_in_ms') {\n            return (eventCount) => (eventCount / 1000000.0).toFixed(3);\n        }\n    }\n\n    getSampleWeightSuffix() {\n        if (this.curOption == 'event_count_in_ms') {\n            return ' ms';\n        }\n        return '';\n    }\n}\n\n\nclass SampleTableView {\n    constructor(divContainer, eventInfo) {\n        this.id = createId();\n        this.div = $('<div>', {id: this.id}).appendTo(divContainer);\n        this.eventInfo = eventInfo;\n        this.selectorView = null;\n        this.tableDiv = null;\n    }\n\n    drawAsync(totalProgress) {\n        return createPromise()\n            .then(wait(() => {\n                this.div.empty();\n                this.selectorView = new SampleTableWeightSelectorView(\n                    this.div, this.eventInfo, () => this.onSampleWeightChange());\n                this.tableDiv = $('<div>').appendTo(this.div);\n            }))\n            .then(() => this._drawSampleTable(totalProgress));\n    }\n\n    // Return a promise to draw SampleTable.\n    _drawSampleTable(totalProgress) {\n        let eventInfo = this.eventInfo;\n        let data = [];\n        return createPromise()\n            .then(wait(() => {\n                this.tableDiv.empty();\n                let getSampleWeight = this.selectorView.getSampleWeightFunction();\n                let sampleWeightSuffix = this.selectorView.getSampleWeightSuffix();\n                // Draw a table of 'Total', 'Self', 'Samples', 'Process', 'Thread', 'Library',\n                // 'Function'.\n                let valueSuffix = sampleWeightSuffix.length > 0 ? `(in${sampleWeightSuffix})` : '';\n                let titles = ['Total' + valueSuffix, 'Self' + valueSuffix, 'Samples', 'Process',\n                              'Thread', 'Library', 'Function', 'HideKey'];\n                this.tableDiv.append(`\n                    <table cellspacing=\"0\" class=\"table table-striped table-bordered\"\n                        style=\"width:100%\">\n                        <thead>${getTableRow(titles, 'th')}</thead>\n                        <tbody></tbody>\n                        <tfoot>${getTableRow(titles, 'th')}</tfoot>\n                    </table>`);\n                for (let [i, process] of eventInfo.processes.entries()) {\n                    let processName = getProcessName(process.pid);\n                    for (let [j, thread] of process.threads.entries()) {\n                        let threadName = getThreadName(thread.tid);\n                        for (let [k, lib] of thread.libs.entries()) {\n                            let libName = getLibName(lib.libId);\n                            for (let [t, func] of lib.functions.entries()) {\n                                let totalValue = getSampleWeight(func.c[2]);\n                                let selfValue = getSampleWeight(func.c[1]);\n                                let key = [i, j, k, t].join('_');\n                                data.push([totalValue, selfValue, func.c[0], processName,\n                                           threadName, libName, getFuncName(func.f), key])\n                           }\n                        }\n                    }\n                }\n            }))\n            .then(addProgress(totalProgress / 2))\n            .then(wait(() => {\n                let table = this.tableDiv.find('table');\n                let dataTable = table.DataTable({\n                    lengthMenu: [10, 20, 50, 100, -1],\n                    order: [0, 'desc'],\n                    data: data,\n                    responsive: true,\n                });\n                dataTable.column(7).visible(false);\n\n                table.find('tr').css('cursor', 'pointer');\n                table.on('click', 'tr', function() {\n                    let data = dataTable.row(this).data();\n                    if (!data) {\n                        // A row in header or footer.\n                        return;\n                    }\n                    let key = data[7];\n                    if (!key) {\n                        return;\n                    }\n                    let indexes = key.split('_');\n                    let processInfo = eventInfo.processes[indexes[0]];\n                    let threadInfo = processInfo.threads[indexes[1]];\n                    let lib = threadInfo.libs[indexes[2]];\n                    let func = lib.functions[indexes[3]];\n                    FunctionTab.showFunction(eventInfo, processInfo, threadInfo, lib, func);\n                });\n            }));\n    }\n\n    onSampleWeightChange() {\n        createPromise()\n            .then(updateProgress('Draw SampleTable...', 0))\n            .then(() => this._drawSampleTable(100))\n            .then(hideProgress());\n    }\n}\n\n\n// Show embedded flamegraph generated by inferno.\nclass FlameGraphTab {\n    init(div) {\n        this.div = div;\n    }\n\n    draw() {\n        let views = [];\n        createPromise()\n            .then(updateProgress('Draw Flamegraph...', 0))\n            .then(wait(() => {\n                this.div.empty();\n                views = createViewsForEvents(this.div, (div, eventInfo) => {\n                    return new FlameGraphViewList(div, eventInfo);\n                });\n            }))\n            .then(() => drawViewsAsync(views, 100, (view, progress) => view.drawAsync(progress)))\n            .then(hideProgress());\n    }\n}\n\n// Show FlameGraphs for samples in an event type, used in FlameGraphTab.\n// 1. Draw 10 FlameGraphs at one time, and use a \"More\" button to show more FlameGraphs.\n// 2. First draw background of Flamegraphs, then draw details in idle time.\nclass FlameGraphViewList {\n    constructor(div, eventInfo) {\n        this.div = div;\n        this.eventInfo = eventInfo;\n        this.selectorView = null;\n        this.flamegraphDiv = null;\n        this.flamegraphs = [];\n        this.moreButton = null;\n    }\n\n    drawAsync(totalProgress) {\n        this.div.empty();\n        this.selectorView = new SampleWeightSelectorView(this.div, this.eventInfo,\n                                                         () => this.onSampleWeightChange());\n        this.flamegraphDiv = $('<div>').appendTo(this.div);\n        return this._drawMoreFlameGraphs(10, totalProgress);\n    }\n\n    // Return a promise to draw flamegraphs.\n    _drawMoreFlameGraphs(moreCount, progress) {\n        let initProgress = progress / (1 + moreCount);\n        let newFlamegraphs = [];\n        return createPromise()\n        .then(wait(() => {\n            if (this.moreButton) {\n                this.moreButton.hide();\n            }\n            let pId = 0;\n            let tId = 0;\n            let newCount = this.flamegraphs.length + moreCount;\n            for (let i = 0; i < newCount; ++i) {\n                if (pId == this.eventInfo.processes.length) {\n                    break;\n                }\n                let process = this.eventInfo.processes[pId];\n                let thread = process.threads[tId];\n                if (i >= this.flamegraphs.length) {\n                    let title = `Process ${getProcessName(process.pid)} ` +\n                                `Thread ${getThreadName(thread.tid)} ` +\n                                `(Samples: ${thread.sampleCount})`;\n                    let totalCount = {countForProcess: process.eventCount,\n                                      countForThread: thread.eventCount};\n                    let flamegraph = new FlameGraphView(this.flamegraphDiv, title, totalCount,\n                                                        thread.g.c, false);\n                    flamegraph.draw();\n                    newFlamegraphs.push(flamegraph);\n                }\n                tId++;\n                if (tId == process.threads.length) {\n                    pId++;\n                    tId = 0;\n                }\n            }\n            if (pId < this.eventInfo.processes.length) {\n                // Show \"More\" Button.\n                if (!this.moreButton) {\n                    this.div.append(`\n                        <div style=\"text-align:center\">\n                            <button type=\"button\" class=\"btn btn-primary\">More</button>\n                        </div>`);\n                    this.moreButton = this.div.children().last().find('button');\n                    this.moreButton.click(() => {\n                        createPromise().then(updateProgress('Draw FlameGraph...', 0))\n                            .then(() => this._drawMoreFlameGraphs(10, 100))\n                            .then(hideProgress());\n                    });\n                    this.moreButton.hide();\n                }\n            } else if (this.moreButton) {\n                this.moreButton.remove();\n                this.moreButton = null;\n            }\n            for (let flamegraph of newFlamegraphs) {\n                this.flamegraphs.push(flamegraph);\n            }\n        }))\n        .then(addProgress(initProgress))\n        .then(() => this.drawDetails(newFlamegraphs, progress - initProgress));\n    }\n\n    drawDetails(flamegraphs, totalProgress) {\n        return createPromise()\n            .then(() => drawViewsAsync(flamegraphs, totalProgress, (view, progress) => {\n                return createPromise()\n                    .then(wait(() => view.drawDetails(this.selectorView.getSampleWeightFunction())))\n                    .then(addProgress(progress));\n            }))\n            .then(wait(() => {\n               if (this.moreButton) {\n                   this.moreButton.show();\n               }\n            }));\n    }\n\n    onSampleWeightChange() {\n        createPromise().then(updateProgress('Draw FlameGraph...', 0))\n            .then(() => this.drawDetails(this.flamegraphs, 100))\n            .then(hideProgress());\n    }\n}\n\n// FunctionTab: show information of a function.\n// 1. Show the callgrpah and reverse callgraph of a function as flamegraphs.\n// 2. Show the annotated source code of the function.\nclass FunctionTab {\n    static showFunction(eventInfo, processInfo, threadInfo, lib, func) {\n        let title = 'Function';\n        let tab = gTabs.findTab(title);\n        if (!tab) {\n            tab = gTabs.addTab(title, new FunctionTab());\n        }\n        gTabs.setActiveAsync(title)\n            .then(() => tab.setFunction(eventInfo, processInfo, threadInfo, lib, func));\n    }\n\n    constructor() {\n        this.func = null;\n        this.selectPercent = 'thread';\n    }\n\n    init(div) {\n        this.div = div;\n    }\n\n    setFunction(eventInfo, processInfo, threadInfo, lib, func) {\n        this.eventInfo = eventInfo;\n        this.processInfo = processInfo;\n        this.threadInfo = threadInfo;\n        this.lib = lib;\n        this.func = func;\n        this.selectorView = null;\n        this.views = [];\n        this.redraw();\n    }\n\n    redraw() {\n        if (!this.func) {\n            return;\n        }\n        createPromise()\n            .then(updateProgress(\"Draw Function...\", 0))\n            .then(wait(() => {\n                this.div.empty();\n                this._drawTitle();\n\n                this.selectorView = new SampleWeightSelectorView(this.div, this.eventInfo,\n                                                                 () => this.onSampleWeightChange());\n                let funcId = this.func.f;\n                let funcName = getFuncName(funcId);\n                function getNodesMatchingFuncId(root) {\n                    let nodes = [];\n                    function recursiveFn(node) {\n                        if (node.f == funcId) {\n                            nodes.push(node);\n                        } else {\n                            for (let child of node.c) {\n                                recursiveFn(child);\n                            }\n                        }\n                    }\n                    recursiveFn(root);\n                    return nodes;\n                }\n                let totalCount = {countForProcess: this.processInfo.eventCount,\n                                  countForThread: this.threadInfo.eventCount};\n                let callgraphView = new FlameGraphView(\n                    this.div, `Functions called by ${funcName}`, totalCount,\n                    getNodesMatchingFuncId(this.threadInfo.g), false);\n                callgraphView.draw();\n                this.views.push(callgraphView);\n                let reverseCallgraphView = new FlameGraphView(\n                    this.div, `Functions calling ${funcName}`, totalCount,\n                    getNodesMatchingFuncId(this.threadInfo.rg), true);\n                reverseCallgraphView.draw();\n                this.views.push(reverseCallgraphView);\n                let sourceFiles = collectSourceFilesForFunction(this.func);\n                if (sourceFiles) {\n                    this.div.append(getHtml('hr'));\n                    this.div.append(getHtml('b', {text: 'SourceCode:'}) + '<br/>');\n                    this.views.push(new SourceCodeView(this.div, sourceFiles, totalCount));\n                }\n\n                let disassembly = collectDisassemblyForFunction(this.func);\n                if (disassembly) {\n                    this.div.append(getHtml('hr'));\n                    this.div.append(getHtml('b', {text: 'Disassembly:'}) + '<br/>');\n                    this.views.push(new DisassemblyView(this.div, disassembly, totalCount));\n                }\n            }))\n            .then(addProgress(25))\n            .then(() => this.drawDetails(75))\n            .then(hideProgress());\n    }\n\n    draw() {}\n\n    _drawTitle() {\n        let eventName = this.eventInfo.eventName;\n        let processName = getProcessName(this.processInfo.pid);\n        let threadName = getThreadName(this.threadInfo.tid);\n        let libName = getLibName(this.lib.libId);\n        let funcName = getFuncName(this.func.f);\n        // Draw a table of 'Name', 'Value'.\n        let rows = [];\n        rows.push(['Event Type', eventName]);\n        rows.push(['Process', processName]);\n        rows.push(['Thread', threadName]);\n        rows.push(['Library', libName]);\n        rows.push(['Function', getHtml('pre', {text: funcName})]);\n        let data = new google.visualization.DataTable();\n        data.addColumn('string', '');\n        data.addColumn('string', '');\n        data.addRows(rows);\n        for (let i = 0; i < rows.length; ++i) {\n            data.setProperty(i, 0, 'className', 'boldTableCell');\n        }\n        let wrapperDiv = $('<div>');\n        wrapperDiv.appendTo(this.div);\n        let table = new google.visualization.Table(wrapperDiv.get(0));\n        table.draw(data, {\n            width: '100%',\n            sort: 'disable',\n            allowHtml: true,\n            cssClassNames: {\n                'tableCell': 'tableCell',\n            },\n        });\n    }\n\n    onSampleWeightChange() {\n        createPromise()\n            .then(updateProgress(\"Draw Function...\", 0))\n            .then(() => this.drawDetails(100))\n            .then(hideProgress());\n    }\n\n    drawDetails(totalProgress) {\n        let sampleWeightFunction = this.selectorView.getSampleWeightFunction();\n        return drawViewsAsync(this.views, totalProgress, (view, progress) => {\n            return createPromise()\n                .then(wait(() => view.drawDetails(sampleWeightFunction)))\n                .then(addProgress(progress));\n        });\n    }\n}\n\n\n// Select the way to show sample weight in FlamegraphTab and FunctionTab.\n// 1. Show percentage of event count relative to all processes.\n// 2. Show percentage of event count relative to the current process.\n// 3. Show percentage of event count relative to the current thread.\n// 4. Show absolute event count.\n// 5. Show event count in milliseconds, only possible for cpu-clock or task-clock events.\nclass SampleWeightSelectorView {\n    constructor(divContainer, eventInfo, onSelectChange) {\n        let options = new Map();\n        options.set('percent_to_all', 'Show percentage of event count relative to all processes');\n        options.set('percent_to_process',\n                    'Show percentage of event count relative to the current process');\n        options.set('percent_to_thread',\n                    'Show percentage of event count relative to the current thread');\n        options.set('event_count', 'Show event count');\n        if (isClockEvent(eventInfo)) {\n            options.set('event_count_in_ms', 'Show event count in milliseconds');\n        }\n        let buttons = [];\n        options.forEach((value, key) => {\n            buttons.push(`<button type=\"button\" class=\"dropdown-item\" key=\"${key}\">${value}\n                          </button>`);\n        });\n        this.curOption = 'percent_to_all';\n        let id = createId();\n        let str = `\n            <div class=\"dropdown\">\n                <button type=\"button\" class=\"btn btn-primary dropdown-toggle\" id=\"${id}\"\n                    data-toggle=\"dropdown\" aria-haspopup=\"true\" aria-expanded=\"false\"\n                    >${options.get(this.curOption)}</button>\n                <div class=\"dropdown-menu\" aria-labelledby=\"${id}\">${buttons.join('')}</div>\n            </div>\n        `;\n        divContainer.append(str);\n        divContainer.children().last().on('hidden.bs.dropdown', (e) => {\n            if (e.clickEvent) {\n                let button = $(e.clickEvent.target);\n                let newOption = button.attr('key');\n                if (newOption && this.curOption != newOption) {\n                    this.curOption = newOption;\n                    divContainer.find(`#${id}`).text(options.get(this.curOption));\n                    onSelectChange();\n                }\n            }\n        });\n        this.countForAllProcesses = eventInfo.eventCount;\n    }\n\n    getSampleWeightFunction() {\n        if (this.curOption == 'percent_to_all') {\n            let countForAllProcesses = this.countForAllProcesses;\n            return function(eventCount, _) {\n                let percent = eventCount * 100.0 / countForAllProcesses;\n                return percent.toFixed(2) + '%';\n            };\n        }\n        if (this.curOption == 'percent_to_process') {\n            return function(eventCount, totalCount) {\n                let percent = eventCount * 100.0 / totalCount.countForProcess;\n                return percent.toFixed(2) + '%';\n            };\n        }\n        if (this.curOption == 'percent_to_thread') {\n            return function(eventCount, totalCount) {\n                let percent = eventCount * 100.0 / totalCount.countForThread;\n                return percent.toFixed(2) + '%';\n            };\n        }\n        if (this.curOption == 'event_count') {\n            return function(eventCount, _) {\n                return '' + eventCount;\n            };\n        }\n        if (this.curOption == 'event_count_in_ms') {\n            return function(eventCount, _) {\n                let timeInMs = eventCount / 1000000.0;\n                return timeInMs.toFixed(3) + ' ms';\n            };\n        }\n    }\n}\n\n// Given a callgraph, show the flamegraph.\nclass FlameGraphView {\n    constructor(divContainer, title, totalCount, initNodes, reverseOrder) {\n        this.id = createId();\n        this.div = $('<div>', {id: this.id,\n                               style: 'font-family: Monospace; font-size: 12px'});\n        this.div.appendTo(divContainer);\n        this.title = title;\n        this.totalCount = totalCount;\n        this.reverseOrder = reverseOrder;\n        this.sampleWeightFunction = null;\n        this.svgNodeHeight = 17;\n        this.initNodes = initNodes;\n        this.sumCount = 0;\n        for (let node of initNodes) {\n            this.sumCount += node.s;\n        }\n        this.maxDepth = this._getMaxDepth(this.initNodes);\n        this.svgHeight = this.svgNodeHeight * (this.maxDepth + 3);\n        this.svgStr = null;\n        this.svgDiv = null;\n        this.svg = null;\n    }\n\n    _getMaxDepth(nodes) {\n        let isArray = Array.isArray(nodes);\n        let sumCount;\n        if (isArray) {\n            sumCount = nodes.reduce((acc, cur) => acc + cur.s, 0);\n        } else {\n            sumCount = nodes.s;\n        }\n        let width = this._getWidthPercentage(sumCount);\n        if (width < 0.1) {\n            return 0;\n        }\n        let children = isArray ? this._splitChildrenForNodes(nodes) : nodes.c;\n        let childDepth = 0;\n        for (let child of children) {\n            childDepth = Math.max(childDepth, this._getMaxDepth(child));\n        }\n        return childDepth + 1;\n    }\n\n    draw() {\n        // Only draw skeleton.\n        this.div.empty();\n        this.div.append(`<p><b>${this.title}</b></p>`);\n        this.svgStr = [];\n        this._renderBackground();\n        this.svgStr.push('</svg></div>');\n        this.div.append(this.svgStr.join(''));\n        this.svgDiv = this.div.children().last();\n        this.div.append('<br/><br/>');\n    }\n\n    drawDetails(sampleWeightFunction) {\n        this.sampleWeightFunction = sampleWeightFunction;\n        this.svgStr = [];\n        this._renderBackground();\n        this._renderSvgNodes();\n        this._renderUnzoomNode();\n        this._renderInfoNode();\n        this._renderPercentNode();\n        this._renderSearchNode();\n        // It is much faster to add html content to svgStr than adding it directly to svgDiv.\n        this.svgDiv.html(this.svgStr.join(''));\n        this.svgStr = [];\n        this.svg = this.svgDiv.find('svg');\n        this._adjustTextSize();\n        this._enableZoom();\n        this._enableInfo();\n        this._enableSearch();\n        this._adjustTextSizeOnResize();\n    }\n\n    _renderBackground() {\n        this.svgStr.push(`\n            <div style=\"width: 100%; height: ${this.svgHeight}px;\">\n                <svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n                    version=\"1.1\" width=\"100%\" height=\"100%\" style=\"border: 1px solid black; \">\n                        <defs > <linearGradient id=\"background_gradient_${this.id}\"\n                                  y1=\"0\" y2=\"1\" x1=\"0\" x2=\"0\" >\n                                  <stop stop-color=\"#eeeeee\" offset=\"5%\" />\n                                  <stop stop-color=\"#efefb1\" offset=\"90%\" />\n                                  </linearGradient>\n                         </defs>\n                         <rect x=\"0\" y=\"0\" width=\"100%\" height=\"100%\"\n                           fill=\"url(#background_gradient_${this.id})\" />`);\n    }\n\n    _getYForDepth(depth) {\n        if (this.reverseOrder) {\n            return (depth + 3) * this.svgNodeHeight;\n        }\n        return this.svgHeight - (depth + 1) * this.svgNodeHeight;\n    }\n\n    _getWidthPercentage(eventCount) {\n        return eventCount * 100.0 / this.sumCount;\n    }\n\n    _getHeatColor(widthPercentage) {\n        return {\n            r: Math.floor(245 + 10 * (1 - widthPercentage * 0.01)),\n            g: Math.floor(110 + 105 * (1 - widthPercentage * 0.01)),\n            b: 100,\n        };\n    }\n\n    _renderSvgNodes() {\n        let fakeNodes = [{c: this.initNodes}];\n        let children = this._splitChildrenForNodes(fakeNodes);\n        let xOffset = 0;\n        for (let child of children) {\n            xOffset = this._renderSvgNodesWithSameRoot(child, 0, xOffset);\n        }\n    }\n\n    // Return an array of children nodes, with children having the same functionId merged in a\n    // subarray.\n    _splitChildrenForNodes(nodes) {\n        let map = new Map();\n        for (let node of nodes) {\n            for (let child of node.c) {\n                let subNodes = map.get(child.f);\n                if (subNodes) {\n                    subNodes.push(child);\n                } else {\n                    map.set(child.f, [child]);\n                }\n            }\n        }\n        let res = [];\n        for (let subNodes of map.values()) {\n            res.push(subNodes.length == 1 ? subNodes[0] : subNodes);\n        }\n        return res;\n    }\n\n    // nodes can be a CallNode, or an array of CallNodes with the same functionId.\n    _renderSvgNodesWithSameRoot(nodes, depth, xOffset) {\n        let x = xOffset;\n        let y = this._getYForDepth(depth);\n        let isArray = Array.isArray(nodes);\n        let funcId;\n        let sumCount;\n        if (isArray) {\n            funcId = nodes[0].f;\n            sumCount = nodes.reduce((acc, cur) => acc + cur.s, 0);\n        } else {\n            funcId = nodes.f;\n            sumCount = nodes.s;\n        }\n        let width = this._getWidthPercentage(sumCount);\n        if (width < 0.1) {\n            return xOffset;\n        }\n        let color = this._getHeatColor(width);\n        let borderColor = {};\n        for (let key in color) {\n            borderColor[key] = Math.max(0, color[key] - 50);\n        }\n        let funcName = getFuncName(funcId);\n        let libName = getLibNameOfFunction(funcId);\n        let sampleWeight = this.sampleWeightFunction(sumCount, this.totalCount);\n        let title = funcName + ' | ' + libName + ' (' + sumCount + ' events: ' +\n                    sampleWeight + ')';\n        this.svgStr.push(`<g><title>${title}</title> <rect x=\"${x}%\" y=\"${y}\" ox=\"${x}\"\n                        depth=\"${depth}\" width=\"${width}%\" owidth=\"${width}\" height=\"15.0\"\n                        ofill=\"rgb(${color.r},${color.g},${color.b})\"\n                        fill=\"rgb(${color.r},${color.g},${color.b})\"\n                        style=\"stroke:rgb(${borderColor.r},${borderColor.g},${borderColor.b})\"/>\n                        <text x=\"${x}%\" y=\"${y + 12}\"></text></g>`);\n\n        let children = isArray ? this._splitChildrenForNodes(nodes) : nodes.c;\n        let childXOffset = xOffset;\n        for (let child of children) {\n            childXOffset = this._renderSvgNodesWithSameRoot(child, depth + 1, childXOffset);\n        }\n        return xOffset + width;\n    }\n\n    _renderUnzoomNode() {\n        this.svgStr.push(`<rect id=\"zoom_rect_${this.id}\" style=\"display:none;stroke:rgb(0,0,0);\"\n        rx=\"10\" ry=\"10\" x=\"10\" y=\"10\" width=\"80\" height=\"30\"\n        fill=\"rgb(255,255,255)\"/>\n         <text id=\"zoom_text_${this.id}\" x=\"19\" y=\"30\" style=\"display:none\">Zoom out</text>`);\n    }\n\n    _renderInfoNode() {\n        this.svgStr.push(`<clipPath id=\"info_clip_path_${this.id}\">\n                         <rect style=\"stroke:rgb(0,0,0);\" rx=\"10\" ry=\"10\" x=\"120\" y=\"10\"\n                         width=\"789\" height=\"30\" fill=\"rgb(255,255,255)\"/>\n                         </clipPath>\n                         <rect style=\"stroke:rgb(0,0,0);\" rx=\"10\" ry=\"10\" x=\"120\" y=\"10\"\n                         width=\"799\" height=\"30\" fill=\"rgb(255,255,255)\"/>\n                         <text clip-path=\"url(#info_clip_path_${this.id})\"\n                         id=\"info_text_${this.id}\" x=\"128\" y=\"30\"></text>`);\n    }\n\n    _renderPercentNode() {\n        this.svgStr.push(`<rect style=\"stroke:rgb(0,0,0);\" rx=\"10\" ry=\"10\"\n                         x=\"934\" y=\"10\" width=\"150\" height=\"30\"\n                         fill=\"rgb(255,255,255)\"/>\n                         <text id=\"percent_text_${this.id}\" text-anchor=\"end\"\n                         x=\"1074\" y=\"30\"></text>`);\n    }\n\n    _renderSearchNode() {\n        this.svgStr.push(`<rect style=\"stroke:rgb(0,0,0); rx=\"10\" ry=\"10\"\n                         x=\"1150\" y=\"10\" width=\"80\" height=\"30\"\n                         fill=\"rgb(255,255,255)\" class=\"search\"/>\n                         <text x=\"1160\" y=\"30\" class=\"search\">Search</text>`);\n    }\n\n    _adjustTextSizeForNode(g) {\n        let text = g.find('text');\n        let width = parseFloat(g.find('rect').attr('width')) * this.svgWidth * 0.01;\n        if (width < 28) {\n            text.text('');\n            return;\n        }\n        let methodName = g.find('title').text().split(' | ')[0];\n        let numCharacters;\n        for (numCharacters = methodName.length; numCharacters > 4; numCharacters--) {\n            if (numCharacters * 7.5 <= width) {\n                break;\n            }\n        }\n        if (numCharacters == methodName.length) {\n            text.text(methodName);\n        } else {\n            text.text(methodName.substring(0, numCharacters - 2) + '..');\n        }\n    }\n\n    _adjustTextSize() {\n        this.svgWidth = $(window).width();\n        let thisObj = this;\n        this.svg.find('g').each(function(_, g) {\n            thisObj._adjustTextSizeForNode($(g));\n        });\n    }\n\n    _enableZoom() {\n        this.zoomStack = [null];\n        this.svg.find('g').css('cursor', 'pointer').click(zoom);\n        this.svg.find(`#zoom_rect_${this.id}`).css('cursor', 'pointer').click(unzoom);\n        this.svg.find(`#zoom_text_${this.id}`).css('cursor', 'pointer').click(unzoom);\n\n        let thisObj = this;\n        function zoom() {\n            thisObj.zoomStack.push(this);\n            displayFromElement(this);\n            thisObj.svg.find(`#zoom_rect_${thisObj.id}`).css('display', 'block');\n            thisObj.svg.find(`#zoom_text_${thisObj.id}`).css('display', 'block');\n        }\n\n        function unzoom() {\n            if (thisObj.zoomStack.length > 1) {\n                thisObj.zoomStack.pop();\n                displayFromElement(thisObj.zoomStack[thisObj.zoomStack.length - 1]);\n                if (thisObj.zoomStack.length == 1) {\n                    thisObj.svg.find(`#zoom_rect_${thisObj.id}`).css('display', 'none');\n                    thisObj.svg.find(`#zoom_text_${thisObj.id}`).css('display', 'none');\n                }\n            }\n        }\n\n        function displayFromElement(g) {\n            let clickedOriginX = 0;\n            let clickedDepth = 0;\n            let clickedOriginWidth = 100;\n            let scaleFactor = 1;\n            if (g) {\n                g = $(g);\n                let clickedRect = g.find('rect');\n                clickedOriginX = parseFloat(clickedRect.attr('ox'));\n                clickedDepth = parseInt(clickedRect.attr('depth'));\n                clickedOriginWidth = parseFloat(clickedRect.attr('owidth'));\n                scaleFactor = 100.0 / clickedOriginWidth;\n            }\n            thisObj.svg.find('g').each(function(_, g) {\n                g = $(g);\n                let text = g.find('text');\n                let rect = g.find('rect');\n                let depth = parseInt(rect.attr('depth'));\n                let ox = parseFloat(rect.attr('ox'));\n                let owidth = parseFloat(rect.attr('owidth'));\n                if (depth < clickedDepth || ox < clickedOriginX - 1e-9 ||\n                    ox + owidth > clickedOriginX + clickedOriginWidth + 1e-9) {\n                    rect.css('display', 'none');\n                    text.css('display', 'none');\n                } else {\n                    rect.css('display', 'block');\n                    text.css('display', 'block');\n                    let nx = (ox - clickedOriginX) * scaleFactor + '%';\n                    let ny = thisObj._getYForDepth(depth - clickedDepth);\n                    rect.attr('x', nx);\n                    rect.attr('y', ny);\n                    rect.attr('width', owidth * scaleFactor + '%');\n                    text.attr('x', nx);\n                    text.attr('y', ny + 12);\n                    thisObj._adjustTextSizeForNode(g);\n                }\n            });\n        }\n    }\n\n    _enableInfo() {\n        this.selected = null;\n        let thisObj = this;\n        this.svg.find('g').on('mouseenter', function() {\n            if (thisObj.selected) {\n                thisObj.selected.css('stroke-width', '0');\n            }\n            // Mark current node.\n            let g = $(this);\n            thisObj.selected = g;\n            g.css('stroke', 'black').css('stroke-width', '0.5');\n\n            // Parse title.\n            let title = g.find('title').text();\n            let methodAndInfo = title.split(' | ');\n            thisObj.svg.find(`#info_text_${thisObj.id}`).text(methodAndInfo[0]);\n\n            // Parse percentage.\n            // '/system/lib64/libhwbinder.so (4 events: 0.28%)'\n            let regexp = /.* \\(.*:\\s+(.*)\\)/g;\n            let match = regexp.exec(methodAndInfo[1]);\n            let percentage = '';\n            if (match && match.length > 1) {\n                percentage = match[1];\n            }\n            thisObj.svg.find(`#percent_text_${thisObj.id}`).text(percentage);\n        });\n    }\n\n    _enableSearch() {\n        this.svg.find('.search').css('cursor', 'pointer').click(() => {\n            let term = prompt('Search for:', '');\n            if (!term) {\n                this.svg.find('g > rect').each(function() {\n                    this.attributes['fill'].value = this.attributes['ofill'].value;\n                });\n            } else {\n                this.svg.find('g').each(function() {\n                    let title = this.getElementsByTagName('title')[0];\n                    let rect = this.getElementsByTagName('rect')[0];\n                    if (title.textContent.indexOf(term) != -1) {\n                        rect.attributes['fill'].value = 'rgb(230,100,230)';\n                    } else {\n                        rect.attributes['fill'].value = rect.attributes['ofill'].value;\n                    }\n                });\n            }\n        });\n    }\n\n    _adjustTextSizeOnResize() {\n        function throttle(callback) {\n            let running = false;\n            return function() {\n                if (!running) {\n                    running = true;\n                    window.requestAnimationFrame(function () {\n                        callback();\n                        running = false;\n                    });\n                }\n            };\n        }\n        $(window).resize(throttle(() => this._adjustTextSize()));\n    }\n}\n\n\nclass SourceFile {\n\n    constructor(fileId) {\n        this.path = getSourceFilePath(fileId);\n        this.code = getSourceCode(fileId);\n        this.showLines = {};  // map from line number to {eventCount, subtreeEventCount}.\n        this.hasCount = false;\n    }\n\n    addLineRange(startLine, endLine) {\n        for (let i = startLine; i <= endLine; ++i) {\n            if (i in this.showLines || !(i in this.code)) {\n                continue;\n            }\n            this.showLines[i] = {eventCount: 0, subtreeEventCount: 0};\n        }\n    }\n\n    addLineCount(lineNumber, eventCount, subtreeEventCount) {\n        let line = this.showLines[lineNumber];\n        if (line) {\n            line.eventCount += eventCount;\n            line.subtreeEventCount += subtreeEventCount;\n            this.hasCount = true;\n        }\n    }\n}\n\n// Return a list of SourceFile related to a function.\nfunction collectSourceFilesForFunction(func) {\n    if (!func.hasOwnProperty('s')) {\n        return null;\n    }\n    let hitLines = func.s;\n    let sourceFiles = {};  // map from sourceFileId to SourceFile.\n\n    function getFile(fileId) {\n        let file = sourceFiles[fileId];\n        if (!file) {\n            file = sourceFiles[fileId] = new SourceFile(fileId);\n        }\n        return file;\n    }\n\n    // Show lines for the function.\n    let funcRange = getFuncSourceRange(func.f);\n    if (funcRange) {\n        let file = getFile(funcRange.fileId);\n        file.addLineRange(funcRange.startLine);\n    }\n\n    // Show lines for hitLines.\n    for (let hitLine of hitLines) {\n        let file = getFile(hitLine.f);\n        file.addLineRange(hitLine.l - 5, hitLine.l + 5);\n        file.addLineCount(hitLine.l, hitLine.e, hitLine.s);\n    }\n\n    let result = [];\n    // Show the source file containing the function before other source files.\n    if (funcRange) {\n        let file = getFile(funcRange.fileId);\n        if (file.hasCount) {\n            result.push(file);\n        }\n        delete sourceFiles[funcRange.fileId];\n    }\n    for (let fileId in sourceFiles) {\n        let file = sourceFiles[fileId];\n        if (file.hasCount) {\n            result.push(file);\n        }\n    }\n    return result.length > 0 ? result : null;\n}\n\n// Show annotated source code of a function.\nclass SourceCodeView {\n\n    constructor(divContainer, sourceFiles, totalCount) {\n        this.div = $('<div>');\n        this.div.appendTo(divContainer);\n        this.sourceFiles = sourceFiles;\n        this.totalCount = totalCount;\n    }\n\n    drawDetails(sampleWeightFunction) {\n        google.charts.setOnLoadCallback(() => this.realDraw(sampleWeightFunction));\n    }\n\n    realDraw(sampleWeightFunction) {\n        this.div.empty();\n        // For each file, draw a table of 'Line', 'Total', 'Self', 'Code'.\n        for (let sourceFile of this.sourceFiles) {\n            let rows = [];\n            let lineNumbers = Object.keys(sourceFile.showLines);\n            lineNumbers.sort((a, b) => a - b);\n            for (let lineNumber of lineNumbers) {\n                let code = getHtml('pre', {text: sourceFile.code[lineNumber]});\n                let countInfo = sourceFile.showLines[lineNumber];\n                let totalValue = '';\n                let selfValue = '';\n                if (countInfo.subtreeEventCount != 0) {\n                    totalValue = sampleWeightFunction(countInfo.subtreeEventCount, this.totalCount);\n                    selfValue = sampleWeightFunction(countInfo.eventCount, this.totalCount);\n                }\n                rows.push([lineNumber, totalValue, selfValue, code]);\n            }\n\n            let data = new google.visualization.DataTable();\n            data.addColumn('string', 'Line');\n            data.addColumn('string', 'Total');\n            data.addColumn('string', 'Self');\n            data.addColumn('string', 'Code');\n            data.addRows(rows);\n            for (let i = 0; i < rows.length; ++i) {\n                data.setProperty(i, 0, 'className', 'colForLine');\n                for (let j = 1; j <= 2; ++j) {\n                    data.setProperty(i, j, 'className', 'colForCount');\n                }\n            }\n            this.div.append(getHtml('pre', {text: sourceFile.path}));\n            let wrapperDiv = $('<div>');\n            wrapperDiv.appendTo(this.div);\n            let table = new google.visualization.Table(wrapperDiv.get(0));\n            table.draw(data, {\n                width: '100%',\n                sort: 'disable',\n                frozenColumns: 3,\n                allowHtml: true,\n            });\n        }\n    }\n}\n\n// Return a list of disassembly related to a function.\nfunction collectDisassemblyForFunction(func) {\n    if (!func.hasOwnProperty('a')) {\n        return null;\n    }\n    let hitAddrs = func.a;\n    let rawCode = getFuncDisassembly(func.f);\n    if (!rawCode) {\n        return null;\n    }\n\n    // Annotate disassembly with event count information.\n    let annotatedCode = [];\n    let codeForLastAddr = null;\n    let hitAddrPos = 0;\n    let hasCount = false;\n\n    function addEventCount(addr) {\n        while (hitAddrPos < hitAddrs.length && BigInt(hitAddrs[hitAddrPos].a) < addr) {\n            if (codeForLastAddr) {\n                codeForLastAddr.eventCount += hitAddrs[hitAddrPos].e;\n                codeForLastAddr.subtreeEventCount += hitAddrs[hitAddrPos].s;\n                hasCount = true;\n            }\n            hitAddrPos++;\n        }\n    }\n\n    for (let line of rawCode) {\n        let code = line[0];\n        let addr = BigInt(line[1]);\n\n        addEventCount(addr);\n        let item = {code: code, eventCount: 0, subtreeEventCount: 0};\n        annotatedCode.push(item);\n        // Objdump sets addr to 0 when a disassembly line is not associated with an addr.\n        if (addr != 0) {\n            codeForLastAddr = item;\n        }\n    }\n    addEventCount(Number.MAX_VALUE);\n    return hasCount ? annotatedCode : null;\n}\n\n// Show annotated disassembly of a function.\nclass DisassemblyView {\n\n    constructor(divContainer, disassembly, totalCount) {\n        this.div = $('<div>');\n        this.div.appendTo(divContainer);\n        this.disassembly = disassembly;\n        this.totalCount = totalCount;\n    }\n\n    drawDetails(sampleWeightFunction) {\n        google.charts.setOnLoadCallback(() => this.realDraw(sampleWeightFunction));\n    }\n\n    realDraw(sampleWeightFunction) {\n        this.div.empty();\n        // Draw a table of 'Total', 'Self', 'Code'.\n        let rows = [];\n        for (let line of this.disassembly) {\n            let code = getHtml('pre', {text: line.code});\n            let totalValue = '';\n            let selfValue = '';\n            if (line.subtreeEventCount != 0) {\n                totalValue = sampleWeightFunction(line.subtreeEventCount, this.totalCount);\n                selfValue = sampleWeightFunction(line.eventCount, this.totalCount);\n            }\n            rows.push([totalValue, selfValue, code]);\n        }\n        let data = new google.visualization.DataTable();\n        data.addColumn('string', 'Total');\n        data.addColumn('string', 'Self');\n        data.addColumn('string', 'Code');\n        data.addRows(rows);\n        for (let i = 0; i < rows.length; ++i) {\n            for (let j = 0; j < 2; ++j) {\n                data.setProperty(i, j, 'className', 'colForCount');\n            }\n        }\n        let wrapperDiv = $('<div>');\n        wrapperDiv.appendTo(this.div);\n        let table = new google.visualization.Table(wrapperDiv.get(0));\n        table.draw(data, {\n            width: '100%',\n            sort: 'disable',\n            frozenColumns: 2,\n            allowHtml: true,\n        });\n    }\n}\n\n\nfunction initGlobalObjects() {\n    let recordData = $('#record_data').text();\n    gRecordInfo = JSON.parse(recordData);\n    gProcesses = gRecordInfo.processNames;\n    gThreads = gRecordInfo.threadNames;\n    gLibList = gRecordInfo.libList;\n    gFunctionMap = gRecordInfo.functionMap;\n    gSampleInfo = gRecordInfo.sampleInfo;\n    gSourceFiles = gRecordInfo.sourceFiles;\n}\n\nfunction createTabs() {\n    gTabs = new TabManager($('div#report_content'));\n    gTabs.addTab('Chart Statistics', new ChartStatTab());\n    gTabs.addTab('Sample Table', new SampleTableTab());\n    gTabs.addTab('Flamegraph', new FlameGraphTab());\n}\n\n// Global draw objects\nlet gTabs;\nlet gProgressBar = new ProgressBar();\n\n// Gobal Json Data\nlet gRecordInfo;\nlet gProcesses;\nlet gThreads;\nlet gLibList;\nlet gFunctionMap;\nlet gSampleInfo;\nlet gSourceFiles;\n\nfunction updateProgress(text, progress) {\n    return () => gProgressBar.updateAsync(text, progress);\n}\n\nfunction addProgress(progress) {\n    return () => gProgressBar.updateAsync(null, gProgressBar.progress + progress);\n}\n\nfunction hideProgress() {\n    return () => gProgressBar.hide();\n}\n\nfunction createPromise(callback) {\n    if (callback) {\n        return new Promise((resolve, _) => callback(resolve));\n    }\n    return new Promise((resolve,_) => resolve());\n}\n\nfunction waitDocumentReady() {\n    return createPromise((resolve) => $(document).ready(resolve));\n}\n\nfunction wait(functionCall) {\n    return () => {\n        functionCall();\n        return createPromise();\n    };\n}\n\ncreatePromise()\n    .then(updateProgress('Load page...', 0))\n    .then(waitDocumentReady)\n    .then(updateProgress('Parse Json data...', 20))\n    .then(wait(initGlobalObjects))\n    .then(updateProgress('Create tabs...', 30))\n    .then(wait(createTabs))\n    .then(updateProgress('Draw ChartStat...', 40))\n    .then(() => gTabs.setActiveAsync('Chart Statistics'))\n    .then(updateProgress(null, 100))\n    .then(hideProgress());\n})();\n"
  },
  {
    "path": "simpleperf/report_html.py",
    "content": "#!/usr/bin/env python3\n#\n# Copyright (C) 2017 The Android Open Source Project\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nfrom __future__ import annotations\nimport argparse\nimport collections\nfrom concurrent.futures import Future, ThreadPoolExecutor\nfrom dataclasses import dataclass\nimport datetime\nimport json\nimport logging\nimport os\nfrom pathlib import Path\nimport sys\nfrom typing import Any, Callable, Dict, Iterator, List, Optional, Set, Tuple, Union\n\nfrom simpleperf_report_lib import ReportLib, SymbolStruct\nfrom simpleperf_utils import (\n    Addr2Nearestline, BaseArgumentParser, BinaryFinder, get_script_dir, log_exit, Objdump,\n    open_report_in_browser, ReadElf, SourceFileSearcher)\n\nMAX_CALLSTACK_LENGTH = 750\n\n\nclass HtmlWriter(object):\n\n    def __init__(self, output_path: Union[Path, str]):\n        self.fh = open(output_path, 'w')\n        self.tag_stack = []\n\n    def close(self):\n        self.fh.close()\n\n    def open_tag(self, tag: str, **attrs: Dict[str, str]) -> HtmlWriter:\n        attr_str = ''\n        for key in attrs:\n            attr_str += ' %s=\"%s\"' % (key, attrs[key])\n        self.fh.write('<%s%s>' % (tag, attr_str))\n        self.tag_stack.append(tag)\n        return self\n\n    def close_tag(self, tag: Optional[str] = None):\n        if tag:\n            assert tag == self.tag_stack[-1]\n        self.fh.write('</%s>\\n' % self.tag_stack.pop())\n\n    def add(self, text: str) -> HtmlWriter:\n        self.fh.write(text)\n        return self\n\n    def add_file(self, file_path: Union[Path, str]) -> HtmlWriter:\n        file_path = os.path.join(get_script_dir(), file_path)\n        with open(file_path, 'r') as f:\n            self.add(f.read())\n        return self\n\n\ndef modify_text_for_html(text: str) -> str:\n    return text.replace('>', '&gt;').replace('<', '&lt;')\n\n\ndef hex_address_for_json(addr: int) -> str:\n    \"\"\" To handle big addrs (nears uint64_max) in Javascript, store addrs as hex strings in Json.\n    \"\"\"\n    return '0x%x' % addr\n\n\nclass EventScope(object):\n\n    def __init__(self, name: str):\n        self.name = name\n        self.processes: Dict[int, ProcessScope] = {}  # map from pid to ProcessScope\n        self.sample_count = 0\n        self.event_count = 0\n\n    def get_process(self, pid: int) -> ProcessScope:\n        process = self.processes.get(pid)\n        if not process:\n            process = self.processes[pid] = ProcessScope(pid)\n        return process\n\n    def get_sample_info(self, gen_addr_hit_map: bool) -> Dict[str, Any]:\n        result = {}\n        result['eventName'] = self.name\n        result['eventCount'] = self.event_count\n        processes = sorted(self.processes.values(), key=lambda a: a.event_count, reverse=True)\n        result['processes'] = [process.get_sample_info(gen_addr_hit_map)\n                               for process in processes]\n        return result\n\n    @property\n    def threads(self) -> Iterator[ThreadScope]:\n        for process in self.processes.values():\n            for thread in process.threads.values():\n                yield thread\n\n    @property\n    def libraries(self) -> Iterator[LibScope]:\n        for process in self.processes.values():\n            for thread in process.threads.values():\n                for lib in thread.libs.values():\n                    yield lib\n\n\nclass ProcessScope(object):\n\n    def __init__(self, pid: int):\n        self.pid = pid\n        self.name = ''\n        self.event_count = 0\n        self.threads: Dict[int, ThreadScope] = {}  # map from tid to ThreadScope\n\n    def get_thread(self, tid: int, thread_name: str) -> ThreadScope:\n        thread = self.threads.get(tid)\n        if not thread:\n            thread = self.threads[tid] = ThreadScope(tid)\n        thread.name = thread_name\n        if self.pid == tid:\n            self.name = thread_name\n        return thread\n\n    def get_sample_info(self, gen_addr_hit_map: bool) -> Dict[str, Any]:\n        result = {}\n        result['pid'] = self.pid\n        result['eventCount'] = self.event_count\n        # Sorting threads by sample count is better for profiles recorded with --trace-offcpu.\n        threads = sorted(self.threads.values(), key=lambda a: a.sample_count, reverse=True)\n        result['threads'] = [thread.get_sample_info(gen_addr_hit_map)\n                             for thread in threads]\n        return result\n\n    def merge_by_thread_name(self, process: ProcessScope):\n        self.event_count += process.event_count\n        thread_list: List[ThreadScope] = list(\n            self.threads.values()) + list(process.threads.values())\n        new_threads: Dict[str, ThreadScope] = {}  # map from thread name to ThreadScope\n        for thread in thread_list:\n            cur_thread = new_threads.get(thread.name)\n            if cur_thread is None:\n                new_threads[thread.name] = thread\n            else:\n                cur_thread.merge(thread)\n        self.threads = {}\n        for thread in new_threads.values():\n            self.threads[thread.tid] = thread\n\n\nclass ThreadScope(object):\n\n    def __init__(self, tid: int):\n        self.tid = tid\n        self.name = ''\n        self.event_count = 0\n        self.sample_count = 0\n        self.libs: Dict[int, LibScope] = {}  # map from lib_id to LibScope\n        self.call_graph = CallNode(-1)\n        self.reverse_call_graph = CallNode(-1)\n\n    def add_callstack(\n            self, event_count: int, callstack: List[Tuple[int, int, int]],\n            build_addr_hit_map: bool):\n        \"\"\" callstack is a list of tuple (lib_id, func_id, addr).\n            For each i > 0, callstack[i] calls callstack[i-1].\"\"\"\n        hit_func_ids: Set[int] = set()\n        for i, (lib_id, func_id, addr) in enumerate(callstack):\n            # When a callstack contains recursive function, only add for each function once.\n            if func_id in hit_func_ids:\n                continue\n            hit_func_ids.add(func_id)\n\n            lib = self.libs.get(lib_id)\n            if not lib:\n                lib = self.libs[lib_id] = LibScope(lib_id)\n            function = lib.get_function(func_id)\n            function.subtree_event_count += event_count\n            if i == 0:\n                lib.event_count += event_count\n                function.event_count += event_count\n                function.sample_count += 1\n            if build_addr_hit_map:\n                function.build_addr_hit_map(addr, event_count if i == 0 else 0, event_count)\n\n        # build call graph and reverse call graph\n        node = self.call_graph\n        for item in reversed(callstack):\n            node = node.get_child(item[1])\n        node.event_count += event_count\n        node = self.reverse_call_graph\n        for item in callstack:\n            node = node.get_child(item[1])\n        node.event_count += event_count\n\n    def update_subtree_event_count(self):\n        self.call_graph.update_subtree_event_count()\n        self.reverse_call_graph.update_subtree_event_count()\n\n    def limit_percents(self, min_func_limit: float, min_callchain_percent: float,\n                       hit_func_ids: Set[int]):\n        for lib in self.libs.values():\n            to_del_funcs = []\n            for function in lib.functions.values():\n                if function.subtree_event_count < min_func_limit:\n                    to_del_funcs.append(function.func_id)\n                else:\n                    hit_func_ids.add(function.func_id)\n            for func_id in to_del_funcs:\n                del lib.functions[func_id]\n        min_limit = min_callchain_percent * 0.01 * self.call_graph.subtree_event_count\n        self.call_graph.cut_edge(min_limit, hit_func_ids)\n        self.reverse_call_graph.cut_edge(min_limit, hit_func_ids)\n\n    def get_sample_info(self, gen_addr_hit_map: bool) -> Dict[str, Any]:\n        result = {}\n        result['tid'] = self.tid\n        result['eventCount'] = self.event_count\n        result['sampleCount'] = self.sample_count\n        result['libs'] = [lib.gen_sample_info(gen_addr_hit_map)\n                          for lib in self.libs.values()]\n        result['g'] = self.call_graph.gen_sample_info()\n        result['rg'] = self.reverse_call_graph.gen_sample_info()\n        return result\n\n    def merge(self, thread: ThreadScope):\n        self.event_count += thread.event_count\n        self.sample_count += thread.sample_count\n        for lib_id, lib in thread.libs.items():\n            cur_lib = self.libs.get(lib_id)\n            if cur_lib is None:\n                self.libs[lib_id] = lib\n            else:\n                cur_lib.merge(lib)\n        self.call_graph.merge(thread.call_graph)\n        self.reverse_call_graph.merge(thread.reverse_call_graph)\n\n\nclass LibScope(object):\n\n    def __init__(self, lib_id: int):\n        self.lib_id = lib_id\n        self.event_count = 0\n        self.functions: Dict[int, FunctionScope] = {}  # map from func_id to FunctionScope.\n\n    def get_function(self, func_id: int) -> FunctionScope:\n        function = self.functions.get(func_id)\n        if not function:\n            function = self.functions[func_id] = FunctionScope(func_id)\n        return function\n\n    def gen_sample_info(self, gen_addr_hit_map: bool) -> Dict[str, Any]:\n        result = {}\n        result['libId'] = self.lib_id\n        result['eventCount'] = self.event_count\n        result['functions'] = [func.gen_sample_info(gen_addr_hit_map)\n                               for func in self.functions.values()]\n        return result\n\n    def merge(self, lib: LibScope):\n        self.event_count += lib.event_count\n        for func_id, function in lib.functions.items():\n            cur_function = self.functions.get(func_id)\n            if cur_function is None:\n                self.functions[func_id] = function\n            else:\n                cur_function.merge(function)\n\n\nclass FunctionScope(object):\n\n    def __init__(self, func_id: int):\n        self.func_id = func_id\n        self.sample_count = 0\n        self.event_count = 0\n        self.subtree_event_count = 0\n        self.addr_hit_map = None  # map from addr to [event_count, subtree_event_count].\n        # map from (source_file_id, line) to [event_count, subtree_event_count].\n        self.line_hit_map = None\n\n    def build_addr_hit_map(self, addr: int, event_count: int, subtree_event_count: int):\n        if self.addr_hit_map is None:\n            self.addr_hit_map = {}\n        count_info = self.addr_hit_map.get(addr)\n        if count_info is None:\n            self.addr_hit_map[addr] = [event_count, subtree_event_count]\n        else:\n            count_info[0] += event_count\n            count_info[1] += subtree_event_count\n\n    def build_line_hit_map(self, source_file_id: int, line: int, event_count: int,\n                           subtree_event_count: int):\n        if self.line_hit_map is None:\n            self.line_hit_map = {}\n        key = (source_file_id, line)\n        count_info = self.line_hit_map.get(key)\n        if count_info is None:\n            self.line_hit_map[key] = [event_count, subtree_event_count]\n        else:\n            count_info[0] += event_count\n            count_info[1] += subtree_event_count\n\n    def gen_sample_info(self, gen_addr_hit_map: bool) -> Dict[str, Any]:\n        result = {}\n        result['f'] = self.func_id\n        result['c'] = [self.sample_count, self.event_count, self.subtree_event_count]\n        if self.line_hit_map:\n            items = []\n            for key in self.line_hit_map:\n                count_info = self.line_hit_map[key]\n                item = {'f': key[0], 'l': key[1], 'e': count_info[0], 's': count_info[1]}\n                items.append(item)\n            result['s'] = items\n        if gen_addr_hit_map and self.addr_hit_map:\n            items = []\n            for addr in sorted(self.addr_hit_map):\n                count_info = self.addr_hit_map[addr]\n                items.append(\n                    {'a': hex_address_for_json(addr),\n                     'e': count_info[0],\n                     's': count_info[1]})\n            result['a'] = items\n        return result\n\n    def merge(self, function: FunctionScope):\n        self.sample_count += function.sample_count\n        self.event_count += function.event_count\n        self.subtree_event_count += function.subtree_event_count\n        self.addr_hit_map = self.__merge_hit_map(self.addr_hit_map, function.addr_hit_map)\n        self.line_hit_map = self.__merge_hit_map(self.line_hit_map, function.line_hit_map)\n\n    @staticmethod\n    def __merge_hit_map(map1: Optional[Dict[int, List[int]]],\n                        map2: Optional[Dict[int, List[int]]]) -> Optional[Dict[int, List[int]]]:\n        if not map1:\n            return map2\n        if not map2:\n            return map1\n        for key, value2 in map2.items():\n            value1 = map1.get(key)\n            if value1 is None:\n                map1[key] = value2\n            else:\n                value1[0] += value2[0]\n                value1[1] += value2[1]\n        return map1\n\n\nclass CallNode(object):\n\n    def __init__(self, func_id: int):\n        self.event_count = 0\n        self.subtree_event_count = 0\n        self.func_id = func_id\n        # map from func_id to CallNode\n        self.children: Dict[int, CallNode] = collections.OrderedDict()\n\n    def get_child(self, func_id: int) -> CallNode:\n        child = self.children.get(func_id)\n        if not child:\n            child = self.children[func_id] = CallNode(func_id)\n        return child\n\n    def update_subtree_event_count(self):\n        self.subtree_event_count = self.event_count\n        for child in self.children.values():\n            self.subtree_event_count += child.update_subtree_event_count()\n        return self.subtree_event_count\n\n    def cut_edge(self, min_limit: float, hit_func_ids: Set[int]):\n        hit_func_ids.add(self.func_id)\n        to_del_children = []\n        for key in self.children:\n            child = self.children[key]\n            if child.subtree_event_count < min_limit:\n                to_del_children.append(key)\n            else:\n                child.cut_edge(min_limit, hit_func_ids)\n        for key in to_del_children:\n            del self.children[key]\n\n    def gen_sample_info(self) -> Dict[str, Any]:\n        result = {}\n        result['e'] = self.event_count\n        result['s'] = self.subtree_event_count\n        result['f'] = self.func_id\n        result['c'] = [child.gen_sample_info() for child in self.children.values()]\n        return result\n\n    def merge(self, node: CallNode):\n        self.event_count += node.event_count\n        self.subtree_event_count += node.subtree_event_count\n        for key, child in node.children.items():\n            cur_child = self.children.get(key)\n            if cur_child is None:\n                self.children[key] = child\n            else:\n                cur_child.merge(child)\n\n\n@dataclass\nclass LibInfo:\n    name: str\n    build_id: str\n\n\nclass LibSet(object):\n    \"\"\" Collection of shared libraries used in perf.data. \"\"\"\n\n    def __init__(self):\n        self.lib_name_to_id: Dict[str, int] = {}\n        self.libs: List[LibInfo] = []\n\n    def get_lib_id(self, lib_name: str) -> Optional[int]:\n        return self.lib_name_to_id.get(lib_name)\n\n    def add_lib(self, lib_name: str, build_id: str) -> int:\n        \"\"\" Return lib_id of the newly added lib. \"\"\"\n        lib_id = len(self.libs)\n        self.libs.append(LibInfo(lib_name, build_id))\n        self.lib_name_to_id[lib_name] = lib_id\n        return lib_id\n\n    def get_lib(self, lib_id: int) -> LibInfo:\n        return self.libs[lib_id]\n\n\nclass Function(object):\n    \"\"\" Represent a function in a shared library. \"\"\"\n\n    def __init__(self, lib_id: int, func_name: str, func_id: int, start_addr: int, addr_len: int):\n        self.lib_id = lib_id\n        self.func_name = func_name\n        self.func_id = func_id\n        self.start_addr = start_addr\n        self.addr_len = addr_len\n        self.source_info = None\n        self.disassembly = None\n\n\nclass FunctionSet(object):\n    \"\"\" Collection of functions used in perf.data. \"\"\"\n\n    def __init__(self):\n        self.name_to_func: Dict[Tuple[int, str], Function] = {}\n        self.id_to_func: Dict[int, Function] = {}\n\n    def get_func_id(self, lib_id: int, symbol: SymbolStruct) -> int:\n        key = (lib_id, symbol.symbol_name)\n        function = self.name_to_func.get(key)\n        if function is None:\n            func_id = len(self.id_to_func)\n            function = Function(lib_id, symbol.symbol_name, func_id, symbol.symbol_addr,\n                                symbol.symbol_len)\n            self.name_to_func[key] = function\n            self.id_to_func[func_id] = function\n        return function.func_id\n\n    def trim_functions(self, left_func_ids: Set[int]):\n        \"\"\" Remove functions excepts those in left_func_ids. \"\"\"\n        for function in self.name_to_func.values():\n            if function.func_id not in left_func_ids:\n                del self.id_to_func[function.func_id]\n        # name_to_func will not be used.\n        self.name_to_func = None\n\n\nclass SourceFile(object):\n    \"\"\" A source file containing source code hit by samples. \"\"\"\n\n    def __init__(self, file_id: int, abstract_path: str):\n        self.file_id = file_id\n        self.abstract_path = abstract_path  # path reported by addr2line\n        self.real_path: Optional[str] = None  # file path in the file system\n        self.requested_lines: Optional[Set[int]] = set()\n        self.line_to_code: Dict[int, str] = {}  # map from line to code in that line.\n\n    def request_lines(self, start_line: int, end_line: int):\n        self.requested_lines |= set(range(start_line, end_line + 1))\n\n    def add_source_code(self, real_path: str):\n        self.real_path = real_path\n        with open(real_path, 'r') as f:\n            source_code = f.readlines()\n        max_line = len(source_code)\n        for line in self.requested_lines:\n            if line > 0 and line <= max_line:\n                self.line_to_code[line] = source_code[line - 1]\n        # requested_lines is no longer used.\n        self.requested_lines = None\n\n\nclass SourceFileSet(object):\n    \"\"\" Collection of source files. \"\"\"\n\n    def __init__(self):\n        self.path_to_source_files: Dict[str, SourceFile] = {}  # map from file path to SourceFile.\n\n    def get_source_file(self, file_path: str) -> SourceFile:\n        source_file = self.path_to_source_files.get(file_path)\n        if not source_file:\n            source_file = SourceFile(len(self.path_to_source_files), file_path)\n            self.path_to_source_files[file_path] = source_file\n        return source_file\n\n    def load_source_code(self, source_dirs: List[str]):\n        file_searcher = SourceFileSearcher(source_dirs)\n        for source_file in self.path_to_source_files.values():\n            real_path = file_searcher.get_real_path(source_file.abstract_path)\n            if real_path:\n                source_file.add_source_code(real_path)\n\n\nclass RecordData(object):\n\n    \"\"\"RecordData reads perf.data, and generates data used by report_html.js in json format.\n        All generated items are listed as below:\n            1. recordTime: string\n            2. machineType: string\n            3. androidVersion: string\n            4. recordCmdline: string\n            5. totalSamples: int\n            6. processNames: map from pid to processName.\n            7. threadNames: map from tid to threadName.\n            8. libList: an array of libNames, indexed by libId.\n            9. functionMap: map from functionId to funcData.\n                funcData = {\n                    l: libId\n                    f: functionName\n                    s: [sourceFileId, startLine, endLine] [optional]\n                    d: [(disassembly, addr)] [optional]\n                }\n\n            10.  sampleInfo = [eventInfo]\n                eventInfo = {\n                    eventName\n                    eventCount\n                    processes: [processInfo]\n                }\n                processInfo = {\n                    pid\n                    eventCount\n                    threads: [threadInfo]\n                }\n                threadInfo = {\n                    tid\n                    eventCount\n                    sampleCount\n                    libs: [libInfo],\n                    g: callGraph,\n                    rg: reverseCallgraph\n                }\n                libInfo = {\n                    libId,\n                    eventCount,\n                    functions: [funcInfo]\n                }\n                funcInfo = {\n                    f: functionId\n                    c: [sampleCount, eventCount, subTreeEventCount]\n                    s: [sourceCodeInfo] [optional]\n                    a: [addrInfo] (sorted by addrInfo.addr) [optional]\n                }\n                callGraph and reverseCallGraph are both of type CallNode.\n                callGraph shows how a function calls other functions.\n                reverseCallGraph shows how a function is called by other functions.\n                CallNode {\n                    e: selfEventCount\n                    s: subTreeEventCount\n                    f: functionId\n                    c: [CallNode] # children\n                }\n\n                sourceCodeInfo {\n                    f: sourceFileId\n                    l: line\n                    e: eventCount\n                    s: subtreeEventCount\n                }\n\n                addrInfo {\n                    a: addr\n                    e: eventCount\n                    s: subtreeEventCount\n                }\n\n            11. sourceFiles: an array of sourceFile, indexed by sourceFileId.\n                sourceFile {\n                    path\n                    code:  # a map from line to code for that line.\n                }\n    \"\"\"\n\n    def __init__(\n            self, binary_cache_path: Optional[str],\n            ndk_path: Optional[str],\n            build_addr_hit_map: bool, proguard_mapping_files: Optional[List[str]],\n            trace_offcpu: Optional[str]):\n        self.binary_cache_path = binary_cache_path\n        self.ndk_path = ndk_path\n        self.build_addr_hit_map = build_addr_hit_map\n        self.proguard_mapping_files = proguard_mapping_files\n        self.trace_offcpu = trace_offcpu\n        self.meta_info: Optional[Dict[str, str]] = None\n        self.cmdline: Optional[str] = None\n        self.arch: Optional[str] = None\n        self.events: Dict[str, EventScope] = {}\n        self.libs = LibSet()\n        self.functions = FunctionSet()\n        self.total_samples = 0\n        self.source_files = SourceFileSet()\n        self.gen_addr_hit_map_in_record_info = False\n        self.binary_finder = BinaryFinder(binary_cache_path, ReadElf(ndk_path))\n\n    def load_record_file(\n            self, record_file: str, show_art_frames: bool, sample_filter: Optional[str]):\n        lib = ReportLib()\n        lib.SetRecordFile(record_file)\n        # If not showing ip for unknown symbols, the percent of the unknown symbol may be\n        # accumulated to very big, and ranks first in the sample table.\n        lib.ShowIpForUnknownSymbol()\n        if show_art_frames:\n            lib.ShowArtFrames()\n        if self.binary_cache_path:\n            lib.SetSymfs(self.binary_cache_path)\n        for file_path in self.proguard_mapping_files or []:\n            lib.AddProguardMappingFile(file_path)\n        if self.trace_offcpu:\n            lib.SetTraceOffCpuMode(self.trace_offcpu)\n        if sample_filter:\n            lib.SetSampleFilter(sample_filter)\n        self.meta_info = lib.MetaInfo()\n        self.cmdline = lib.GetRecordCmd()\n        self.arch = lib.GetArch()\n        while True:\n            raw_sample = lib.GetNextSample()\n            if not raw_sample:\n                lib.Close()\n                break\n            raw_event = lib.GetEventOfCurrentSample()\n            symbol = lib.GetSymbolOfCurrentSample()\n            callchain = lib.GetCallChainOfCurrentSample()\n            event = self._get_event(raw_event.name)\n            self.total_samples += 1\n            event.sample_count += 1\n            event.event_count += raw_sample.period\n            process = event.get_process(raw_sample.pid)\n            process.event_count += raw_sample.period\n            thread = process.get_thread(raw_sample.tid, raw_sample.thread_comm)\n            thread.event_count += raw_sample.period\n            thread.sample_count += 1\n\n            lib_id = self.libs.get_lib_id(symbol.dso_name)\n            if lib_id is None:\n                lib_id = self.libs.add_lib(symbol.dso_name, lib.GetBuildIdForPath(symbol.dso_name))\n            func_id = self.functions.get_func_id(lib_id, symbol)\n            callstack = [(lib_id, func_id, symbol.vaddr_in_file)]\n            for i in range(callchain.nr):\n                symbol = callchain.entries[i].symbol\n                lib_id = self.libs.get_lib_id(symbol.dso_name)\n                if lib_id is None:\n                    lib_id = self.libs.add_lib(\n                        symbol.dso_name, lib.GetBuildIdForPath(symbol.dso_name))\n                func_id = self.functions.get_func_id(lib_id, symbol)\n                callstack.append((lib_id, func_id, symbol.vaddr_in_file))\n            if len(callstack) > MAX_CALLSTACK_LENGTH:\n                callstack = callstack[:MAX_CALLSTACK_LENGTH]\n            thread.add_callstack(raw_sample.period, callstack, self.build_addr_hit_map)\n\n        for event in self.events.values():\n            for thread in event.threads:\n                thread.update_subtree_event_count()\n\n    def aggregate_by_thread_name(self):\n        for event in self.events.values():\n            new_processes = {}  # from process name to ProcessScope\n            for process in event.processes.values():\n                cur_process = new_processes.get(process.name)\n                if cur_process is None:\n                    new_processes[process.name] = process\n                else:\n                    cur_process.merge_by_thread_name(process)\n            event.processes = {}\n            for process in new_processes.values():\n                event.processes[process.pid] = process\n\n    def limit_percents(self, min_func_percent: float, min_callchain_percent: float):\n        hit_func_ids: Set[int] = set()\n        for event in self.events.values():\n            min_limit = event.event_count * min_func_percent * 0.01\n            to_del_processes = []\n            for process in event.processes.values():\n                to_del_threads = []\n                for thread in process.threads.values():\n                    if thread.call_graph.subtree_event_count < min_limit:\n                        to_del_threads.append(thread.tid)\n                    else:\n                        thread.limit_percents(min_limit, min_callchain_percent, hit_func_ids)\n                for thread in to_del_threads:\n                    del process.threads[thread]\n                if not process.threads:\n                    to_del_processes.append(process.pid)\n            for process in to_del_processes:\n                del event.processes[process]\n        self.functions.trim_functions(hit_func_ids)\n\n    def _get_event(self, event_name: str) -> EventScope:\n        if event_name not in self.events:\n            self.events[event_name] = EventScope(event_name)\n        return self.events[event_name]\n\n    def add_source_code(self, source_dirs: List[str], filter_lib: Callable[[str], bool], jobs: int):\n        \"\"\" Collect source code information:\n            1. Find line ranges for each function in FunctionSet.\n            2. Find line for each addr in FunctionScope.addr_hit_map.\n            3. Collect needed source code in SourceFileSet.\n        \"\"\"\n        addr2line = Addr2Nearestline(self.ndk_path, self.binary_finder, False)\n        # Request line range for each function.\n        for function in self.functions.id_to_func.values():\n            if function.func_name == 'unknown':\n                continue\n            lib_info = self.libs.get_lib(function.lib_id)\n            if filter_lib(lib_info.name):\n                addr2line.add_addr(lib_info.name, lib_info.build_id,\n                                   function.start_addr, function.start_addr)\n                addr2line.add_addr(lib_info.name, lib_info.build_id, function.start_addr,\n                                   function.start_addr + function.addr_len - 1)\n        # Request line for each addr in FunctionScope.addr_hit_map.\n        for event in self.events.values():\n            for lib in event.libraries:\n                lib_info = self.libs.get_lib(lib.lib_id)\n                if filter_lib(lib_info.name):\n                    for function in lib.functions.values():\n                        func_addr = self.functions.id_to_func[function.func_id].start_addr\n                        for addr in function.addr_hit_map:\n                            addr2line.add_addr(lib_info.name, lib_info.build_id, func_addr, addr)\n        addr2line.convert_addrs_to_lines(jobs)\n\n        # Set line range for each function.\n        for function in self.functions.id_to_func.values():\n            if function.func_name == 'unknown':\n                continue\n            dso = addr2line.get_dso(self.libs.get_lib(function.lib_id).name)\n            if not dso:\n                continue\n            start_source = addr2line.get_addr_source(dso, function.start_addr)\n            end_source = addr2line.get_addr_source(dso, function.start_addr + function.addr_len - 1)\n            if not start_source or not end_source:\n                continue\n            start_file_path, start_line = start_source[-1]\n            end_file_path, end_line = end_source[-1]\n            if start_file_path != end_file_path or start_line > end_line:\n                continue\n            source_file = self.source_files.get_source_file(start_file_path)\n            source_file.request_lines(start_line, end_line)\n            function.source_info = (source_file.file_id, start_line, end_line)\n\n        # Build FunctionScope.line_hit_map.\n        for event in self.events.values():\n            for lib in event.libraries:\n                dso = addr2line.get_dso(self.libs.get_lib(lib.lib_id).name)\n                if not dso:\n                    continue\n                for function in lib.functions.values():\n                    for addr in function.addr_hit_map:\n                        source = addr2line.get_addr_source(dso, addr)\n                        if not source:\n                            continue\n                        for file_path, line in source:\n                            source_file = self.source_files.get_source_file(file_path)\n                            # Show [line - 5, line + 5] of the line hit by a sample.\n                            source_file.request_lines(line - 5, line + 5)\n                            count_info = function.addr_hit_map[addr]\n                            function.build_line_hit_map(source_file.file_id, line, count_info[0],\n                                                        count_info[1])\n\n        # Collect needed source code in SourceFileSet.\n        self.source_files.load_source_code(source_dirs)\n\n    def add_disassembly(self, filter_lib: Callable[[str], bool], jobs: int):\n        \"\"\" Collect disassembly information:\n            1. Use objdump to collect disassembly for each function in FunctionSet.\n            2. Set flag to dump addr_hit_map when generating record info.\n        \"\"\"\n        objdump = Objdump(self.ndk_path, self.binary_finder)\n        lib_functions: Dict[int, List[Function]] = collections.defaultdict(list)\n\n        for function in self.functions.id_to_func.values():\n            if function.func_name == 'unknown':\n                continue\n            lib_functions[function.lib_id].append(function)\n\n        with ThreadPoolExecutor(jobs) as executor:\n            for lib_id, functions in lib_functions.items():\n                lib = self.libs.get_lib(lib_id)\n                if not filter_lib(lib.name):\n                    continue\n                dso_info = objdump.get_dso_info(lib.name, lib.build_id)\n                if not dso_info:\n                    continue\n                logging.info('Disassemble %s' % dso_info[0])\n                futures: List[Future] = []\n                for function in functions:\n                    futures.append(\n                        executor.submit(objdump.disassemble_code, dso_info,\n                                        function.start_addr, function.addr_len))\n                for i in range(len(functions)):\n                    # Call future.result() to report exceptions raised in the executor.\n                    functions[i].disassembly = futures[i].result()\n        self.gen_addr_hit_map_in_record_info = True\n\n    def gen_record_info(self) -> Dict[str, Any]:\n        \"\"\" Return json data which will be used by report_html.js. \"\"\"\n        record_info = {}\n        timestamp = self.meta_info.get('timestamp')\n        if timestamp:\n            t = datetime.datetime.fromtimestamp(int(timestamp))\n        else:\n            t = datetime.datetime.now()\n        record_info['recordTime'] = t.strftime('%Y-%m-%d (%A) %H:%M:%S')\n\n        product_props = self.meta_info.get('product_props')\n        machine_type = self.arch\n        if product_props:\n            manufacturer, model, name = product_props.split(':')\n            machine_type = '%s (%s) by %s, arch %s' % (model, name, manufacturer, self.arch)\n        record_info['machineType'] = machine_type\n        record_info['androidVersion'] = self.meta_info.get('android_version', '')\n        record_info['androidBuildFingerprint'] = self.meta_info.get('android_build_fingerprint', '')\n        record_info['kernelVersion'] = self.meta_info.get('kernel_version', '')\n        record_info['recordCmdline'] = self.cmdline\n        record_info['totalSamples'] = self.total_samples\n        record_info['processNames'] = self._gen_process_names()\n        record_info['threadNames'] = self._gen_thread_names()\n        record_info['libList'] = self._gen_lib_list()\n        record_info['functionMap'] = self._gen_function_map()\n        record_info['sampleInfo'] = self._gen_sample_info()\n        record_info['sourceFiles'] = self._gen_source_files()\n        return record_info\n\n    def _gen_process_names(self) -> Dict[int, str]:\n        process_names: Dict[int, str] = {}\n        for event in self.events.values():\n            for process in event.processes.values():\n                process_names[process.pid] = process.name\n        return process_names\n\n    def _gen_thread_names(self) -> Dict[int, str]:\n        thread_names: Dict[int, str] = {}\n        for event in self.events.values():\n            for process in event.processes.values():\n                for thread in process.threads.values():\n                    thread_names[thread.tid] = thread.name\n        return thread_names\n\n    def _gen_lib_list(self) -> List[str]:\n        return [modify_text_for_html(lib.name) for lib in self.libs.libs]\n\n    def _gen_function_map(self) -> Dict[int, Any]:\n        func_map: Dict[int, Any] = {}\n        for func_id in sorted(self.functions.id_to_func):\n            function = self.functions.id_to_func[func_id]\n            func_data = {}\n            func_data['l'] = function.lib_id\n            func_data['f'] = modify_text_for_html(function.func_name)\n            if function.source_info:\n                func_data['s'] = function.source_info\n            if function.disassembly:\n                disassembly_list = []\n                for code, addr in function.disassembly:\n                    disassembly_list.append(\n                        [modify_text_for_html(code),\n                         hex_address_for_json(addr)])\n                func_data['d'] = disassembly_list\n            func_map[func_id] = func_data\n        return func_map\n\n    def _gen_sample_info(self) -> List[Dict[str, Any]]:\n        return [event.get_sample_info(self.gen_addr_hit_map_in_record_info)\n                for event in self.events.values()]\n\n    def _gen_source_files(self) -> List[Dict[str, Any]]:\n        source_files = sorted(self.source_files.path_to_source_files.values(),\n                              key=lambda x: x.file_id)\n        file_list = []\n        for source_file in source_files:\n            file_data = {}\n            if not source_file.real_path:\n                file_data['path'] = ''\n                file_data['code'] = {}\n            else:\n                file_data['path'] = source_file.real_path\n                code_map = {}\n                for line in source_file.line_to_code:\n                    code_map[line] = modify_text_for_html(source_file.line_to_code[line])\n                file_data['code'] = code_map\n            file_list.append(file_data)\n        return file_list\n\n\nURLS = {\n    'jquery': 'https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js',\n    'bootstrap4-css': 'https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css',\n    'bootstrap4-popper':\n        'https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js',\n    'bootstrap4': 'https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js',\n    'dataTable': 'https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js',\n    'dataTable-bootstrap4': 'https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js',\n    'dataTable-css': 'https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css',\n    'gstatic-charts': 'https://www.gstatic.com/charts/loader.js',\n}\n\n\nclass ReportGenerator(object):\n\n    def __init__(self, html_path: Union[Path, str]):\n        self.hw = HtmlWriter(html_path)\n        self.hw.open_tag('html')\n        self.hw.open_tag('head')\n        for css in ['bootstrap4-css', 'dataTable-css']:\n            self.hw.open_tag('link', rel='stylesheet', type='text/css', href=URLS[css]).close_tag()\n        for js in ['jquery', 'bootstrap4-popper', 'bootstrap4', 'dataTable', 'dataTable-bootstrap4',\n                   'gstatic-charts']:\n            self.hw.open_tag('script', src=URLS[js]).close_tag()\n\n        self.hw.open_tag('script').add(\n            \"google.charts.load('current', {'packages': ['corechart', 'table']});\").close_tag()\n        self.hw.open_tag('style', type='text/css').add(\"\"\"\n            .colForLine { width: 50px; }\n            .colForCount { width: 100px; }\n            .tableCell { font-size: 17px; }\n            .boldTableCell { font-weight: bold; font-size: 17px; }\n            \"\"\").close_tag()\n        self.hw.close_tag('head')\n        self.hw.open_tag('body')\n\n    def write_content_div(self):\n        self.hw.open_tag('div', id='report_content').close_tag()\n\n    def write_record_data(self, record_data: Dict[str, Any]):\n        self.hw.open_tag('script', id='record_data', type='application/json')\n        self.hw.add(json.dumps(record_data))\n        self.hw.close_tag()\n\n    def write_script(self):\n        self.hw.open_tag('script').add_file('report_html.js').close_tag()\n\n    def finish(self):\n        self.hw.close_tag('body')\n        self.hw.close_tag('html')\n        self.hw.close()\n\n\ndef get_args() -> argparse.Namespace:\n    parser = BaseArgumentParser(description='report profiling data')\n    parser.add_argument('-i', '--record_file', nargs='+', default=['perf.data'], help=\"\"\"\n                        Set profiling data file to report.\"\"\")\n    parser.add_argument('-o', '--report_path', default='report.html', help='Set output html file')\n    parser.add_argument('--min_func_percent', default=0.01, type=float, help=\"\"\"\n                        Set min percentage of functions shown in the report.\n                        For example, when set to 0.01, only functions taking >= 0.01%% of total\n                        event count are collected in the report.\"\"\")\n    parser.add_argument('--min_callchain_percent', default=0.01, type=float, help=\"\"\"\n                        Set min percentage of callchains shown in the report.\n                        It is used to limit nodes shown in the function flamegraph. For example,\n                        when set to 0.01, only callchains taking >= 0.01%% of the event count of\n                        the starting function are collected in the report.\"\"\")\n    parser.add_argument('--add_source_code', action='store_true', help='Add source code.')\n    parser.add_argument('--source_dirs', nargs='+', help='Source code directories.')\n    parser.add_argument('--add_disassembly', action='store_true', help='Add disassembled code.')\n    parser.add_argument('--binary_filter', nargs='+', help=\"\"\"Annotate source code and disassembly\n                        only for selected binaries.\"\"\")\n    parser.add_argument(\n        '-j', '--jobs', type=int, default=os.cpu_count(),\n        help='Use multithreading to speed up disassembly and source code annotation.')\n    parser.add_argument('--ndk_path', nargs=1, help='Find tools in the ndk path.')\n    parser.add_argument('--no_browser', action='store_true', help=\"Don't open report in browser.\")\n    parser.add_argument('--show_art_frames', action='store_true',\n                        help='Show frames of internal methods in the ART Java interpreter.')\n    parser.add_argument('--aggregate-by-thread-name', action='store_true', help=\"\"\"aggregate\n                        samples by thread name instead of thread id. This is useful for\n                        showing multiple perf.data generated for the same app.\"\"\")\n    parser.add_argument(\n        '--proguard-mapping-file', nargs='+',\n        help='Add proguard mapping file to de-obfuscate symbols')\n    parser.add_trace_offcpu_option()\n    parser.add_sample_filter_options()\n    return parser.parse_args()\n\n\ndef main():\n    sys.setrecursionlimit(MAX_CALLSTACK_LENGTH * 2 + 50)\n    args = get_args()\n\n    # 1. Process args.\n    binary_cache_path = 'binary_cache'\n    if not os.path.isdir(binary_cache_path):\n        if args.add_source_code or args.add_disassembly:\n            log_exit(\"\"\"binary_cache/ doesn't exist. Can't add source code or disassembled code\n                        without collected binaries. Please run binary_cache_builder.py to\n                        collect binaries for current profiling data, or run app_profiler.py\n                        without -nb option.\"\"\")\n        binary_cache_path = None\n\n    if args.add_source_code and not args.source_dirs:\n        log_exit('--source_dirs is needed to add source code.')\n    build_addr_hit_map = args.add_source_code or args.add_disassembly\n    ndk_path = None if not args.ndk_path else args.ndk_path[0]\n    if args.jobs < 1:\n        log_exit('Invalid --jobs option.')\n\n    # 2. Produce record data.\n    record_data = RecordData(binary_cache_path, ndk_path, build_addr_hit_map,\n                             args.proguard_mapping_file, args.trace_offcpu)\n    for record_file in args.record_file:\n        record_data.load_record_file(record_file, args.show_art_frames, args.sample_filter)\n    if args.aggregate_by_thread_name:\n        record_data.aggregate_by_thread_name()\n    record_data.limit_percents(args.min_func_percent, args.min_callchain_percent)\n\n    def filter_lib(lib_name: str) -> bool:\n        if not args.binary_filter:\n            return True\n        for binary in args.binary_filter:\n            if binary in lib_name:\n                return True\n        return False\n    if args.add_source_code:\n        record_data.add_source_code(args.source_dirs, filter_lib, args.jobs)\n    if args.add_disassembly:\n        record_data.add_disassembly(filter_lib, args.jobs)\n\n    # 3. Generate report html.\n    report_generator = ReportGenerator(args.report_path)\n    report_generator.write_script()\n    report_generator.write_content_div()\n    report_generator.write_record_data(record_data.gen_record_info())\n    report_generator.finish()\n\n    if not args.no_browser:\n        open_report_in_browser(args.report_path)\n    logging.info(\"Report generated at '%s'.\" % args.report_path)\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "simpleperf/report_sample.py",
    "content": "#!/usr/bin/env python3\n#\n# Copyright (C) 2016 The Android Open Source Project\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\"\"\"report_sample.py: report samples in the same format as `perf script`.\n\"\"\"\n\nfrom simpleperf_report_lib import ReportLib\nfrom simpleperf_utils import BaseArgumentParser, flatten_arg_list\nfrom typing import List, Set, Optional\n\n\ndef report_sample(\n        record_file: str,\n        symfs_dir: str,\n        kallsyms_file: str,\n        show_tracing_data: bool,\n        proguard_mapping_file: List[str],\n        header: bool,\n        comm_filter: Set[str],\n        trace_offcpu: Optional[str],\n        sample_filter: Optional[str]):\n    \"\"\" read record_file, and print each sample\"\"\"\n    lib = ReportLib()\n\n    lib.ShowIpForUnknownSymbol()\n    for file_path in proguard_mapping_file:\n        lib.AddProguardMappingFile(file_path)\n    if symfs_dir is not None:\n        lib.SetSymfs(symfs_dir)\n    if record_file is not None:\n        lib.SetRecordFile(record_file)\n    if kallsyms_file is not None:\n        lib.SetKallsymsFile(kallsyms_file)\n    if trace_offcpu:\n        lib.SetTraceOffCpuMode(trace_offcpu)\n    if sample_filter:\n        lib.SetSampleFilter(sample_filter)\n\n    if header:\n        print(\"# ========\")\n        print(\"# cmdline : %s\" % lib.GetRecordCmd())\n        print(\"# arch : %s\" % lib.GetArch())\n        for k, v in lib.MetaInfo().items():\n            print('# %s : %s' % (k, v.replace('\\n', ' ')))\n        print(\"# ========\")\n        print(\"#\")\n\n    while True:\n        sample = lib.GetNextSample()\n        if sample is None:\n            lib.Close()\n            break\n        if comm_filter:\n            if sample.thread_comm not in comm_filter:\n                continue\n        event = lib.GetEventOfCurrentSample()\n        symbol = lib.GetSymbolOfCurrentSample()\n        callchain = lib.GetCallChainOfCurrentSample()\n\n        sec = sample.time // 1000000000\n        usec = (sample.time - sec * 1000000000) // 1000\n        print('%s\\t%d/%d [%03d] %d.%06d: %d %s:' % (sample.thread_comm,\n                                                    sample.pid, sample.tid, sample.cpu, sec,\n                                                    usec, sample.period, event.name))\n        print('\\t%16x %s (%s)' % (sample.ip, symbol.symbol_name, symbol.dso_name))\n        for i in range(callchain.nr):\n            entry = callchain.entries[i]\n            print('\\t%16x %s (%s)' % (entry.ip, entry.symbol.symbol_name, entry.symbol.dso_name))\n        if show_tracing_data:\n            data = lib.GetTracingDataOfCurrentSample()\n            if data:\n                print('\\ttracing data:')\n                for key, value in data.items():\n                    print('\\t\\t%s : %s' % (key, value))\n        print('')\n\n\ndef main():\n    parser = BaseArgumentParser(description='Report samples in perf.data.')\n    parser.add_argument('--symfs',\n                        help='Set the path to find binaries with symbols and debug info.')\n    parser.add_argument('--kallsyms', help='Set the path to find kernel symbols.')\n    parser.add_argument('-i', '--record_file', nargs='?', default='perf.data',\n                        help='Default is perf.data.')\n    parser.add_argument('--show_tracing_data', action='store_true', help='print tracing data.')\n    parser.add_argument(\n        '--proguard-mapping-file', nargs='+',\n        help='Add proguard mapping file to de-obfuscate symbols',\n        default=[])\n    parser.add_argument('--header', action='store_true',\n                        help='Show metadata header, like perf script --header')\n    parser.add_argument('--comm', nargs='+', action='append', help=\"\"\"\n        Use samples only in threads with selected names.\"\"\")\n    parser.add_trace_offcpu_option()\n    parser.add_sample_filter_options()\n    args = parser.parse_args()\n    report_sample(\n        record_file=args.record_file,\n        symfs_dir=args.symfs,\n        kallsyms_file=args.kallsyms,\n        show_tracing_data=args.show_tracing_data,\n        proguard_mapping_file=args.proguard_mapping_file,\n        header=args.header,\n        comm_filter=set(flatten_arg_list(args.comm)),\n        trace_offcpu=args.trace_offcpu,\n        sample_filter=args.sample_filter)\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "simpleperf/run.bat",
    "content": "set mydate=%date:/=%\r\nset DATE=%mydate: =_%\r\nset dt=%TIME:~0,2%_%TIME:~3,2%_%TIME:~6,2%\r\nset TIMESTAMP=%dt: =0%\r\nset PKG_NAME=com.sina.weibo\r\nIF not \"%~1\"==\"\" set PKG_NAME=%~1\r\ncall python %~dp0\\app_profiler.py -p %PKG_NAME% -r=\"-e task-clock:u -f 100000 -m 4096 -g --duration 1\" --ndk_path %~dp0\\ndk\r\ncall python %~dp0\\report_html.py --ndk_path %~dp0\\ndk --report_path %~dp0\\%PKG_NAME%_%DATE%_%TIMESTAMP%.html\r\n@REM call python %~dp0\\report_html.py --ndk_path %~dp0\\ndk --report_path %~dp0\\%PKG_NAME%_%DATE%_%TIMESTAMP%.html --add_disassembly --binary_filter libUE4.so"
  },
  {
    "path": "simpleperf/run_simpleperf_on_device.py",
    "content": "#!/usr/bin/env python3\n#\n# Copyright (C) 2017 The Android Open Source Project\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\"\"\"run_simpleperf_on_device.py:\n    It downloads simpleperf to /data/local/tmp on device, and run it with all given arguments.\n    It saves the time downloading simpleperf and using `adb shell` directly.\n\"\"\"\nimport subprocess\nimport sys\nfrom simpleperf_utils import AdbHelper, get_target_binary_path, Log\n\n\ndef main():\n    Log.init()\n    adb = AdbHelper()\n    device_arch = adb.get_device_arch()\n    simpleperf_binary = get_target_binary_path(device_arch, 'simpleperf')\n    adb.check_run(['push', simpleperf_binary, '/data/local/tmp'])\n    adb.check_run(['shell', 'chmod', 'a+x', '/data/local/tmp/simpleperf'])\n    shell_cmd = 'cd /data/local/tmp && ./simpleperf ' + ' '.join(sys.argv[1:])\n    sys.exit(subprocess.call([adb.adb_path, 'shell', shell_cmd]))\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "simpleperf/run_simpleperf_without_usb_connection.py",
    "content": "#!/usr/bin/env python3\n#\n# Copyright (C) 2018 The Android Open Source Project\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\"\"\"\n    Support profiling without usb connection in below steps:\n    1. With usb connection, start simpleperf recording.\n    2. Unplug the usb cable and play the app you want to profile, while the process of\n       simpleperf keeps running and collecting samples.\n    3. Replug the usb cable, stop simpleperf recording and pull recording file on host.\n\n    Note that recording is stopped once the app is killed. So if you restart the app\n    during profiling time, simpleperf only records the first running.\n\"\"\"\n\nimport logging\nimport subprocess\nimport sys\nimport time\n\nfrom simpleperf_utils import AdbHelper, BaseArgumentParser, get_target_binary_path\n\n\ndef start_recording(args):\n    adb = AdbHelper()\n    device_arch = adb.get_device_arch()\n    simpleperf_binary = get_target_binary_path(device_arch, 'simpleperf')\n    adb.check_run(['push', simpleperf_binary, '/data/local/tmp'])\n    adb.check_run(['shell', 'chmod', 'a+x', '/data/local/tmp/simpleperf'])\n    adb.check_run(['shell', 'rm', '-rf', '/data/local/tmp/perf.data',\n                   '/data/local/tmp/simpleperf_output'])\n    shell_cmd = 'cd /data/local/tmp && nohup ./simpleperf record ' + args.record_options\n    if args.app:\n        shell_cmd += ' --app ' + args.app\n    if args.size_limit:\n        shell_cmd += ' --size-limit ' + args.size_limit\n    shell_cmd += ' >/data/local/tmp/simpleperf_output 2>&1'\n    print('shell_cmd: %s' % shell_cmd)\n    subproc = subprocess.Popen([adb.adb_path, 'shell', shell_cmd])\n    # Wait 2 seconds to see if the simpleperf command fails to start.\n    time.sleep(2)\n    if subproc.poll() is None:\n        print('Simpleperf recording has started. Please unplug the usb cable and run the app.')\n        print('After that, run `%s stop` to get recording result.' % sys.argv[0])\n    else:\n        adb.run(['shell', 'cat', '/data/local/tmp/simpleperf_output'])\n        sys.exit(subproc.returncode)\n\n\ndef stop_recording(args):\n    adb = AdbHelper()\n    result = adb.run(['shell', 'pidof', 'simpleperf'])\n    if not result:\n        logging.warning('No simpleperf process on device. The recording has ended.')\n    else:\n        adb.run(['shell', 'pkill', '-l', '2', 'simpleperf'])\n        print('Waiting for simpleperf process to finish...')\n        while adb.run(['shell', 'pidof', 'simpleperf']):\n            time.sleep(1)\n    adb.run(['shell', 'cat', '/data/local/tmp/simpleperf_output'])\n    adb.check_run(['pull', '/data/local/tmp/perf.data', args.perf_data_path])\n    print('The recording data has been collected in %s.' % args.perf_data_path)\n\n\ndef main():\n    parser = BaseArgumentParser(description=__doc__)\n    subparsers = parser.add_subparsers()\n    start_parser = subparsers.add_parser('start', help='Start recording.')\n    start_parser.add_argument('-r', '--record_options',\n                              default='-e task-clock:u -g',\n                              help=\"\"\"Set options for `simpleperf record` command.\n                                      Default is `-e task-clock:u -g`.\"\"\")\n    start_parser.add_argument('-p', '--app', help=\"\"\"Profile an Android app, given the package\n                              name. Like `-p com.example.android.myapp`.\"\"\")\n    start_parser.add_argument('--size_limit', type=str,\n                              help=\"\"\"Stop profiling when recording data reaches\n                                      [size_limit][K|M|G] bytes. Like `--size_limit 1M`.\"\"\")\n    start_parser.set_defaults(func=start_recording)\n    stop_parser = subparsers.add_parser('stop', help='Stop recording.')\n    stop_parser.add_argument('-o', '--perf_data_path', default='perf.data', help=\"\"\"The path to\n                             store profiling data on host. Default is perf.data.\"\"\")\n    stop_parser.set_defaults(func=stop_recording)\n    args = parser.parse_args()\n    args.func(args)\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "simpleperf/simpleperf-help-report.txt",
    "content": "\r\nd:\\svn_pool\\perf-doctor\\simpleperf>d:\\svn_pool\\perf-doctor\\simpleperf\\\\bin\\windows\\x86_64\\simpleperf.exe help report \r\nUsage: simpleperf report [options]\r\nThe default options are: -i perf.data --sort comm,pid,tid,dso,symbol.\r\n-b    Use the branch-to addresses in sampled take branches instead of the\r\n      instruction addresses. Only valid for perf.data recorded with -b/-j\r\n      option.\r\n--children    Print the overhead accumulated by appearing in the callchain.\r\n              In the report, Children column shows overhead for a symbol and functions called\r\n              by the symbol, while Self column shows overhead for the symbol itself.\r\n--csv                     Report in csv format.\r\n--csv-separator <sep>     Set separator for csv columns. Default is ','.\r\n--full-callgraph  Print full call graph. Used with -g option. By default,\r\n                  brief call graph is printed.\r\n-g [callee|caller]    Print call graph. If callee mode is used, the graph\r\n                      shows how functions are called from others. Otherwise,\r\n                      the graph shows how functions call others.\r\n                      Default is caller mode.\r\n-i <file>  Specify path of record file, default is perf.data.\r\n--kallsyms <file>     Set the file to read kernel symbols.\r\n--max-stack <frames>  Set max stack frames shown when printing call graph.\r\n-n         Print the sample count for each item.\r\n--no-demangle         Don't demangle symbol names.\r\n--no-show-ip          Don't show vaddr in file for unknown symbols.\r\n-o report_file_name   Set report file name, default is stdout.\r\n--percent-limit <percent>  Set min percentage in report entries and call graphs.\r\n--print-event-count   Print event counts for each item. Additional events can be added by\r\n                      --add-counter in record cmd.\r\n--raw-period          Report period count instead of period percentage.\r\n--sort key1,key2,...  Select keys used to group samples into report entries. Samples having\r\n                      the same key values are aggregated into one report entry. Each report\r\n                      entry is printed in one row, having columns to show key values.\r\n                      Possible keys include:\r\n                        pid             -- process id\r\n                        tid             -- thread id\r\n                        comm            -- thread name (can be changed during\r\n                                           the lifetime of a thread)\r\n                        dso             -- shared library\r\n                        symbol          -- function name in the shared library\r\n                        vaddr_in_file   -- virtual address in the shared\r\n                                           library\r\n                      Keys can only be used with -b option:\r\n                        dso_from        -- shared library branched from\r\n                        dso_to          -- shared library branched to\r\n                        symbol_from     -- name of function branched from\r\n                        symbol_to       -- name of function branched to\r\n                      The default sort keys are:\r\n                        comm,pid,tid,dso,symbol\r\n--symfs <dir>         Look for files with symbols relative to this directory.\r\n--vmlinux <file>      Parse kernel symbols from <file>.\r\n\r\nSample filter options:\r\n--comms comm1,comm2,...          Report only for threads with selected names.\r\n--cpu   cpu_item1,cpu_item2,...  Report samples on the selected cpus. cpu_item can be cpu\r\n                                 number like 1, or cpu range like 0-3.\r\n--dsos dso1,dso2,...             Report only for selected dsos.\r\n--pids pid1,pid2,...             Same as '--include-pid'.\r\n--symbols symbol1;symbol2;...    Report only for selected symbols.\r\n--tids tid1,tid2,...             Same as '--include-tid'.\r\n--exclude-pid pid1,pid2,...   Exclude samples for selected processes.\r\n--exclude-tid tid1,tid2,...   Exclude samples for selected threads.\r\n--exclude-process-name process_name_regex   Exclude samples for processes with name\r\n                                            containing the regular expression.\r\n--exclude-thread-name thread_name_regex     Exclude samples for threads with name containing\r\n                                            the regular expression.\r\n--include-pid pid1,pid2,...   Include samples for selected processes.\r\n--include-tid tid1,tid2,...   Include samples for selected threads.\r\n--include-process-name process_name_regex   Include samples for processes with name\r\n                                            containing the regular expression.\r\n--include-thread-name thread_name_regex     Include samples for threads with name containing\r\n                                            the regular expression.\r\n--filter-file <file>          Use filter file to filter samples based on timestamps. The\r\n                              file format is in doc/sampler_filter.md.\r\n\r\n"
  },
  {
    "path": "simpleperf/simpleperf.bat",
    "content": "%~dp0\\bin\\windows\\x86_64\\simpleperf.exe %*"
  },
  {
    "path": "simpleperf/simpleperf_report_lib.py",
    "content": "#!/usr/bin/env python3\n#\n# Copyright (C) 2016 The Android Open Source Project\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\"\"\"simpleperf_report_lib.py: a python wrapper of libsimpleperf_report.so.\n   Used to access samples in perf.data.\n\n\"\"\"\n\nimport collections\nimport ctypes as ct\nfrom pathlib import Path\nimport struct\nfrom typing import Any, Dict, List, Optional, Union\n\nfrom simpleperf_utils import bytes_to_str, get_host_binary_path, is_windows, str_to_bytes\n\n\ndef _is_null(p: Optional[ct._Pointer]) -> bool:\n    if p:\n        return False\n    return ct.cast(p, ct.c_void_p).value is None\n\n\ndef _char_pt(s: str) -> bytes:\n    return str_to_bytes(s)\n\n\ndef _char_pt_to_str(char_pt: ct.c_char_p) -> str:\n    return bytes_to_str(char_pt)\n\n\ndef _check(cond: bool, failmsg: str):\n    if not cond:\n        raise RuntimeError(failmsg)\n\n\nclass SampleStruct(ct.Structure):\n    \"\"\" Instance of a sample in perf.data.\n        ip: the program counter of the thread generating the sample.\n        pid: process id (or thread group id) of the thread generating the sample.\n        tid: thread id.\n        thread_comm: thread name.\n        time: time at which the sample was generated. The value is in nanoseconds.\n              The clock is decided by the --clockid option in `simpleperf record`.\n        in_kernel: whether the instruction is in kernel space or user space.\n        cpu: the cpu generating the sample.\n        period: count of events have happened since last sample. For example, if we use\n             -e cpu-cycles, it means how many cpu-cycles have happened.\n             If we use -e cpu-clock, it means how many nanoseconds have passed.\n    \"\"\"\n    _fields_ = [('ip', ct.c_uint64),\n                ('pid', ct.c_uint32),\n                ('tid', ct.c_uint32),\n                ('_thread_comm', ct.c_char_p),\n                ('time', ct.c_uint64),\n                ('_in_kernel', ct.c_uint32),\n                ('cpu', ct.c_uint32),\n                ('period', ct.c_uint64)]\n\n    @property\n    def thread_comm(self) -> str:\n        return _char_pt_to_str(self._thread_comm)\n\n    @property\n    def in_kernel(self) -> bool:\n        return bool(self._in_kernel)\n\n\nclass TracingFieldFormatStruct(ct.Structure):\n    \"\"\"Format of a tracing field.\n       name: name of the field.\n       offset: offset of the field in tracing data.\n       elem_size: size of the element type.\n       elem_count: the number of elements in this field, more than one if the field is an array.\n       is_signed: whether the element type is signed or unsigned.\n       is_dynamic: whether the element is a dynamic string.\n    \"\"\"\n    _fields_ = [('_name', ct.c_char_p),\n                ('offset', ct.c_uint32),\n                ('elem_size', ct.c_uint32),\n                ('elem_count', ct.c_uint32),\n                ('is_signed', ct.c_uint32),\n                ('is_dynamic', ct.c_uint32)]\n\n    _unpack_key_dict = {1: 'b', 2: 'h', 4: 'i', 8: 'q'}\n\n    @property\n    def name(self) -> str:\n        return _char_pt_to_str(self._name)\n\n    def parse_value(self, data: ct.c_char_p) -> Union[str, bytes, List[bytes]]:\n        \"\"\" Parse value of a field in a tracepoint event.\n            The return value depends on the type of the field, and can be an int value, a string,\n            an array of int values, etc. If the type can't be parsed, return a byte array or an\n            array of byte arrays.\n        \"\"\"\n        if self.is_dynamic:\n            offset, max_len = struct.unpack('<HH', data[self.offset:self.offset + 4])\n            length = 0\n            while length < max_len and bytes_to_str(data[offset + length]) != '\\x00':\n                length += 1\n            return bytes_to_str(data[offset: offset + length])\n\n        if self.elem_count > 1 and self.elem_size == 1:\n            # Probably the field is a string.\n            # Don't use self.is_signed, which has different values on x86 and arm.\n            length = 0\n            while length < self.elem_count and bytes_to_str(data[self.offset + length]) != '\\x00':\n                length += 1\n            return bytes_to_str(data[self.offset: self.offset + length])\n        unpack_key = self._unpack_key_dict.get(self.elem_size)\n        if unpack_key:\n            if not self.is_signed:\n                unpack_key = unpack_key.upper()\n            value = struct.unpack('%d%s' % (self.elem_count, unpack_key),\n                                  data[self.offset:self.offset + self.elem_count * self.elem_size])\n        else:\n            # Since we don't know the element type, just return the bytes.\n            value = []\n            offset = self.offset\n            for _ in range(self.elem_count):\n                value.append(data[offset: offset + self.elem_size])\n                offset += self.elem_size\n        if self.elem_count == 1:\n            value = value[0]\n        return value\n\n\nclass TracingDataFormatStruct(ct.Structure):\n    \"\"\"Format of tracing data of a tracepoint event, like\n       https://www.kernel.org/doc/html/latest/trace/events.html#event-formats.\n       size: total size of all fields in the tracing data.\n       field_count: the number of fields.\n       fields: an array of fields.\n    \"\"\"\n    _fields_ = [('size', ct.c_uint32),\n                ('field_count', ct.c_uint32),\n                ('fields', ct.POINTER(TracingFieldFormatStruct))]\n\n\nclass EventStruct(ct.Structure):\n    \"\"\"Event type of a sample.\n       name: name of the event type.\n       tracing_data_format: only available when it is a tracepoint event.\n    \"\"\"\n    _fields_ = [('_name', ct.c_char_p),\n                ('tracing_data_format', TracingDataFormatStruct)]\n\n    @property\n    def name(self) -> str:\n        return _char_pt_to_str(self._name)\n\n\nclass MappingStruct(ct.Structure):\n    \"\"\" A mapping area in the monitored threads, like the content in /proc/<pid>/maps.\n        start: start addr in memory.\n        end: end addr in memory.\n        pgoff: offset in the mapped shared library.\n    \"\"\"\n    _fields_ = [('start', ct.c_uint64),\n                ('end', ct.c_uint64),\n                ('pgoff', ct.c_uint64)]\n\n\nclass SymbolStruct(ct.Structure):\n    \"\"\" Symbol info of the instruction hit by a sample or a callchain entry of a sample.\n        dso_name: path of the shared library containing the instruction.\n        vaddr_in_file: virtual address of the instruction in the shared library.\n        symbol_name: name of the function containing the instruction.\n        symbol_addr: start addr of the function containing the instruction.\n        symbol_len: length of the function in the shared library.\n        mapping: the mapping area hit by the instruction.\n    \"\"\"\n    _fields_ = [('_dso_name', ct.c_char_p),\n                ('vaddr_in_file', ct.c_uint64),\n                ('_symbol_name', ct.c_char_p),\n                ('symbol_addr', ct.c_uint64),\n                ('symbol_len', ct.c_uint64),\n                ('mapping', ct.POINTER(MappingStruct))]\n\n    @property\n    def dso_name(self) -> str:\n        return _char_pt_to_str(self._dso_name)\n\n    @property\n    def symbol_name(self) -> str:\n        return _char_pt_to_str(self._symbol_name)\n\n\nclass CallChainEntryStructure(ct.Structure):\n    \"\"\" A callchain entry of a sample.\n        ip: the address of the instruction of the callchain entry.\n        symbol: symbol info of the callchain entry.\n    \"\"\"\n    _fields_ = [('ip', ct.c_uint64),\n                ('symbol', SymbolStruct)]\n\n\nclass CallChainStructure(ct.Structure):\n    \"\"\" Callchain info of a sample.\n        nr: number of entries in the callchain.\n        entries: a pointer to an array of CallChainEntryStructure.\n\n        For example, if a sample is generated when a thread is running function C\n        with callchain function A -> function B -> function C.\n        Then nr = 2, and entries = [function B, function A].\n    \"\"\"\n    _fields_ = [('nr', ct.c_uint32),\n                ('entries', ct.POINTER(CallChainEntryStructure))]\n\n\nclass FeatureSectionStructure(ct.Structure):\n    \"\"\" A feature section in perf.data to store information like record cmd, device arch, etc.\n        data: a pointer to a buffer storing the section data.\n        data_size: data size in bytes.\n    \"\"\"\n    _fields_ = [('data', ct.POINTER(ct.c_char)),\n                ('data_size', ct.c_uint32)]\n\n\nclass ReportLibStructure(ct.Structure):\n    _fields_ = []\n\n\n# pylint: disable=invalid-name\nclass ReportLib(object):\n\n    def __init__(self, native_lib_path: Optional[str] = None):\n        if native_lib_path is None:\n            native_lib_path = self._get_native_lib()\n\n        self._load_dependent_lib()\n        self._lib = ct.CDLL(native_lib_path)\n        self._CreateReportLibFunc = self._lib.CreateReportLib\n        self._CreateReportLibFunc.restype = ct.POINTER(ReportLibStructure)\n        self._DestroyReportLibFunc = self._lib.DestroyReportLib\n        self._SetLogSeverityFunc = self._lib.SetLogSeverity\n        self._SetSymfsFunc = self._lib.SetSymfs\n        self._SetRecordFileFunc = self._lib.SetRecordFile\n        self._SetKallsymsFileFunc = self._lib.SetKallsymsFile\n        self._ShowIpForUnknownSymbolFunc = self._lib.ShowIpForUnknownSymbol\n        self._ShowArtFramesFunc = self._lib.ShowArtFrames\n        self._MergeJavaMethodsFunc = self._lib.MergeJavaMethods\n        self._AddProguardMappingFileFunc = self._lib.AddProguardMappingFile\n        self._AddProguardMappingFileFunc.restype = ct.c_bool\n        self._GetSupportedTraceOffCpuModesFunc = self._lib.GetSupportedTraceOffCpuModes\n        self._GetSupportedTraceOffCpuModesFunc.restype = ct.c_char_p\n        self._SetTraceOffCpuModeFunc = self._lib.SetTraceOffCpuMode\n        self._SetTraceOffCpuModeFunc.restype = ct.c_bool\n        self._SetSampleFilterFunc = self._lib.SetSampleFilter\n        self._SetSampleFilterFunc.restype = ct.c_bool\n        self._GetNextSampleFunc = self._lib.GetNextSample\n        self._GetNextSampleFunc.restype = ct.POINTER(SampleStruct)\n        self._GetEventOfCurrentSampleFunc = self._lib.GetEventOfCurrentSample\n        self._GetEventOfCurrentSampleFunc.restype = ct.POINTER(EventStruct)\n        self._GetSymbolOfCurrentSampleFunc = self._lib.GetSymbolOfCurrentSample\n        self._GetSymbolOfCurrentSampleFunc.restype = ct.POINTER(SymbolStruct)\n        self._GetCallChainOfCurrentSampleFunc = self._lib.GetCallChainOfCurrentSample\n        self._GetCallChainOfCurrentSampleFunc.restype = ct.POINTER(CallChainStructure)\n        self._GetTracingDataOfCurrentSampleFunc = self._lib.GetTracingDataOfCurrentSample\n        self._GetTracingDataOfCurrentSampleFunc.restype = ct.POINTER(ct.c_char)\n        self._GetBuildIdForPathFunc = self._lib.GetBuildIdForPath\n        self._GetBuildIdForPathFunc.restype = ct.c_char_p\n        self._GetFeatureSection = self._lib.GetFeatureSection\n        self._GetFeatureSection.restype = ct.POINTER(FeatureSectionStructure)\n        self._instance = self._CreateReportLibFunc()\n        assert not _is_null(self._instance)\n\n        self.meta_info: Optional[Dict[str, str]] = None\n        self.current_sample: Optional[SampleStruct] = None\n        self.record_cmd: Optional[str] = None\n\n    def _get_native_lib(self) -> str:\n        return get_host_binary_path('libsimpleperf_report.so')\n\n    def _load_dependent_lib(self):\n        # As the windows dll is built with mingw we need to load 'libwinpthread-1.dll'.\n        if is_windows():\n            self._libwinpthread = ct.CDLL(get_host_binary_path('libwinpthread-1.dll'))\n\n    def Close(self):\n        if self._instance:\n            self._DestroyReportLibFunc(self._instance)\n            self._instance = None\n\n    def SetLogSeverity(self, log_level: str = 'info'):\n        \"\"\" Set log severity of native lib, can be verbose,debug,info,error,fatal.\"\"\"\n        cond: bool = self._SetLogSeverityFunc(self.getInstance(), _char_pt(log_level))\n        _check(cond, 'Failed to set log level')\n\n    def SetSymfs(self, symfs_dir: str):\n        \"\"\" Set directory used to find symbols.\"\"\"\n        cond: bool = self._SetSymfsFunc(self.getInstance(), _char_pt(symfs_dir))\n        _check(cond, 'Failed to set symbols directory')\n\n    def SetRecordFile(self, record_file: str):\n        \"\"\" Set the path of record file, like perf.data.\"\"\"\n        cond: bool = self._SetRecordFileFunc(self.getInstance(), _char_pt(record_file))\n        _check(cond, 'Failed to set record file')\n\n    def ShowIpForUnknownSymbol(self):\n        self._ShowIpForUnknownSymbolFunc(self.getInstance())\n\n    def ShowArtFrames(self, show: bool = True):\n        \"\"\" Show frames of internal methods of the Java interpreter. \"\"\"\n        self._ShowArtFramesFunc(self.getInstance(), show)\n\n    def MergeJavaMethods(self, merge: bool = True):\n        \"\"\" This option merges jitted java methods with the same name but in different jit\n            symfiles. If possible, it also merges jitted methods with interpreted methods,\n            by mapping jitted methods to their corresponding dex files.\n            Side effects:\n              It only works at method level, not instruction level.\n              It makes symbol.vaddr_in_file and symbol.mapping not accurate for jitted methods.\n            Java methods are merged by default.\n        \"\"\"\n        self._MergeJavaMethodsFunc(self.getInstance(), merge)\n\n    def AddProguardMappingFile(self, mapping_file: Union[str, Path]):\n        \"\"\" Add proguard mapping.txt to de-obfuscate method names. \"\"\"\n        if not self._AddProguardMappingFileFunc(self.getInstance(), _char_pt(str(mapping_file))):\n            raise ValueError(f'failed to add proguard mapping file: {mapping_file}')\n\n    def SetKallsymsFile(self, kallsym_file: str):\n        \"\"\" Set the file path to a copy of the /proc/kallsyms file (for off device decoding) \"\"\"\n        cond: bool = self._SetKallsymsFileFunc(self.getInstance(), _char_pt(kallsym_file))\n        _check(cond, 'Failed to set kallsyms file')\n\n    def GetSupportedTraceOffCpuModes(self) -> List[str]:\n        \"\"\" Get trace-offcpu modes supported by the recording file. It should be called after\n            SetRecordFile(). The modes are only available for profiles recorded with --trace-offcpu\n            option. All possible modes are:\n              on-cpu:           report on-cpu samples with period representing time spent on cpu\n              off-cpu:          report off-cpu samples with period representing time spent off cpu\n              on-off-cpu:       report both on-cpu samples and off-cpu samples, which can be split\n                                by event name.\n              mixed-on-off-cpu: report on-cpu and off-cpu samples under the same event name.\n        \"\"\"\n        modes_str = self._GetSupportedTraceOffCpuModesFunc(self.getInstance())\n        _check(not _is_null(modes_str), 'Failed to call GetSupportedTraceOffCpuModes()')\n        modes_str = _char_pt_to_str(modes_str)\n        return modes_str.split(',') if modes_str else []\n\n    def SetTraceOffCpuMode(self, mode: str):\n        \"\"\" Set trace-offcpu mode. It should be called after SetRecordFile(). The mode should be\n            one of the modes returned by GetSupportedTraceOffCpuModes().\n        \"\"\"\n        res: bool = self._SetTraceOffCpuModeFunc(self.getInstance(), _char_pt(mode))\n        _check(res, f'Failed to call SetTraceOffCpuMode({mode})')\n\n    def SetSampleFilter(self, filter: str):\n        \"\"\" Set options used to filter samples. Available options are:\n            --exclude-pid pid1,pid2,...   Exclude samples for selected processes.\n            --exclude-tid tid1,tid2,...   Exclude samples for selected threads.\n            --exclude-process-name process_name_regex   Exclude samples for processes with name\n                                                        containing the regular expression.\n            --exclude-thread-name thread_name_regex     Exclude samples for threads with name\n                                                        containing the regular expression.\n            --include-pid pid1,pid2,...   Include samples for selected processes.\n            --include-tid tid1,tid2,...   Include samples for selected threads.\n            --include-process-name process_name_regex   Include samples for processes with name\n                                                        containing the regular expression.\n            --include-thread-name thread_name_regex     Include samples for threads with name\n                                                        containing the regular expression.\n            --filter-file <file>          Use filter file to filter samples based on timestamps. The\n                                          file format is in doc/sampler_filter.md.\n\n            The filter argument should be a concatenation of options.\n        \"\"\"\n        res: bool = self._SetSampleFilterFunc(self.getInstance(), _char_pt(filter))\n        _check(res, f'Failed to call SetSampleFilter({filter})')\n\n    def GetNextSample(self) -> Optional[SampleStruct]:\n        \"\"\" Return the next sample. If no more samples, return None. \"\"\"\n        psample = self._GetNextSampleFunc(self.getInstance())\n        if _is_null(psample):\n            self.current_sample = None\n        else:\n            self.current_sample = psample[0]\n        return self.current_sample\n\n    def GetCurrentSample(self) -> Optional[SampleStruct]:\n        return self.current_sample\n\n    def GetEventOfCurrentSample(self) -> EventStruct:\n        event = self._GetEventOfCurrentSampleFunc(self.getInstance())\n        assert not _is_null(event)\n        return event[0]\n\n    def GetSymbolOfCurrentSample(self) -> SymbolStruct:\n        symbol = self._GetSymbolOfCurrentSampleFunc(self.getInstance())\n        assert not _is_null(symbol)\n        return symbol[0]\n\n    def GetCallChainOfCurrentSample(self) -> CallChainStructure:\n        callchain = self._GetCallChainOfCurrentSampleFunc(self.getInstance())\n        assert not _is_null(callchain)\n        return callchain[0]\n\n    def GetTracingDataOfCurrentSample(self) -> Optional[Dict[str, Any]]:\n        data = self._GetTracingDataOfCurrentSampleFunc(self.getInstance())\n        if _is_null(data):\n            return None\n        event = self.GetEventOfCurrentSample()\n        result = collections.OrderedDict()\n        for i in range(event.tracing_data_format.field_count):\n            field = event.tracing_data_format.fields[i]\n            result[field.name] = field.parse_value(data)\n        return result\n\n    def GetBuildIdForPath(self, path: str) -> str:\n        build_id = self._GetBuildIdForPathFunc(self.getInstance(), _char_pt(path))\n        assert not _is_null(build_id)\n        return _char_pt_to_str(build_id)\n\n    def GetRecordCmd(self) -> str:\n        if self.record_cmd is not None:\n            return self.record_cmd\n        self.record_cmd = ''\n        feature_data = self._GetFeatureSection(self.getInstance(), _char_pt('cmdline'))\n        if not _is_null(feature_data):\n            void_p = ct.cast(feature_data[0].data, ct.c_void_p)\n            arg_count = ct.cast(void_p, ct.POINTER(ct.c_uint32)).contents.value\n            void_p.value += 4\n            args = []\n            for _ in range(arg_count):\n                str_len = ct.cast(void_p, ct.POINTER(ct.c_uint32)).contents.value\n                void_p.value += 4\n                char_p = ct.cast(void_p, ct.POINTER(ct.c_char))\n                current_str = ''\n                for j in range(str_len):\n                    c = bytes_to_str(char_p[j])\n                    if c != '\\0':\n                        current_str += c\n                if ' ' in current_str:\n                    current_str = '\"' + current_str + '\"'\n                args.append(current_str)\n                void_p.value += str_len\n            self.record_cmd = ' '.join(args)\n        return self.record_cmd\n\n    def _GetFeatureString(self, feature_name: str) -> str:\n        feature_data = self._GetFeatureSection(self.getInstance(), _char_pt(feature_name))\n        result = ''\n        if not _is_null(feature_data):\n            void_p = ct.cast(feature_data[0].data, ct.c_void_p)\n            str_len = ct.cast(void_p, ct.POINTER(ct.c_uint32)).contents.value\n            void_p.value += 4\n            char_p = ct.cast(void_p, ct.POINTER(ct.c_char))\n            for i in range(str_len):\n                c = bytes_to_str(char_p[i])\n                if c == '\\0':\n                    break\n                result += c\n        return result\n\n    def GetArch(self) -> str:\n        return self._GetFeatureString('arch')\n\n    def MetaInfo(self) -> Dict[str, str]:\n        \"\"\" Return a string to string map stored in meta_info section in perf.data.\n            It is used to pass some short meta information.\n        \"\"\"\n        if self.meta_info is None:\n            self.meta_info = {}\n            feature_data = self._GetFeatureSection(self.getInstance(), _char_pt('meta_info'))\n            if not _is_null(feature_data):\n                str_list = []\n                data = feature_data[0].data\n                data_size = feature_data[0].data_size\n                current_str = ''\n                for i in range(data_size):\n                    c = bytes_to_str(data[i])\n                    if c != '\\0':\n                        current_str += c\n                    else:\n                        str_list.append(current_str)\n                        current_str = ''\n                for i in range(0, len(str_list), 2):\n                    self.meta_info[str_list[i]] = str_list[i + 1]\n        return self.meta_info\n\n    def getInstance(self) -> ct._Pointer:\n        if self._instance is None:\n            raise Exception('Instance is Closed')\n        return self._instance\n"
  },
  {
    "path": "simpleperf/simpleperf_utils.py",
    "content": "#!/usr/bin/env python3\n#\n# Copyright (C) 2016 The Android Open Source Project\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\"\"\"utils.py: export utility functions.\n\"\"\"\n\nfrom __future__ import annotations\nimport argparse\nfrom concurrent.futures import Future, ThreadPoolExecutor\nimport logging\nimport os\nimport os.path\nfrom pathlib import Path\nimport re\nimport shutil\nimport subprocess\nimport sys\nimport time\nfrom typing import Any, Dict, Iterator, List, Optional, Set, Tuple, Union\n\n\nNDK_ERROR_MESSAGE = \"Please install the Android NDK (https://developer.android.com/studio/projects/install-ndk), then set NDK path with --ndk_path option.\"\n\n\ndef get_script_dir() -> str:\n    return os.path.dirname(os.path.realpath(__file__))\n\n\ndef is_windows() -> bool:\n    return sys.platform == 'win32' or sys.platform == 'cygwin'\n\n\ndef is_darwin() -> bool:\n    return sys.platform == 'darwin'\n\n\ndef get_platform() -> str:\n    if is_windows():\n        return 'windows'\n    if is_darwin():\n        return 'darwin'\n    return 'linux'\n\n\ndef str_to_bytes(str_value: str) -> bytes:\n    # In python 3, str are wide strings whereas the C api expects 8 bit strings,\n    # hence we have to convert. For now using utf-8 as the encoding.\n    return str_value.encode('utf-8')\n\n\ndef bytes_to_str(bytes_value: Optional[bytes]) -> str:\n    if not bytes_value:\n        return ''\n    return bytes_value.decode('utf-8')\n\n\ndef get_target_binary_path(arch: str, binary_name: str) -> str:\n    if arch == 'aarch64':\n        arch = 'arm64'\n    arch_dir = os.path.join(get_script_dir(), \"bin\", \"android\", arch)\n    if not os.path.isdir(arch_dir):\n        log_fatal(\"can't find arch directory: %s\" % arch_dir)\n    binary_path = os.path.join(arch_dir, binary_name)\n    if not os.path.isfile(binary_path):\n        log_fatal(\"can't find binary: %s\" % binary_path)\n    return binary_path\n\n\ndef get_host_binary_path(binary_name: str) -> str:\n    dirname = os.path.join(get_script_dir(), 'bin')\n    if is_windows():\n        if binary_name.endswith('.so'):\n            binary_name = binary_name[0:-3] + '.dll'\n        elif '.' not in binary_name:\n            binary_name += '.exe'\n        dirname = os.path.join(dirname, 'windows')\n    elif sys.platform == 'darwin':  # OSX\n        if binary_name.endswith('.so'):\n            binary_name = binary_name[0:-3] + '.dylib'\n        dirname = os.path.join(dirname, 'darwin')\n    else:\n        dirname = os.path.join(dirname, 'linux')\n    dirname = os.path.join(dirname, 'x86_64' if sys.maxsize > 2 ** 32 else 'x86')\n    binary_path = os.path.join(dirname, binary_name)\n    if not os.path.isfile(binary_path):\n        log_fatal(\"can't find binary: %s\" % binary_path)\n    return binary_path\n\n\ndef is_executable_available(executable: str, option='--help') -> bool:\n    \"\"\" Run an executable to see if it exists. \"\"\"\n    try:\n        subproc = subprocess.Popen([executable, option], stdout=subprocess.PIPE,\n                                   stderr=subprocess.PIPE)\n        subproc.communicate()\n        return subproc.returncode == 0\n    except OSError:\n        return False\n\n\nclass ToolFinder:\n    \"\"\" Find tools in ndk or sdk. \"\"\"\n    DEFAULT_SDK_PATH = {\n        'darwin': 'Library/Android/sdk',\n        'linux': 'Android/Sdk',\n        'windows': 'AppData/Local/Android/sdk',\n    }\n\n    EXPECTED_TOOLS = {\n        'adb': {\n            'is_binutils': False,\n            'test_option': 'version',\n            'path_in_sdk': 'platform-tools/adb',\n        },\n        'llvm-objdump': {\n            'is_binutils': False,\n            'path_in_ndk':\n                lambda platform: 'toolchains/llvm/prebuilt/%s-x86_64/bin/llvm-objdump' % platform,\n        },\n        'llvm-readelf': {\n            'is_binutils': False,\n            'path_in_ndk': \n                lambda platform: 'toolchains/llvm/prebuilt/%s-x86_64/bin/llvm-readelf' % platform,\n        },\n        'llvm-symbolizer': {\n            'is_binutils': False,\n            'path_in_ndk':\n                lambda platform: 'toolchains/llvm/prebuilt/%s-x86_64/bin/llvm-symbolizer' % platform,\n        },\n        'llvm-strip': {\n            'is_binutils': False,\n            'path_in_ndk':\n                lambda platform: 'toolchains/llvm/prebuilt/%s-x86_64/bin/llvm-strip' % platform,\n        },\n    }\n\n    @classmethod\n    def find_ndk_and_sdk_paths(cls, ndk_path: Optional[str] = None\n                               ) -> Iterator[Tuple[Optional[str], Optional[str]]]:\n        # Use the given ndk path.\n        if ndk_path and os.path.isdir(ndk_path):\n            ndk_path = os.path.abspath(ndk_path)\n            yield ndk_path, cls.find_sdk_path(ndk_path)\n        # Find ndk in the parent directory containing simpleperf scripts.\n        ndk_path = os.path.dirname(os.path.abspath(get_script_dir()))\n        yield ndk_path, cls.find_sdk_path(ndk_path)\n        # Find ndk in the default sdk installation path.\n        if is_windows():\n            home = os.environ.get('HOMEDRIVE') + os.environ.get('HOMEPATH')\n        else:\n            home = os.environ.get('HOME')\n        if home:\n            platform = get_platform()\n            sdk_path = os.path.join(home, cls.DEFAULT_SDK_PATH[platform].replace('/', os.sep))\n            if os.path.isdir(sdk_path):\n                path = os.path.join(sdk_path, 'ndk')\n                if os.path.isdir(path):\n                    # Android Studio can install multiple ndk versions in 'ndk'.\n                    # Find the newest one.\n                    ndk_version = None\n                    for name in os.listdir(path):\n                        if not ndk_version or ndk_version < name:\n                            ndk_version = name\n                    if ndk_version:\n                        yield os.path.join(path, ndk_version), sdk_path\n            ndk_path = os.path.join(sdk_path, 'ndk-bundle')\n            if os.path.isdir(ndk_path):\n                yield ndk_path, sdk_path\n\n    @classmethod\n    def find_sdk_path(cls, ndk_path: str) -> Optional[str]:\n        path = ndk_path\n        for _ in range(2):\n            path = os.path.dirname(path)\n            if os.path.isdir(os.path.join(path, 'platform-tools')):\n                return path\n        return None\n\n    @classmethod\n    def _get_binutils_path_in_ndk(cls, toolname: str, arch: Optional[str], platform: str\n                                  ) -> Tuple[str, str]:\n        if not arch:\n            arch = 'arm64'\n        if arch == 'arm64':\n            name = 'aarch64-linux-android-' + toolname\n        elif arch == 'arm':\n            name = 'arm-linux-androideabi-' + toolname\n        elif arch == 'x86_64':\n            name = 'x86_64-linux-android-' + toolname\n        elif arch == 'x86':\n            name = 'i686-linux-android-' + toolname\n        else:\n            log_fatal('unexpected arch %s' % arch)\n        path = 'toolchains/llvm/prebuilt/%s-x86_64/bin/%s' % (platform, name)\n        return (name, path)\n\n    @classmethod\n    def find_tool_path(cls, toolname: str, ndk_path: Optional[str] = None,\n                       arch: Optional[str] = None) -> Optional[str]:\n        tool_info = cls.EXPECTED_TOOLS.get(toolname)\n        if not tool_info:\n            return None\n\n        is_binutils = tool_info['is_binutils']\n        test_option = tool_info.get('test_option', '--help')\n        platform = get_platform()\n\n        # Find tool in clang prebuilts in Android platform.\n        if toolname.startswith('llvm-') and platform == 'linux' and get_script_dir().endswith(\n                'system/extras/simpleperf/scripts'):\n            path = str(\n                Path(get_script_dir()).parents[3] / 'prebuilts' / 'clang' / 'host' / 'linux-x86' /\n                'llvm-binutils-stable' / toolname)\n            if is_executable_available(path, test_option):\n                return path\n\n        # Find tool in NDK or SDK.\n        path_in_ndk = None\n        path_in_sdk = None\n        if is_binutils:\n            toolname_with_arch, path_in_ndk = cls._get_binutils_path_in_ndk(\n                toolname, arch, platform)\n        else:\n            toolname_with_arch = toolname\n            if 'path_in_ndk' in tool_info:\n                path_in_ndk = tool_info['path_in_ndk'](platform)\n            elif 'path_in_sdk' in tool_info:\n                path_in_sdk = tool_info['path_in_sdk']\n        if path_in_ndk:\n            path_in_ndk = path_in_ndk.replace('/', os.sep)\n        elif path_in_sdk:\n            path_in_sdk = path_in_sdk.replace('/', os.sep)\n\n        for ndk_dir, sdk_dir in cls.find_ndk_and_sdk_paths(ndk_path):\n            if path_in_ndk and ndk_dir:\n                path = os.path.join(ndk_dir, path_in_ndk)\n                if is_executable_available(path, test_option):\n                    return path\n            elif path_in_sdk and sdk_dir:\n                path = os.path.join(sdk_dir, path_in_sdk)\n                if is_executable_available(path, test_option):\n                    return path\n\n        # Find tool in $PATH.\n        if is_executable_available(toolname_with_arch, test_option):\n            return toolname_with_arch\n\n        # Find tool without arch in $PATH.\n        if is_binutils and tool_info.get('accept_tool_without_arch'):\n            if is_executable_available(toolname, test_option):\n                return toolname\n        return None\n\n\nclass AdbHelper(object):\n    def __init__(self, enable_switch_to_root: bool = True):\n        adb_path = ToolFinder.find_tool_path('adb')\n        if not adb_path:\n            log_exit(\"Can't find adb in PATH environment.\")\n        self.adb_path: str = adb_path\n        self.enable_switch_to_root = enable_switch_to_root\n        self.serial_number: Optional[str] = None\n\n    def is_device_available(self) -> bool:\n        return self.run_and_return_output(['shell', 'whoami'])[0]\n\n    def run(self, adb_args: List[str], log_output: bool = False, log_stderr: bool = False) -> bool:\n        return self.run_and_return_output(adb_args, log_output, log_stderr)[0]\n\n    def run_and_return_output(self, adb_args: List[str], log_output: bool = False,\n                              log_stderr: bool = False) -> Tuple[bool, str]:\n        adb_args = [self.adb_path] + adb_args\n        logging.debug('run adb cmd: %s' % adb_args)\n        env = None\n        if self.serial_number:\n            env = os.environ.copy()\n            env['ANDROID_SERIAL'] = self.serial_number\n        subproc = subprocess.Popen(\n            adb_args, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n        stdout_data, stderr_data = subproc.communicate()\n        stdout_data = bytes_to_str(stdout_data)\n        stderr_data = bytes_to_str(stderr_data)\n        returncode = subproc.returncode\n        result = (returncode == 0)\n        if log_output and stdout_data:\n            logging.debug(stdout_data)\n        if log_stderr and stderr_data:\n            logging.warning(stderr_data)\n        logging.debug('run adb cmd: %s  [result %s]' % (adb_args, result))\n        return (result, stdout_data)\n\n    def check_run(self, adb_args: List[str], log_output: bool = False):\n        self.check_run_and_return_output(adb_args, log_output)\n\n    def check_run_and_return_output(self, adb_args: List[str], log_output: bool = False,\n                                    log_stderr: bool = False) -> str:\n        result, stdoutdata = self.run_and_return_output(adb_args, log_output, True)\n        if not result:\n            log_exit('run \"adb %s\" failed: %s' % (adb_args, stdoutdata))\n        return stdoutdata\n\n    def _unroot(self):\n        result, stdoutdata = self.run_and_return_output(['shell', 'whoami'])\n        if not result:\n            return\n        if 'root' not in stdoutdata:\n            return\n        logging.info('unroot adb')\n        self.run(['unroot'])\n        time.sleep(1)\n        self.run(['wait-for-device'])\n\n    def switch_to_root(self) -> bool:\n        if not self.enable_switch_to_root:\n            self._unroot()\n            return False\n        result, stdoutdata = self.run_and_return_output(['shell', 'whoami'])\n        if not result:\n            return False\n        if 'root' in stdoutdata:\n            return True\n        build_type = self.get_property('ro.build.type')\n        if build_type == 'user':\n            return False\n        self.run(['root'])\n        time.sleep(1)\n        self.run(['wait-for-device'])\n        result, stdoutdata = self.run_and_return_output(['shell', 'whoami'])\n        return result and 'root' in stdoutdata\n\n    def get_property(self, name: str) -> Optional[str]:\n        result, stdoutdata = self.run_and_return_output(['shell', 'getprop', name])\n        return stdoutdata.strip() if result else None\n\n    def set_property(self, name: str, value: str) -> bool:\n        return self.run(['shell', 'setprop', name, value])\n\n    def get_device_arch(self) -> str:\n        output = self.check_run_and_return_output(['shell', 'uname', '-m'])\n        if 'aarch64' in output:\n            return 'arm64'\n        if 'arm' in output:\n            return 'arm'\n        if 'x86_64' in output:\n            return 'x86_64'\n        if '86' in output:\n            return 'x86'\n        log_fatal('unsupported architecture: %s' % output.strip())\n        return ''\n\n    def get_android_version(self) -> int:\n        \"\"\" Get Android version on device, like 7 is for Android N, 8 is for Android O.\"\"\"\n        build_version = self.get_property('ro.build.version.codename')\n        if not build_version or build_version == 'REL':\n            build_version = self.get_property('ro.build.version.release')\n        android_version = 0\n        if build_version:\n            if build_version[0].isdigit():\n                i = 1\n                while i < len(build_version) and build_version[i].isdigit():\n                    i += 1\n                android_version = int(build_version[:i])\n            else:\n                c = build_version[0].upper()\n                if c.isupper() and c >= 'L':\n                    android_version = ord(c) - ord('L') + 5\n        return android_version\n\n\ndef flatten_arg_list(arg_list: List[List[str]]) -> List[str]:\n    res = []\n    if arg_list:\n        for items in arg_list:\n            res += items\n    return res\n\n\ndef remove(dir_or_file: Union[Path, str]):\n    if os.path.isfile(dir_or_file):\n        os.remove(dir_or_file)\n    elif os.path.isdir(dir_or_file):\n        shutil.rmtree(dir_or_file, ignore_errors=True)\n\n\ndef open_report_in_browser(report_path: str):\n    if is_darwin():\n        # On darwin 10.12.6, webbrowser can't open browser, so try `open` cmd first.\n        try:\n            subprocess.check_call(['open', report_path])\n            return\n        except subprocess.CalledProcessError:\n            pass\n    import webbrowser\n    try:\n        # Try to open the report with Chrome\n        browser = webbrowser.get('google-chrome')\n        browser.open(report_path, new=0, autoraise=True)\n    except webbrowser.Error:\n        # webbrowser.get() doesn't work well on darwin/windows.\n        webbrowser.open_new_tab(report_path)\n\n\nclass BinaryFinder:\n    def __init__(self, binary_cache_dir: Optional[Union[Path, str]], readelf: ReadElf):\n        if isinstance(binary_cache_dir, str):\n            binary_cache_dir = Path(binary_cache_dir)\n        self.binary_cache_dir = binary_cache_dir\n        self.readelf = readelf\n        self.build_id_map = self._load_build_id_map()\n\n    def _load_build_id_map(self) -> Dict[str, Path]:\n        build_id_map: Dict[str, Path] = {}\n        if self.binary_cache_dir:\n            build_id_list_file = self.binary_cache_dir / 'build_id_list'\n            if build_id_list_file.is_file():\n                with open(self.binary_cache_dir / 'build_id_list', 'rb') as fh:\n                    for line in fh.readlines():\n                        # lines are in format \"<build_id>=<path_in_binary_cache>\".\n                        items = bytes_to_str(line).strip().split('=')\n                        if len(items) == 2:\n                            build_id_map[items[0]] = self.binary_cache_dir / items[1]\n        return build_id_map\n\n    def find_binary(self, dso_path_in_record_file: str,\n                    expected_build_id: Optional[str]) -> Optional[Path]:\n        \"\"\" If expected_build_id is None, don't check build id.\n            Otherwise, the build id of the found binary should match the expected one.\"\"\"\n        # Find binary from build id map.\n        if expected_build_id:\n            path = self.build_id_map.get(expected_build_id)\n            if path and self._check_path(path, expected_build_id):\n                return path\n        # Find binary by path in binary cache.\n        if self.binary_cache_dir:\n            path = self.binary_cache_dir / dso_path_in_record_file[1:]\n            if self._check_path(path, expected_build_id):\n                return path\n        # Find binary by its absolute path.\n        path = Path(dso_path_in_record_file)\n        if self._check_path(path, expected_build_id):\n            return path\n        return None\n\n    def _check_path(self, path: Path, expected_build_id: Optional[str]) -> bool:\n        if not self.readelf.is_elf_file(path):\n            return False\n        if expected_build_id is not None:\n            return self.readelf.get_build_id(path) == expected_build_id\n        return True\n\n\nclass Addr2Nearestline(object):\n    \"\"\" Use llvm-symbolizer to convert (dso_path, func_addr, addr) to (source_file, line).\n        For instructions generated by C++ compilers without a matching statement in source code\n        (like stack corruption check, switch optimization, etc.), addr2line can't generate\n        line information. However, we want to assign the instruction to the nearest line before\n        the instruction (just like objdump -dl). So we use below strategy:\n        Instead of finding the exact line of the instruction in an address, we find the nearest\n        line to the instruction in an address. If an address doesn't have a line info, we find\n        the line info of address - 1. If still no line info, then use address - 2, address - 3,\n        etc.\n\n        The implementation steps are as below:\n        1. Collect all (dso_path, func_addr, addr) requests before converting. This saves the\n        times to call addr2line.\n        2. Convert addrs to (source_file, line) pairs for each dso_path as below:\n          2.1 Check if the dso_path has .debug_line. If not, omit its conversion.\n          2.2 Get arch of the dso_path, and decide the addr_step for it. addr_step is the step we\n          change addr each time. For example, since instructions of arm64 are all 4 bytes long,\n          addr_step for arm64 can be 4.\n          2.3 Use addr2line to find line info for each addr in the dso_path.\n          2.4 For each addr without line info, use addr2line to find line info for\n              range(addr - addr_step, addr - addr_step * 4 - 1, -addr_step).\n          2.5 For each addr without line info, use addr2line to find line info for\n              range(addr - addr_step * 5, addr - addr_step * 128 - 1, -addr_step).\n              (128 is a guess number. A nested switch statement in\n               system/core/demangle/Demangler.cpp has >300 bytes without line info in arm64.)\n    \"\"\"\n    class Dso(object):\n        \"\"\" Info of a dynamic shared library.\n            addrs: a map from address to Addr object in this dso.\n        \"\"\"\n\n        def __init__(self, build_id: Optional[str]):\n            self.build_id = build_id\n            self.addrs: Dict[int, Addr2Nearestline.Addr] = {}\n            # Saving file names for each addr takes a lot of memory. So we store file ids in Addr,\n            # and provide data structures connecting file id and file name here.\n            self.file_name_to_id: Dict[str, int] = {}\n            self.file_id_to_name: List[str] = []\n            self.func_name_to_id: Dict[str, int] = {}\n            self.func_id_to_name: List[str] = []\n\n        def get_file_id(self, file_path: str) -> int:\n            file_id = self.file_name_to_id.get(file_path)\n            if file_id is None:\n                file_id = self.file_name_to_id[file_path] = len(self.file_id_to_name)\n                self.file_id_to_name.append(file_path)\n            return file_id\n\n        def get_func_id(self, func_name: str) -> int:\n            func_id = self.func_name_to_id.get(func_name)\n            if func_id is None:\n                func_id = self.func_name_to_id[func_name] = len(self.func_id_to_name)\n                self.func_id_to_name.append(func_name)\n            return func_id\n\n    class Addr(object):\n        \"\"\" Info of an addr request.\n            func_addr: start_addr of the function containing addr.\n            source_lines: a list of [file_id, line_number] for addr.\n                          source_lines[:-1] are all for inlined functions.\n        \"\"\"\n\n        def __init__(self, func_addr: int):\n            self.func_addr = func_addr\n            self.source_lines: Optional[List[int, int]] = None\n\n    def __init__(\n            self, ndk_path: Optional[str],\n            binary_finder: BinaryFinder, with_function_name: bool):\n        self.symbolizer_path = ToolFinder.find_tool_path('llvm-symbolizer', ndk_path)\n        if not self.symbolizer_path:\n            log_exit(\"Can't find llvm-symbolizer. \" + NDK_ERROR_MESSAGE)\n        self.readelf = ReadElf(ndk_path)\n        self.dso_map: Dict[str, Addr2Nearestline.Dso] = {}  # map from dso_path to Dso.\n        self.binary_finder = binary_finder\n        self.with_function_name = with_function_name\n\n    def add_addr(self, dso_path: str, build_id: Optional[str], func_addr: int, addr: int):\n        dso = self.dso_map.get(dso_path)\n        if dso is None:\n            dso = self.dso_map[dso_path] = self.Dso(build_id)\n        if addr not in dso.addrs:\n            dso.addrs[addr] = self.Addr(func_addr)\n\n    def convert_addrs_to_lines(self, jobs: int):\n        with ThreadPoolExecutor(jobs) as executor:\n            futures: List[Future] = []\n            for dso_path, dso in self.dso_map.items():\n                futures.append(executor.submit(self._convert_addrs_in_one_dso, dso_path, dso))\n            for future in futures:\n                # Call future.result() to report exceptions raised in the executor.\n                future.result()\n\n    def _convert_addrs_in_one_dso(self, dso_path: str, dso: Addr2Nearestline.Dso):\n        real_path = self.binary_finder.find_binary(dso_path, dso.build_id)\n        if not real_path:\n            if dso_path not in ['//anon', 'unknown', '[kernel.kallsyms]']:\n                logging.debug(\"Can't find dso %s\" % dso_path)\n            return\n\n        if not self._check_debug_line_section(real_path):\n            logging.warning(\"file %s doesn't contain .debug_line section.\" % real_path)\n            return\n\n        addr_step = self._get_addr_step(real_path)\n        self._collect_line_info(dso, real_path, [0])\n        self._collect_line_info(dso, real_path, range(-addr_step, -addr_step * 4 - 1, -addr_step))\n        self._collect_line_info(dso, real_path,\n                                range(-addr_step * 5, -addr_step * 128 - 1, -addr_step))\n\n    def _check_debug_line_section(self, real_path: Path) -> bool:\n        return '.debug_line' in self.readelf.get_sections(real_path)\n\n    def _get_addr_step(self, real_path: Path) -> int:\n        arch = self.readelf.get_arch(real_path)\n        if arch == 'arm64':\n            return 4\n        if arch == 'arm':\n            return 2\n        return 1\n\n    def _collect_line_info(\n            self, dso: Addr2Nearestline.Dso, real_path: Path, addr_shifts: List[int]):\n        \"\"\" Use addr2line to get line info in a dso, with given addr shifts. \"\"\"\n        # 1. Collect addrs to send to addr2line.\n        addr_set: Set[int] = set()\n        for addr in dso.addrs:\n            addr_obj = dso.addrs[addr]\n            if addr_obj.source_lines:  # already has source line, no need to search.\n                continue\n            for shift in addr_shifts:\n                # The addr after shift shouldn't change to another function.\n                shifted_addr = max(addr + shift, addr_obj.func_addr)\n                addr_set.add(shifted_addr)\n                if shifted_addr == addr_obj.func_addr:\n                    break\n        if not addr_set:\n            return\n        addr_request = '\\n'.join(['0x%x' % addr for addr in sorted(addr_set)])\n\n        # 2. Use addr2line to collect line info.\n        try:\n            subproc = subprocess.Popen(self._build_symbolizer_args(real_path),\n                                       stdin=subprocess.PIPE, stdout=subprocess.PIPE)\n            (stdoutdata, _) = subproc.communicate(str_to_bytes(addr_request))\n            stdoutdata = bytes_to_str(stdoutdata)\n        except OSError:\n            return\n        addr_map = self.parse_line_output(stdoutdata, dso)\n\n        # 3. Fill line info in dso.addrs.\n        for addr in dso.addrs:\n            addr_obj = dso.addrs[addr]\n            if addr_obj.source_lines:\n                continue\n            for shift in addr_shifts:\n                shifted_addr = max(addr + shift, addr_obj.func_addr)\n                lines = addr_map.get(shifted_addr)\n                if lines:\n                    addr_obj.source_lines = lines\n                    break\n                if shifted_addr == addr_obj.func_addr:\n                    break\n\n    def _build_symbolizer_args(self, binary_path: Path) -> List[str]:\n        args = [self.symbolizer_path, '--print-address', '--inlining', '--obj=%s' % binary_path]\n        if self.with_function_name:\n            args += ['--functions=linkage', '--demangle']\n        else:\n            args.append('--functions=none')\n        return args\n\n    def parse_line_output(self, output: str, dso: Addr2Nearestline.Dso) -> Dict[int,\n                                                                                List[Tuple[int]]]:\n        \"\"\"\n        The output is a list of lines.\n            address1\n            function_name1 (the function name can be empty)\n            source_location1\n            function_name2\n            source_location2\n            ...\n            (end with empty line)\n        \"\"\"\n\n        addr_map: Dict[int, List[Tuple[int]]] = {}\n        lines = output.strip().splitlines()\n        i = 0\n        while i < len(lines):\n            address = self._parse_line_output_address(lines[i])\n            i += 1\n            if address is None:\n                continue\n            info = []\n            while i < len(lines):\n                if self.with_function_name:\n                    if i + 1 == len(lines):\n                        break\n                    function_name = lines[i].strip()\n                    if not function_name and (':' not in lines[i+1]):\n                        # no more frames\n                        break\n                    i += 1\n                elif not lines[i]:\n                    i += 1\n                    break\n\n                file_path, line_number = self._parse_line_output_source_location(lines[i])\n                i += 1\n                if not file_path or not line_number:\n                    # An addr can have a list of (file, line), when the addr belongs to an inlined\n                    # function. Sometimes only part of the list has ? mark. In this case, we think\n                    # the line info is valid if the first line doesn't have ? mark.\n                    if not info:\n                        break\n                    continue\n                file_id = dso.get_file_id(file_path)\n                if self.with_function_name:\n                    func_id = dso.get_func_id(function_name)\n                    info.append((file_id, line_number, func_id))\n                else:\n                    info.append((file_id, line_number))\n            if info:\n                addr_map[address] = info\n        return addr_map\n\n    def _parse_line_output_address(self, output: str) -> Optional[int]:\n        if output.startswith('0x'):\n            return int(output, 16)\n        return None\n\n    def _parse_line_output_source_location(self, line: str) -> Tuple[Optional[str], Optional[int]]:\n        file_path, line_number = None, None\n        # Handle lines in format filename:line:column, like \"runtest/two_functions.cpp:14:25\".\n        # Filename may contain ':' like \"C:\\Users\\...\\file\".\n        items = line.rsplit(':', 2)\n        if len(items) == 3:\n            file_path, line_number = items[:2]\n        if not file_path or ('?' in file_path) or not line_number or ('?' in line_number):\n            return None, None\n        try:\n            line_number = int(line_number)\n        except ValueError:\n            return None, None\n        return file_path, line_number\n\n    def get_dso(self, dso_path: str) -> Addr2Nearestline.Dso:\n        return self.dso_map.get(dso_path)\n\n    def get_addr_source(self, dso: Addr2Nearestline.Dso, addr: int) -> Optional[List[Tuple[int]]]:\n        source = dso.addrs[addr].source_lines\n        if source is None:\n            return None\n        if self.with_function_name:\n            return [(dso.file_id_to_name[file_id], line, dso.func_id_to_name[func_id])\n                    for (file_id, line, func_id) in source]\n        return [(dso.file_id_to_name[file_id], line) for (file_id, line) in source]\n\n\nclass SourceFileSearcher(object):\n    \"\"\" Find source file paths in the file system.\n        The file paths reported by addr2line are the paths stored in debug sections\n        of shared libraries. And we need to convert them to file paths in the file\n        system. It is done in below steps:\n        1. Collect all file paths under the provided source_dirs. The suffix of a\n           source file should contain one of below:\n            h: for C/C++ header files.\n            c: for C/C++ source files.\n            java: for Java source files.\n            kt: for Kotlin source files.\n        2. Given an abstract_path reported by addr2line, select the best real path\n           as below:\n           2.1 Find all real paths with the same file name as the abstract path.\n           2.2 Select the real path having the longest common suffix with the abstract path.\n    \"\"\"\n\n    SOURCE_FILE_EXTS = {'.h', '.hh', '.H', '.hxx', '.hpp', '.h++',\n                        '.c', '.cc', '.C', '.cxx', '.cpp', '.c++',\n                        '.java', '.kt'}\n\n    @classmethod\n    def is_source_filename(cls, filename: str) -> bool:\n        ext = os.path.splitext(filename)[1]\n        return ext in cls.SOURCE_FILE_EXTS\n\n    def __init__(self, source_dirs: List[str]):\n        # Map from filename to a list of reversed directory path containing filename.\n        self.filename_to_rparents: Dict[str, List[str]] = {}\n        self._collect_paths(source_dirs)\n\n    def _collect_paths(self, source_dirs: List[str]):\n        for source_dir in source_dirs:\n            for parent, _, file_names in os.walk(source_dir):\n                rparent = None\n                for file_name in file_names:\n                    if self.is_source_filename(file_name):\n                        rparents = self.filename_to_rparents.get(file_name)\n                        if rparents is None:\n                            rparents = self.filename_to_rparents[file_name] = []\n                        if rparent is None:\n                            rparent = parent[::-1]\n                        rparents.append(rparent)\n\n    def get_real_path(self, abstract_path: str) -> Optional[str]:\n        abstract_path = abstract_path.replace('/', os.sep)\n        abstract_parent, file_name = os.path.split(abstract_path)\n        abstract_rparent = abstract_parent[::-1]\n        real_rparents = self.filename_to_rparents.get(file_name)\n        if real_rparents is None:\n            return None\n        best_matched_rparent = None\n        best_common_length = -1\n        for real_rparent in real_rparents:\n            length = len(os.path.commonprefix((real_rparent, abstract_rparent)))\n            if length > best_common_length:\n                best_common_length = length\n                best_matched_rparent = real_rparent\n        if best_matched_rparent is None:\n            return None\n        return os.path.join(best_matched_rparent[::-1], file_name)\n\n\nclass Objdump(object):\n    \"\"\" A wrapper of objdump to disassemble code. \"\"\"\n\n    def __init__(self, ndk_path: Optional[str], binary_finder: BinaryFinder):\n        self.ndk_path = ndk_path\n        self.binary_finder = binary_finder\n        self.readelf = ReadElf(ndk_path)\n        self.objdump_paths: Dict[str, str] = {}\n\n    def get_dso_info(self, dso_path: str, expected_build_id: Optional[str]\n                     ) -> Optional[Tuple[str, str]]:\n        real_path = self.binary_finder.find_binary(dso_path, expected_build_id)\n        if not real_path:\n            return None\n        arch = self.readelf.get_arch(real_path)\n        if arch == 'unknown':\n            return None\n        return (str(real_path), arch)\n\n    def disassemble_code(self, dso_info, start_addr, addr_len) -> List[Tuple[str, int]]:\n        \"\"\" Disassemble [start_addr, start_addr + addr_len] of dso_path.\n            Return a list of pair (disassemble_code_line, addr).\n        \"\"\"\n        real_path, arch = dso_info\n        objdump_path = self.objdump_paths.get(arch)\n        if not objdump_path:\n            objdump_path = ToolFinder.find_tool_path('llvm-objdump', self.ndk_path, arch)\n            if not objdump_path:\n                log_exit(\"Can't find llvm-objdump.\" + NDK_ERROR_MESSAGE)\n            self.objdump_paths[arch] = objdump_path\n\n        # 3. Run objdump.\n        args = [objdump_path, '-dlC', '--no-show-raw-insn',\n                '--start-address=0x%x' % start_addr,\n                '--stop-address=0x%x' % (start_addr + addr_len),\n                real_path]\n        if arch == 'arm' and 'llvm-objdump' in objdump_path:\n            args += ['--print-imm-hex']\n        try:\n            subproc = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE)\n            (stdoutdata, _) = subproc.communicate()\n            stdoutdata = bytes_to_str(stdoutdata)\n        except OSError:\n            return None\n\n        if not stdoutdata:\n            return None\n        result = []\n        for line in stdoutdata.split('\\n'):\n            line = line.rstrip()  # Remove '\\r' on Windows.\n            items = line.split(':', 1)\n            try:\n                addr = int(items[0], 16)\n            except ValueError:\n                addr = 0\n            result.append((line, addr))\n        return result\n\n\nclass ReadElf(object):\n    \"\"\" A wrapper of readelf. \"\"\"\n\n    def __init__(self, ndk_path: Optional[str]):\n        self.readelf_path = ToolFinder.find_tool_path('llvm-readelf', ndk_path)\n        if not self.readelf_path:\n            log_exit(\"Can't find llvm-readelf. \" + NDK_ERROR_MESSAGE)\n\n    @staticmethod\n    def is_elf_file(path: Union[Path, str]) -> bool:\n        if os.path.isfile(path):\n            with open(path, 'rb') as fh:\n                return fh.read(4) == b'\\x7fELF'\n        return False\n\n    def get_arch(self, elf_file_path: Union[Path, str]) -> str:\n        \"\"\" Get arch of an elf file. \"\"\"\n        if self.is_elf_file(elf_file_path):\n            try:\n                output = subprocess.check_output([self.readelf_path, '-h', str(elf_file_path)])\n                output = bytes_to_str(output)\n                if output.find('AArch64') != -1:\n                    return 'arm64'\n                if output.find('ARM') != -1:\n                    return 'arm'\n                if output.find('X86-64') != -1:\n                    return 'x86_64'\n                if output.find('80386') != -1:\n                    return 'x86'\n            except subprocess.CalledProcessError:\n                pass\n        return 'unknown'\n\n    def get_build_id(self, elf_file_path: Union[Path, str], with_padding=True) -> str:\n        \"\"\" Get build id of an elf file. \"\"\"\n        if self.is_elf_file(elf_file_path):\n            try:\n                output = subprocess.check_output([self.readelf_path, '-n', str(elf_file_path)])\n                output = bytes_to_str(output)\n                result = re.search(r'Build ID:\\s*(\\S+)', output)\n                if result:\n                    build_id = result.group(1)\n                    if with_padding:\n                        build_id = self.pad_build_id(build_id)\n                    return build_id\n            except subprocess.CalledProcessError:\n                pass\n        return \"\"\n\n    @staticmethod\n    def pad_build_id(build_id: str) -> str:\n        \"\"\" Pad build id to 40 hex numbers (20 bytes). \"\"\"\n        if len(build_id) < 40:\n            build_id += '0' * (40 - len(build_id))\n        else:\n            build_id = build_id[:40]\n        return '0x' + build_id\n\n    @staticmethod\n    def unpad_build_id(build_id: str) -> str:\n        if build_id.startswith('0x'):\n            build_id = build_id[2:]\n            # Unpad build id as TrimZeroesFromBuildIDString() in quipper.\n            padding = '0' * 8\n            while build_id.endswith(padding):\n                build_id = build_id[:-len(padding)]\n        return build_id\n\n    def get_sections(self, elf_file_path: Union[Path, str]) -> List[str]:\n        \"\"\" Get sections of an elf file. \"\"\"\n        section_names: List[str] = []\n        if self.is_elf_file(elf_file_path):\n            try:\n                output = subprocess.check_output([self.readelf_path, '-SW', str(elf_file_path)])\n                output = bytes_to_str(output)\n                for line in output.split('\\n'):\n                    # Parse line like:\" [ 1] .note.android.ident NOTE  0000000000400190 ...\".\n                    result = re.search(r'^\\s+\\[\\s*\\d+\\]\\s(.+?)\\s', line)\n                    if result:\n                        section_name = result.group(1).strip()\n                        if section_name:\n                            section_names.append(section_name)\n            except subprocess.CalledProcessError:\n                pass\n        return section_names\n\n\ndef extant_dir(arg: str) -> str:\n    \"\"\"ArgumentParser type that only accepts extant directories.\n\n    Args:\n        arg: The string argument given on the command line.\n    Returns: The argument as a realpath.\n    Raises:\n        argparse.ArgumentTypeError: The given path isn't a directory.\n    \"\"\"\n    path = os.path.realpath(arg)\n    if not os.path.isdir(path):\n        raise argparse.ArgumentTypeError('{} is not a directory.'.format(path))\n    return path\n\n\ndef extant_file(arg: str) -> str:\n    \"\"\"ArgumentParser type that only accepts extant files.\n\n    Args:\n        arg: The string argument given on the command line.\n    Returns: The argument as a realpath.\n    Raises:\n        argparse.ArgumentTypeError: The given path isn't a file.\n    \"\"\"\n    path = os.path.realpath(arg)\n    if not os.path.isfile(path):\n        raise argparse.ArgumentTypeError('{} is not a file.'.format(path))\n    return path\n\n\ndef log_fatal(msg: str):\n    raise Exception(msg)\n\n\ndef log_exit(msg: str):\n    sys.exit(msg)\n\n\nclass LogFormatter(logging.Formatter):\n    \"\"\" Use custom logging format. \"\"\"\n\n    def __init__(self):\n        super().__init__('%(asctime)s [%(levelname)s] (%(filename)s:%(lineno)d) %(message)s')\n\n    def formatTime(self, record, datefmt):\n        return super().formatTime(record, '%H:%M:%S') + ',%03d' % record.msecs\n\n\nclass Log:\n    initialized = False\n\n    @classmethod\n    def init(cls, log_level: str = 'info'):\n        assert not cls.initialized\n        cls.initialized = True\n        cls.logger = logging.root\n        cls.logger.setLevel(log_level.upper())\n        handler = logging.StreamHandler()\n        handler.setFormatter(LogFormatter())\n        cls.logger.addHandler(handler)\n\n\nclass ArgParseFormatter(\n        argparse.ArgumentDefaultsHelpFormatter, argparse.RawDescriptionHelpFormatter):\n    pass\n\n\nclass BaseArgumentParser(argparse.ArgumentParser):\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs, formatter_class=ArgParseFormatter)\n        self.has_sample_filter_options = False\n        self.sample_filter_with_pid_shortcut = False\n\n    def add_trace_offcpu_option(self, subparser: Optional[Any] = None):\n        parser = subparser if subparser else self\n        parser.add_argument(\n            '--trace-offcpu', choices=['on-cpu', 'off-cpu', 'on-off-cpu', 'mixed-on-off-cpu'],\n            help=\"\"\"Set report mode for profiles recorded with --trace-offcpu option. All possible\n                    modes are: on-cpu (only on-cpu samples), off-cpu (only off-cpu samples),\n                    on-off-cpu (both on-cpu and off-cpu samples, can be split by event name),\n                    mixed-on-off-cpu (on-cpu and off-cpu samples using the same event name).\n                    If not set, mixed-on-off-cpu mode is used.\n                \"\"\")\n\n    def add_sample_filter_options(\n            self, group: Optional[Any] = None, with_pid_shortcut: bool = True):\n        if not group:\n            group = self.add_argument_group('Sample filter options')\n        group.add_argument('--exclude-pid', metavar='pid', nargs='+', type=int,\n                           help='exclude samples for selected processes')\n        group.add_argument('--exclude-tid', metavar='tid', nargs='+', type=int,\n                           help='exclude samples for selected threads')\n        group.add_argument(\n            '--exclude-process-name', metavar='process_name_regex', nargs='+',\n            help='exclude samples for processes with name containing the regular expression')\n        group.add_argument(\n            '--exclude-thread-name', metavar='thread_name_regex', nargs='+',\n            help='exclude samples for threads with name containing the regular expression')\n\n        if with_pid_shortcut:\n            group.add_argument('--pid', metavar='pid', nargs='+', type=int,\n                               help='only include samples for selected processes')\n            group.add_argument('--tid', metavar='tid', nargs='+', type=int,\n                               help='only include samples for selected threads')\n        group.add_argument('--include-pid', metavar='pid', nargs='+', type=int,\n                           help='only include samples for selected processes')\n        group.add_argument('--include-tid', metavar='tid', nargs='+', type=int,\n                           help='only include samples for selected threads')\n        group.add_argument(\n            '--include-process-name', metavar='process_name_regex', nargs='+',\n            help='only include samples for processes with name containing the regular expression')\n        group.add_argument(\n            '--include-thread-name', metavar='thread_name_regex', nargs='+',\n            help='only include samples for threads with name containing the regular expression')\n        group.add_argument(\n            '--filter-file', metavar='file',\n            help='use filter file to filter samples based on timestamps. ' +\n            'The file format is in doc/sampler_filter.md.')\n        self.has_sample_filter_options = True\n        self.sample_filter_with_pid_shortcut = with_pid_shortcut\n\n    def _build_sample_filter(self, args: argparse.Namespace) -> Optional[str]:\n        \"\"\" Convert sample filter options into a sample filter string, which can be passed to\n            ReportLib.SetSampleFilter().\n        \"\"\"\n        filters = []\n        if args.exclude_pid:\n            filters.append('--exclude-pid ' + ','.join(str(pid) for pid in args.exclude_pid))\n        if args.exclude_tid:\n            filters.append('--exclude-tid ' + ','.join(str(tid) for tid in args.exclude_tid))\n        if args.exclude_process_name:\n            for name in args.exclude_process_name:\n                filters.append('--exclude-process-name ' + name)\n        if args.exclude_thread_name:\n            for name in args.exclude_thread_name:\n                filters.append('--exclude-thread-name ' + name)\n\n        if args.include_pid:\n            filters.append('--include-pid ' + ','.join(str(pid) for pid in args.include_pid))\n        if args.include_tid:\n            filters.append('--include-tid ' + ','.join(str(tid) for tid in args.include_tid))\n        if self.sample_filter_with_pid_shortcut:\n            if args.pid:\n                filters.append('--include-pid ' + ','.join(str(pid) for pid in args.pid))\n            if args.tid:\n                filters.append('--include-tid ' + ','.join(str(pid) for pid in args.tid))\n        if args.include_process_name:\n            for name in args.include_process_name:\n                filters.append('--include-process-name ' + name)\n        if args.include_thread_name:\n            for name in args.include_thread_name:\n                filters.append('--include-thread-name ' + name)\n        if args.filter_file:\n            filters.append('--filter-file ' + args.filter_file)\n        return ' '.join(filters)\n\n    def parse_known_args(self, *args, **kwargs):\n        self.add_argument(\n            '--log', choices=['debug', 'info', 'warning'],\n            default='info', help='set log level')\n        namespace, left_args = super().parse_known_args(*args, **kwargs)\n\n        if self.has_sample_filter_options:\n            setattr(namespace, 'sample_filter', self._build_sample_filter(namespace))\n\n        if not Log.initialized:\n            Log.init(namespace.log)\n        return namespace, left_args\n"
  },
  {
    "path": "simpleperf/stackcollapse.py",
    "content": "#!/usr/bin/env python3\n#\n# Copyright (C) 2021 The Android Open Source Project\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\"\"\"stackcollapse.py: convert perf.data to Brendan Gregg's \"Folded Stacks\" format,\n    which can be read by https://github.com/brendangregg/FlameGraph, and many\n    other tools.\n\n  Example:\n    ./app_profiler.py\n    ./stackcollapse.py | ~/FlameGraph/flamegraph.pl --color=java --countname=ns > flamegraph.svg\n\"\"\"\n\nfrom collections import defaultdict\nfrom simpleperf_report_lib import ReportLib\nfrom simpleperf_utils import BaseArgumentParser, flatten_arg_list\nfrom typing import DefaultDict, List, Optional, Set\n\nimport logging\nimport sys\n\n\ndef collapse_stacks(\n        record_file: str,\n        symfs_dir: str,\n        kallsyms_file: str,\n        proguard_mapping_file: List[str],\n        event_filter: str,\n        include_pid: bool,\n        include_tid: bool,\n        annotate_kernel: bool,\n        annotate_jit: bool,\n        include_addrs: bool,\n        comm_filter: Set[str],\n        sample_filter: Optional[str]):\n    \"\"\"read record_file, aggregate per-stack and print totals per-stack\"\"\"\n    lib = ReportLib()\n\n    if include_addrs:\n        lib.ShowIpForUnknownSymbol()\n    for file_path in proguard_mapping_file:\n        lib.AddProguardMappingFile(file_path)\n    if symfs_dir is not None:\n        lib.SetSymfs(symfs_dir)\n    if record_file is not None:\n        lib.SetRecordFile(record_file)\n    if kallsyms_file is not None:\n        lib.SetKallsymsFile(kallsyms_file)\n    if sample_filter:\n        lib.SetSampleFilter(sample_filter)\n\n    stacks: DefaultDict[str, int] = defaultdict(int)\n    event_defaulted = False\n    event_warning_shown = False\n    while True:\n        sample = lib.GetNextSample()\n        if sample is None:\n            lib.Close()\n            break\n        if comm_filter:\n            if sample.thread_comm not in comm_filter:\n                continue\n        event = lib.GetEventOfCurrentSample()\n        symbol = lib.GetSymbolOfCurrentSample()\n        callchain = lib.GetCallChainOfCurrentSample()\n        if not event_filter:\n            event_filter = event.name\n            event_defaulted = True\n        elif event.name != event_filter:\n            if event_defaulted and not event_warning_shown:\n                logging.warning(\n                    'Input has multiple event types. Filtering for the first event type seen: %s' %\n                    event_filter)\n                event_warning_shown = True\n            continue\n\n        stack = []\n        for i in range(callchain.nr):\n            entry = callchain.entries[i]\n            func = entry.symbol.symbol_name\n            if annotate_kernel and \"kallsyms\" in entry.symbol.dso_name or \".ko\" in entry.symbol.dso_name:\n                func += '_[k]'  # kernel\n            if annotate_jit and entry.symbol.dso_name == \"[JIT app cache]\":\n                func += '_[j]'  # jit\n            stack.append(func)\n        if include_tid:\n            stack.append(\"%s-%d/%d\" % (sample.thread_comm, sample.pid, sample.tid))\n        elif include_pid:\n            stack.append(\"%s-%d\" % (sample.thread_comm, sample.pid))\n        else:\n            stack.append(sample.thread_comm)\n        stack.reverse()\n        stacks[\";\".join(stack)] += sample.period\n\n    for k in sorted(stacks.keys()):\n        print(\"%s %d\" % (k, stacks[k]))\n\n\ndef main():\n    parser = BaseArgumentParser(description=__doc__)\n    parser.add_argument('--symfs',\n                        help='Set the path to find binaries with symbols and debug info.')\n    parser.add_argument('--kallsyms', help='Set the path to find kernel symbols.')\n    parser.add_argument('-i', '--record_file', nargs='?', default='perf.data',\n                        help='Default is perf.data.')\n    parser.add_argument('--pid', action='store_true', help='Include PID with process names')\n    parser.add_argument('--tid', action='store_true', help='Include TID and PID with process names')\n    parser.add_argument('--kernel', action='store_true',\n                        help='Annotate kernel functions with a _[k]')\n    parser.add_argument('--jit', action='store_true', help='Annotate JIT functions with a _[j]')\n    parser.add_argument('--addrs', action='store_true',\n                        help='include raw addresses where symbols can\\'t be found')\n    parser.add_argument(\n        '--proguard-mapping-file', nargs='+',\n        help='Add proguard mapping file to de-obfuscate symbols',\n        default=[])\n    sample_filter_group = parser.add_argument_group('Sample filter options')\n    parser.add_sample_filter_options(sample_filter_group, False)\n    sample_filter_group.add_argument('--event-filter', nargs='?', default='',\n                                     help='Event type filter e.g. \"cpu-cycles\" or \"instructions\"')\n    sample_filter_group.add_argument('--comm', nargs='+', action='append', help=\"\"\"\n      Use samples only in threads with selected names.\"\"\")\n    args = parser.parse_args()\n    collapse_stacks(\n        record_file=args.record_file,\n        symfs_dir=args.symfs,\n        kallsyms_file=args.kallsyms,\n        proguard_mapping_file=args.proguard_mapping_file,\n        event_filter=args.event_filter,\n        include_pid=args.pid,\n        include_tid=args.tid,\n        annotate_kernel=args.kernel,\n        annotate_jit=args.jit,\n        include_addrs=args.addrs,\n        comm_filter=set(flatten_arg_list(args.comm)),\n        sample_filter=args.sample_filter)\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "src/LightSpeedApp.cpp",
    "content": "#include \"LightSpeedApp.h\"\n#include \"MiniConfig.h\"\n#include \"Cinder/Timeline.h\"\n#include \"cinder/Json.h\"\n#include \"cinder/Utilities.h\"\n\n// TODO: so ugly\nfloat global_min_t = 0;\nfloat global_max_t = 1;\nuint64_t firstFrameTimestamp = 0;\nuint64_t deltaTimestamp = 0;\nuint64_t firstCpuStatTimestamp = 0;\nint pid;\nvector<pair<uint64_t, CpuStat>> mCpuStats;\nvector<CpuConfig> mCpuConfigs;\n\nAppCpuStat::AppCpuStat(const string& line)\n{\n    auto tokens = split(line, ' ');\n    utime = fromString<long int>(tokens[14]);\n    stime = fromString<long int>(tokens[15]);\n    cutime = fromString<long int>(tokens[16]);\n    cstime = fromString<long int>(tokens[17]);\n}\n\nstring getTimestampForFilename()\n{\n    char buffer[256];\n    time_t rawtime;\n    time(&rawtime);\n    tm* timeinfo = localtime(&rawtime);\n\n    strftime(buffer, sizeof(buffer), \"%Y_%b_%d-%H_%M_%S \", timeinfo);\n\n    return string(buffer);\n}\n\nstring perfettoCmdTemplate;\n\nfloat calcCpuUsage(const CpuStat& lhs, const CpuStat& rhs)\n{\n    auto totalTime = rhs.getAll() - lhs.getAll();\n    auto idleTime = rhs.getIdle() - lhs.getIdle();\n    auto usage = (totalTime - idleTime) * 100.0f / totalTime;\n    return usage;\n}\n\nfloat calcAppCpuUsage(const CpuStat& lhs, const CpuStat& rhs, const AppCpuStat& appLhs, const AppCpuStat& appRhs)\n{\n    auto totalTime = rhs.getAll() - lhs.getAll();\n    auto appActiveTime = appRhs.getActiveTime() - appLhs.getActiveTime();\n    auto usage = appActiveTime * mCpuConfigs.size() * 100.0f / totalTime;\n    return usage;\n}\n\n\n#include <windows.h>\n#include <Dbghelp.h>\n#include <shlobj_core.h>\n#include <winerror.h>\n\nvoid goto_folder(fs::path folder, fs::path selectPath)\n{\n    PIDLIST_ABSOLUTE pidl;\n    if (SUCCEEDED(SHParseDisplayName(folder.wstring().c_str(), 0, &pidl, 0, 0)))\n    {\n        // we don't want to actually select anything in the folder, so we pass an empty\n        // PIDL in the array. if you want to select one or more items in the opened\n        // folder you'd need to build the PIDL array appropriately\n\n        if (selectPath.empty())\n        {\n            ITEMIDLIST idNull = { 0 };\n            LPCITEMIDLIST pidlNull[1] = { &idNull };\n            SHOpenFolderAndSelectItems(pidl, 1, pidlNull, 0);\n        }\n        else\n        {\n            ITEMIDLIST* pidlist;\n            SFGAOF aog;\n            SHParseDisplayName(selectPath.wstring().c_str(), NULL, &pidlist, SFGAO_CANCOPY, &aog);//pidlist����ת���Ժ��shell·��\n\n            LPCITEMIDLIST pidlNull[1] = { pidlist };\n            SHOpenFolderAndSelectItems(pidl, 1, pidlNull, 0);\n            ILFree(pidlist);\n        }\n\n        ILFree(pidl);\n    }\n}\n\n\nvoid make_minidump(EXCEPTION_POINTERS* e)\n{\n    auto hDbgHelp = LoadLibraryA(\"dbghelp\");\n    if (hDbgHelp == nullptr)\n        return;\n    auto pMiniDumpWriteDump = (decltype(&MiniDumpWriteDump))GetProcAddress(hDbgHelp, \"MiniDumpWriteDump\");\n    if (pMiniDumpWriteDump == nullptr)\n        return;\n\n    char name[MAX_PATH];\n    {\n        auto nameEnd = name + GetModuleFileNameA(GetModuleHandleA(0), name, MAX_PATH);\n        SYSTEMTIME t;\n        GetSystemTime(&t);\n        wsprintfA(nameEnd - strlen(\".exe\"),\n            \"_%4d%02d%02d_%02d%02d%02d.dmp\",\n            t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond);\n    }\n\n    auto hFile = CreateFileA(name, GENERIC_WRITE, FILE_SHARE_READ, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);\n    if (hFile == INVALID_HANDLE_VALUE)\n        return;\n\n    MINIDUMP_EXCEPTION_INFORMATION exceptionInfo;\n    exceptionInfo.ThreadId = GetCurrentThreadId();\n    exceptionInfo.ExceptionPointers = e;\n    exceptionInfo.ClientPointers = FALSE;\n\n    auto dumped = pMiniDumpWriteDump(\n        GetCurrentProcess(),\n        GetCurrentProcessId(),\n        hFile,\n        MINIDUMP_TYPE(MiniDumpWithIndirectlyReferencedMemory | MiniDumpScanMemory),\n        e ? &exceptionInfo : nullptr,\n        nullptr,\n        nullptr);\n\n    CloseHandle(hFile);\n\n    return;\n}\n\nLONG CALLBACK unhandled_handler(EXCEPTION_POINTERS* e)\n{\n    make_minidump(e);\n    return EXCEPTION_CONTINUE_SEARCH;\n}\n\nint runCmd(const string& cmd, std::string& outOutput, bool waitForCompletion)\n{\n    CI_LOG_W(cmd);\n\n    HANDLE g_hChildStd_OUT_Rd = NULL;\n    HANDLE g_hChildStd_OUT_Wr = NULL;\n    HANDLE g_hChildStd_ERR_Rd = NULL;\n    HANDLE g_hChildStd_ERR_Wr = NULL;\n\n    SECURITY_ATTRIBUTES sa;\n    // Set the bInheritHandle flag so pipe handles are inherited.\n    sa.nLength = sizeof(SECURITY_ATTRIBUTES);\n    sa.bInheritHandle = TRUE;\n    sa.lpSecurityDescriptor = NULL;\n    if (!CreatePipe(&g_hChildStd_ERR_Rd, &g_hChildStd_ERR_Wr, &sa, 0)) { return 1; } // Create a pipe for the child process's STDERR.\n    if (!SetHandleInformation(g_hChildStd_ERR_Rd, HANDLE_FLAG_INHERIT, 0)) { return 1; } // Ensure the read handle to the pipe for STDERR is not inherited.\n    if (!CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &sa, 0)) { return 1; } // Create a pipe for the child process's STDOUT.\n    if (!SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)) { return 1; } // Ensure the read handle to the pipe for STDOUT is not inherited\n\n    PROCESS_INFORMATION piProcInfo;\n    STARTUPINFOA siStartInfo;\n    bool bSuccess = FALSE;\n\n    // Set up members of the PROCESS_INFORMATION structure.\n    ZeroMemory(&piProcInfo, sizeof(PROCESS_INFORMATION));\n\n    // Set up members of the STARTUPINFO structure.\n    // This structure specifies the STDERR and STDOUT handles for redirection.\n    ZeroMemory(&siStartInfo, sizeof(STARTUPINFOA));\n    siStartInfo.cb = sizeof(STARTUPINFOA);\n    siStartInfo.hStdError = g_hChildStd_ERR_Wr;\n    siStartInfo.hStdOutput = g_hChildStd_OUT_Wr;\n    siStartInfo.dwFlags |= STARTF_USESTDHANDLES;\n\n    // Create the child process.\n    bSuccess = CreateProcessA(\n        NULL,             // program name\n        (char*)cmd.c_str(),       // command line\n        NULL,             // process security attributes\n        NULL,             // primary thread security attributes\n        TRUE,             // handles are inherited\n        CREATE_NO_WINDOW, // creation flags (this is what hides the window)\n        NULL,             // use parent's environment\n        NULL,             // use parent's current directory\n        &siStartInfo,     // STARTUPINFO pointer\n        &piProcInfo       // receives PROCESS_INFORMATION\n    );\n\n    CloseHandle(g_hChildStd_ERR_Wr);\n    CloseHandle(g_hChildStd_OUT_Wr);\n\n    if (waitForCompletion)\n    {\n        // read output\n    #define BUFSIZE 4096\n        DWORD dwRead;\n        CHAR chBuf[BUFSIZE];\n        bool bSuccess2 = FALSE;\n        for (;;) { // read stdout\n            bSuccess2 = ReadFile(g_hChildStd_OUT_Rd, chBuf, BUFSIZE, &dwRead, NULL);\n            if (!bSuccess2 || dwRead == 0) break;\n            std::string s(chBuf, dwRead);\n            outOutput += s;\n        }\n        dwRead = 0;\n        for (;;) { // read stderr\n            bSuccess2 = ReadFile(g_hChildStd_ERR_Rd, chBuf, BUFSIZE, &dwRead, NULL);\n            if (!bSuccess2 || dwRead == 0) break;\n            std::string s(chBuf, dwRead);\n            outOutput += s;\n        }\n    }\n\n    CloseHandle(g_hChildStd_OUT_Rd);\n    CloseHandle(g_hChildStd_ERR_Rd);\n\n    CI_LOG_W(outOutput);\n\n    // The remaining open handles are cleaned up when this process terminates.\n    // To avoid resource leaks in a larger application,\n    // close handles explicitly.\n    return 0;\n}\n\n\nvector<string> PerfDoctorApp::executeIdb(string cmd, bool async, bool oneDeviceOnly)\n{\n    char fullCmd[256];\n    if (oneDeviceOnly)\n        sprintf(fullCmd, \"tidevice -u %s %s\", mSerialNames[DEVICE_ID].c_str(), cmd.c_str());\n    else\n        sprintf(fullCmd, \"tidevice %s\", cmd.c_str());\n\n#if 1\n    fp_idb = nullptr;\n    fp_idb = _popen(fullCmd, \"r\");  // Open the command for reading.\n    if (fp_idb == NULL) {\n        return {};\n    }\n#else\n    string result;\n    runCmd(fullCmd, result);\n    if (result.empty()) return {};\n    auto lines = split(result, \"\\r\\n\");\n    if (lines[lines.size() - 1].empty())\n        lines.pop_back();\n    return lines;\n#endif\n}\n\nvoid PerfDoctorApp::executeUnrealCmd(const string& cmd)\n{\n    char str[256];\n    sprintf(str, \"shell am broadcast -a android.intent.action.RUN -e cmd '%s'\", cmd.c_str());\n    executeAdb(str);\n    if (cmd.find(\"memreport\") != string::npos)\n        getMemReport();\n    if (cmd.find(\"dumpticks\") != string::npos)\n        getDumpTicks();\n}\n\nvector<string> PerfDoctorApp::executeAdb(string cmd, bool oneDeviceOnly)\n{\n    static bool init = true;\n    static string adbExe = \"adb\";\n    if (init)\n    {\n        init = false;\n        string result;\n        runCmd(\"where adb\", result);\n        if (result.find(\"adb\") == string::npos)\n            adbExe = (getAppPath() / \"adb\" / \"adb.exe\").string();\n    }\n    char fullCmd[256];\n    if (oneDeviceOnly)\n        sprintf(fullCmd, \"%s -s %s %s\", adbExe.c_str(), mSerialNames[DEVICE_ID].c_str(), cmd.c_str());\n    else\n        sprintf(fullCmd, \"%s %s\", adbExe.c_str(), cmd.c_str());\n\n    string result;\n    runCmd(fullCmd, result);\n    if (result.empty()) return {};\n    auto lines = split(result, \"\\r\\n\");\n    if (lines[lines.size() - 1].empty())\n        lines.pop_back();\n    return lines;\n}\n\n\nbool PerfDoctorApp::refreshDeviceNames()\n{\n    mSerialNames.clear();\n    mDeviceNames.clear();\n    mTemparatureStatSlot = { \"\",\"\", \"\" };\n\n    char cmd[256];\n\n    auto adbDeviceResults = executeAdb(\"devices\", false);\n\n    for (int i = 1; i < adbDeviceResults.size(); i++)\n    {\n        auto tokens = split(adbDeviceResults[i], '\\t');\n        if (tokens.size() < 2) continue;\n\n        if (tokens[1] != \"device\")\n        {\n#if 1\n            ::MessageBoxA(NULL, \"Device is unauthorized\", tokens[0].c_str(), MB_OK);\n#else\n            dispatchAsync([] {\n                ImGui::OpenPopup(\"Device is unauthorized\");\n\n                // Always center this window when appearing\n                ImVec2 center(ImGui::GetIO().DisplaySize.x * 0.5f, ImGui::GetIO().DisplaySize.y * 0.5f);\n                ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));\n\n                if (ImGui::BeginPopupModal(\"Device is unauthorized\", NULL, ImGuiWindowFlags_AlwaysAutoResize))\n                {\n                    ImGui::Text(\"Please authorize it first.\\n\");\n                    ImGui::Separator();\n\n                    if (ImGui::Button(\"OK\", ImVec2(120, 0))) { ImGui::CloseCurrentPopup(); }\n                    ImGui::SetItemDefaultFocus();\n                    ImGui::EndPopup();\n                }\n            });\n#endif\n            continue;\n        }\n\n        auto serial = tokens[0];\n\n        mSerialNames.push_back(serial);\n\n        sprintf(cmd, \"-s %s shell getprop ro.product.model\", serial.c_str());\n        auto modelResults = executeAdb(cmd, false);\n\n        if (serial.find(\":5555\") != string::npos)\n            mDeviceNames.push_back(modelResults[0] + \" [wifi]\");\n        else\n            mDeviceNames.push_back(modelResults[0]);\n        mIsIOSDevices.push_back(false);\n    }\n\n    int serialCount = mSerialNames.size();\n    for (int i = 0; i < serialCount; i++)\n    {\n        if (mSerialNames[i].find(\":5555\") != string::npos)\n        {\n            continue;\n        }\n\n        sprintf(cmd, \"-s %s shell \\\"ip addr show wlan0 | grep -e wlan0$ | cut -d\\\\\\\" \\\\\\\" -f 6 | cut -d/ -f 1\\\"\", mSerialNames[i].c_str());\n        auto ipResults = executeAdb(cmd, false);\n        if (ipResults.empty()) continue;\n\n        auto ipAddress = ipResults[0];\n        int idx = 0;\n        bool connected = false;\n        for (const auto& name : mSerialNames)\n        {\n            if (name.find(ipAddress) != string::npos)\n            {\n                connected = true;\n                break;\n            }\n            idx++;\n        }\n        if (!connected)\n        {\n            mSerialNames.push_back(ipAddress);\n            mDeviceNames.push_back(mDeviceNames[i] + \" [wifi]\");\n            mIsIOSDevices.push_back(false);\n        }\n    }\n\n#if 0\n    auto idbDeviceResults = executeIdb(\"list\", false, false);\n    for (int i = 0; i < idbDeviceResults.size(); i++)\n    {\n        auto tokens = split(idbDeviceResults[i], '\\t');\n        if (tokens.size() < 3) continue;\n\n        mSerialNames.push_back(tokens[0]);\n        mDeviceNames.push_back(tokens[1] + \" [iOS]\");\n        mIsIOSDevices.push_back(true);\n    }\n#endif\n\n    if (mSerialNames.empty())\n        DEVICE_ID = -1;\n    else\n    {\n        // TODO: ugly\n        if (DEVICE_ID == -1 || DEVICE_ID >= mSerialNames.size())\n            DEVICE_ID = 0;\n    }\n\n    return true;\n}\n\nbool PerfDoctorApp::refreshDeviceDetails_ios()\n{\n    storage.metric_storage[\"frame_time\"].visible = false;\n    storage.metric_storage[\"cpu_usage\"].visible = false;\n    storage.metric_storage[\"core_usage\"].visible = false;\n    storage.metric_storage[\"memory_usage\"].visible = false;\n    storage.metric_storage[\"core_freq\"].visible = false;\n    storage.metric_storage[\"temperature\"].visible = false;\n\n    auto lines = executeIdb(\"-c applist\");\n    for (auto& line : lines)\n    {\n        auto tokens = split(line, '\\t');\n        const auto& appName = tokens[0];\n\n        mAppNames.push_back(appName);\n    }\n    sort(mAppNames.begin(), mAppNames.end());\n\n    if (!APP_NAME.empty())\n    {\n        int idx = 0;\n        for (auto& name : mAppNames)\n        {\n            if (name == APP_NAME)\n            {\n                mAppId = idx;\n                break;\n            }\n            idx++;\n        }\n    }\n\n    lines = executeIdb(\"info\");\n    {\n        for (auto& line : lines)\n        {\n            auto tokens = split(line, \":\\t\");\n            auto key = tokens[0];\n            auto value = tokens[1];\n            if (key == \"MarketName\")\n                mDeviceStat.market_name = value;\n            else if (key == \"ProductVersion\")\n                mDeviceStat.os_version = \"iOS \" + value;\n        }\n    }\n\n    return true;\n}\n\nbool PerfDoctorApp::refreshDeviceDetails()\n{\n    mAppNames.clear();\n    mIsProfiling = false;\n    mAppId = -1;\n\n    mCpuConfigs.clear();\n\n    if (DEVICE_ID == -1) return true;\n\n    storage.metric_storage[\"fps\"].visible = fps_visible;\n\n    if (mIsIOSDevices[DEVICE_ID]) return refreshDeviceDetails_ios();\n\n    storage.metric_storage[\"frame_time\"].visible = frame_time_visible;\n    storage.metric_storage[\"cpu_usage\"].visible = cpu_usage_visible;\n    storage.metric_storage[\"core_usage\"].visible = core_usage_visible;\n    storage.metric_storage[\"memory_usage\"].visible = memory_usage_visible;\n    storage.metric_storage[\"core_freq\"].visible = core_freq_visible;\n    storage.metric_storage[\"temperature\"].visible = temperature_visible;\n\n    if (count(mSerialNames[DEVICE_ID].begin(), mSerialNames[DEVICE_ID].end(), '.') == 3)\n    {\n        // if ip address\n        char cmd[256];\n        if (mSerialNames[DEVICE_ID].find(\":5555\") == string::npos)\n        {\n            // connect if not already connected\n            sprintf(cmd, \"-s %s tcpip 5555\", mSerialNames[DEVICE_ID - 1].c_str());\n            auto tcpipResults = executeAdb(cmd, false);\n\n            sprintf(cmd, \"connect %s\", mSerialNames[DEVICE_ID].c_str());\n            auto connectResults = executeAdb(cmd, false);\n            mSerialNames[DEVICE_ID] += \":5555\";\n        }\n    }\n    auto lines = executeAdb(\"shell cat /proc/cpuinfo\");\n    for (auto& line : lines)\n    {\n        auto tokens = split(line, \"\\t:\");\n        if (tokens.size() != 2) continue;\n\n        const auto& key = tokens[0];\n        const auto& value = tokens[1];\n        if (key == \"processor\")\n        {\n            mCpuConfigs.push_back({});\n            mCpuConfigs.back().id = mCpuConfigs.size() - 1;\n        }\n        if (key == \"Features\")\n        {\n            mCpuConfigs.back().features = value;\n        }\n        if (key == \"CPU implementer\")\n        {\n            auto src = stoi(value, 0, 16);\n            string name = value;\n            switch (src)\n            {\n            case 'A': name = \"arm\"; break;\n            case 'B': name = \"broadcom\"; break;\n            case 'C': name = \"cavium\"; break;\n            case 'H': name = \"huawei\"; break;\n            case 'i': name = \"intel\"; break;\n            case 'N': name = \"nvidia\"; break;\n            case 'P': name = \"apm\"; break;\n            case 'Q': name = \"qualcomm\"; break;\n            case 'S': name = \"samsung\"; break;\n            case 'V': name = \"marvell\"; break;\n            }\n            mCpuConfigs.back().implementer = name;\n        }\n        if (key == \"CPU architecture\") mCpuConfigs.back().architecture = value;\n        if (key == \"CPU variant\") mCpuConfigs.back().variant = value;\n        if (key == \"CPU part\")\n        {\n            auto src = stoi(value, 0, 16);\n            string name = value;\n            switch (src)\n            {\n                // huawei\n            case 0xD40: name = \"Cortex-A76 Big/Medium cores\"; break;\n                // arm\n            case 0xC05: name = \"Cortex-A5\"; break;\n            case 0xC07: name = \"Cortex-A7\"; break;\n            case 0xC08: name = \"Cortex-A8\"; break;\n            case 0xC09: name = \"Cortex-A9\"; break;\n            case 0xC0C: name = \"Cortex-A12\"; break;\n            case 0xC0E: name = \"Cortex-A17\"; break;\n            case 0xC0D: name = \"Cortex-A12\"; break;\n            case 0xC0F: name = \"Cortex-A15\"; break;\n            case 0xD01: name = \"Cortex-A32\"; break;\n            case 0xD03: name = \"Cortex-A53\"; break;\n            case 0xD04: name = \"Cortex-A35\"; break;\n            case 0xD05: name = \"Cortex-A55\"; break;\n            case 0xD06: name = \"Cortex-A65\"; break;\n            case 0xD07: name = \"Cortex-A57\"; break;\n            case 0xD08: name = \"Cortex-A72\"; break;\n            case 0xD09: name = \"Cortex-A73\"; break;\n            case 0xD0A: name = \"Cortex-A75\"; break;\n            case 0xD0B: name = \"Cortex-A76\"; break;\n            case 0xD0C: name = \"Neoverse-N1\"; break;\n            case 0xD0D: name = \"Cortex-A77\"; break;\n            case 0xD0E: name = \"Cortex-A76\"; break;\n            case 0xD41: name = \"Cortex-A78\"; break;\n            case 0xD44: name = \"Cortex-x1\"; break;\n            case 0xD4A: name = \"Neoverse-E1\"; break;\n                // qualcomm\n            case 0x00F: name = \"Cortex-A5\"; break;\n            case 0x02D: name = \"Scorpion\"; break;\n            case 0x04D: name = \"Dual-core Krait\"; break;\n            case 0x06F: name = \"Quad-core Krait\"; break;\n            case 0x201: name = \"Low-power Kryo\"; break;\n            case 0x205: name = \"High-perf Kryo\"; break;\n            case 0x211: name = \"Low-power Kryo\"; break;\n            case 0x800: name = \"Cortex-A73 High-perf Kryo\"; break;\n            case 0x801: name = \"Cortex-A53 Low-power Kryo\"; break;\n            case 0x802: name = \"Cortex-A75 High-perf Kryo\"; break;\n            case 0x803: name = \"Cortex-A55r0 Low-power Kryo\"; break;\n            case 0x804: name = \"Cortex-A76 High-perf Kryo\"; break;\n            case 0x805: name = \"Cortex-A55 Low-power Kryo\"; break;\n            case 0xC00: name = \"Falkor\"; break;\n            case 0xC01: name = \"Saphira\"; break;\n            }\n            mCpuConfigs.back().part = name;\n        }\n        if (key == \"CPU revision\") mCpuConfigs.back().revision = value;\n        if (key == \"Hardware\") mDeviceStat.hardware = value;\n    }\n\n    {\n        auto lines = executeAdb(\"shell cat /sys/devices/system/cpu/cpu*/cpufreq/cpuinfo_min_freq\");\n        for (int i = 0; i < lines.size(); i++)\n            mCpuConfigs[i].cpuinfo_min_freq = stoi(lines[i]);\n\n        lines = executeAdb(\"shell cat /sys/devices/system/cpu/cpu*/cpufreq/cpuinfo_max_freq\");\n        for (int i = 0; i < lines.size(); i++)\n            mCpuConfigs[i].cpuinfo_max_freq = stoi(lines[i]);\n    }\n\n    {\n        // gpu name\n        lines = executeAdb(\"shell \\\"dumpsys SurfaceFlinger | grep GLES\\\"\");\n        if (!lines.empty())\n        {\n            auto tokens = split(lines[0], ',');\n            if (tokens.size() > 2)\n                mDeviceStat.gpu_name = tokens[1];\n        }\n    }\n\n    {\n        auto thermalFiles = executeAdb(\"shell ls /sys/devices/virtual/thermal/thermal_zone*/temp\");\n\n        auto lines = executeAdb(\"shell cat /sys/devices/virtual/thermal/thermal_zone*/type\");\n        for (int i = 0; i < lines.size(); i++)\n        {\n            if (mTemparatureStatSlot.cpu.empty() && (\n                lines[i].find(\"cpuss-\") != string::npos\n                || lines[i].find(\"soc_thermal\") != string::npos\n                ))\n                mTemparatureStatSlot.cpu = thermalFiles[i];\n            if (mTemparatureStatSlot.gpu.empty() && lines[i].find(\"gpuss-\") != string::npos)\n                mTemparatureStatSlot.gpu = thermalFiles[i];\n\n            if (mTemparatureStatSlot.battery.empty() && (\n                lines[i].find(\"battery\") != string::npos\n                || lines[i].find(\"Battery\") != string::npos\n                ))\n                mTemparatureStatSlot.battery = thermalFiles[i];\n        }\n    }\n\n    if (LIST_ALL_APP)\n        lines = executeAdb(\"shell pm list packages\");\n    else\n        lines = executeAdb(\"shell pm list packages -3\");\n    for (auto& line : lines)\n    {\n        auto tokens = split(line, ':');\n        const auto& appName = tokens[1];\n#if 0\n        bool appToIgnore = false;\n        const string igoredApps[] = {\n            \"com.android.\",\n            \"com.google.\",\n\n            \"org.lineageos.\",\n\n            \"com.qualcomm.\",\n            \".qti.\",\n\n            \"com.samsung.\",\n\n            \"com.vivo.\",\n            \"com.bbk.\",\n            \"com.iqoo.\",\n\n            \"com.oppo.\",\n            \"com.color.\",\n            \"com.coloros.\",\n            \"com.oplus.\",\n            \"com.heytap.\",\n\n            \"com.mi.\",\n            \"miui.\",\n            \"com.xiaomi.\",\n\n            \"com.huawei.\",\n        };\n        for (auto& keyword : igoredApps)\n        {\n            if (appName.find(keyword) != string::npos)\n            {\n                appToIgnore = true;\n                break;\n            }\n        }\n        if (appToIgnore) continue;\n#endif\n        mAppNames.push_back(appName);\n    }\n    sort(mAppNames.begin(), mAppNames.end());\n\n    if (!APP_NAME.empty())\n    {\n        int idx = 0;\n        for (auto& name : mAppNames)\n        {\n            if (name == APP_NAME)\n            {\n                mAppId = idx;\n                break;\n            }\n            idx++;\n        }\n    }\n\n    lines = executeAdb(\"shell getprop ro.build.version.release\");\n    if (!lines.empty())\n        mDeviceStat.os_version = \"Android \" + lines[0];\n\n#if 0\n    lines = executeAdb(\"shell getprop persist.sys.rog.width\");\n    if (!lines.empty())\n        mDeviceStat.width = stoi(lines[0]);\n\n    lines = executeAdb(\"shell getprop persist.sys.rog.height\");\n    if (!lines.empty())\n        mDeviceStat.height = stoi(lines[0]);\n#endif\n\n    lines = executeAdb(\"shell getprop ro.opengles.version\");\n    if (!lines.empty())\n    {\n        int version = stoi(lines[0]);\n        if (version == 65535) mDeviceStat.gfx_api_version = \"OpenGL ES 1.0\";\n        else if (version == 65536) mDeviceStat.gfx_api_version = \"OpenGL ES 1.1\";\n        else if (version == 131072) mDeviceStat.gfx_api_version = \"OpenGL ES 2.0\";\n        else if (version == 196608) mDeviceStat.gfx_api_version = \"OpenGL ES 3.0\";\n        else if (version == 196609) mDeviceStat.gfx_api_version = \"OpenGL ES 3.1\";\n        else if (version == 196610) mDeviceStat.gfx_api_version = \"OpenGL ES 3.2\";\n    }\n\n    //lines = executeAdb(\"shell getprop ro.hardware\");\n    //if (!lines.empty())\n    //    mDeviceStat.hardware = lines[0];\n\n    lines = executeAdb(\"shell \\\"dumpsys SurfaceFlinger | grep cur:\\\"\");\n    if (!lines.empty())\n    {\n        auto tokens = split(lines[0], \": \");\n        mDeviceStat.fps_min = fromString<int>(tokens[2]);\n        mDeviceStat.fps_max = fromString<int>(tokens[4]);\n        mDeviceStat.fps_now = fromString<int>(tokens[6]);\n    }\n\n    lines = executeAdb(\"shell \\\"dumpsys SurfaceFlinger | grep WxH\\\"\");\n    if (!lines.empty())\n    {\n        auto tokens = split(lines[0], \": \");\n        mDeviceStat.display_WxH = tokens[2];\n    }\n\n    return true;\n}\n\nbool PerfDoctorApp::startProfiler_ios(const string& pacakgeName)\n{\n    //-o=cpu,memory,fps\n    char cmd[256];\n    sprintf(cmd, \"perf -B %s -o=fps\", pacakgeName.c_str());\n    auto perfResults = executeIdb(cmd);\n\n    return true;\n}\n\nbool PerfDoctorApp::capturePerfetto()\n{\n    if (!fs::exists(getAppPath() / \"p.cfg\"))\n    {\n        // create a placeholder one if missing\n        ofstream ofs(getAppPath() / \"p.cfg\");\n        if (ofs.is_open())\n            ofs << perfettoCmdTemplate;\n    }\n\n    auto ts = getTimestampForFilename();\n    string name = APP_NAME + \"-\" + ts;\n    mAsyncCommands.pushFront((getAppPath() / \"capture-perfetto.bat\").string() + \" \" + name);\n    mAsyncCommands.pushFront((getAppPath() / \"screenshot.bat\").string() + \" \" + name + \" hide_screenshot\");\n    return true;\n}\n\nbool PerfDoctorApp::captureSimpleperf()\n{\n    auto ts = getTimestampForFilename();\n\n    mAsyncCommands.pushFront((getAppPath() / \"..\" / \"SimplePerf\" / \"run.bat\").string() + \" \" + APP_NAME);\n    return true;\n}\n\n\nbool PerfDoctorApp::screenshot()\n{\n    auto ts = getTimestampForFilename();\n    string name = APP_NAME + \"-\" + ts;\n    mAsyncCommands.pushFront((getAppPath() / \"screenshot.bat\").string() + \" \" + name);\n    return true;\n}\n\nvoid PerfDoctorApp::exportGpuTrace()\n{\n    auto ts = getTimestampForFilename();\n    string name = mAppNames[mAppId] + ts + \".gpu.json\";\n    Json tree;\n\n    writeJson(getAppPath() / name, tree);\n}\n\nbool PerfDoctorApp::exportCsv()\n{\n    auto ts = getTimestampForFilename();\n    string name = mAppNames[mAppId] + \"-\" + ts + \".csv\";\n    FILE* fp = fopen((getAppPath() / name).string().c_str(), \"w\");\n    if (!fp) return false;\n\n    {\n        fprintf(fp, \"%s,%s\\n\",\n            ts.c_str(), mPackageName.c_str());\n        fprintf(fp, \"\\n\");\n    }\n\n    {\n        fprintf(fp, \"DeviceInfo\\n\");\n        fprintf(fp, \"Device Name,OS,OpenGL,SerialNum,CPU Info, GPU\\n\"\n            \"%s,%s,%s,%s,%s,%s\\n\",\n            mDeviceNames[DEVICE_ID].c_str(),\n            mDeviceStat.os_version.c_str(),\n            mDeviceStat.gfx_api_version.c_str(),\n            mSerialNames[DEVICE_ID].c_str(),\n            mDeviceStat.hardware.c_str(),\n            mDeviceStat.gpu_name.c_str()\n        );\n        fprintf(fp, \"\\n\");\n    }\n\n    {\n        fprintf(fp, \"Avg(FPS),Avg(Memory)[MB],Peak(Memory)[MB]\\n\"\n            \"%.1f,%.0f,%.0f\\n\",\n            mFpsSummary.Avg,\n            mMemorySummary.Avg,\n            mMemorySummary.Max);\n        fprintf(fp, \"\\n\");\n    }\n\n    {\n        fprintf(fp, \"Num,FPS,\");\n\n        if (storage.metric_storage[\"memory_usage\"].visible)\n        {\n            fprintf(fp, \"Memory[MB],NativePss[MB],\"\n                \"Gfx[MB],EGL[MB],GL[MB],Unknown[MB],\"\n                \"PrivateClean[MB],PrivateDirty[MB],\");\n        }\n        if (storage.metric_storage[\"temperature\"].visible)\n            fprintf(fp, \"CpuTemp,GpuTemp,BatteryTemp,\");\n\n        if (storage.metric_storage[\"core_freq\"].visible)\n        {\n            for (int i = 0; i < mCpuConfigs.size(); i++)\n                fprintf(fp, \"CPUClock%d[MHz],\", i);\n        }\n        if (storage.metric_storage[\"core_usage\"].visible)\n        {\n            for (int i = 0; i < mCpuConfigs.size(); i++)\n                fprintf(fp, \"CPUUsage%d[%%],\", i);\n        }\n        fprintf(fp, \"\\n\");\n\n        int memory_count = min<int>(mFpsArray.size(), mMemoryStats.size());\n        int fps_offset = mFpsArray.size() - memory_count;\n        for (int i = 0; i < memory_count - 1; i++)\n        {\n            const auto& memStat = mMemoryStats[i].second;\n            fprintf(fp, \"%d,%.1f,\",\n                i, mFpsArray[fps_offset + i].second);\n            if (storage.metric_storage[\"memory_usage\"].visible)\n            {\n                fprintf(fp, \"%.0f,%.0f,\"\n                    \"%.0f,%.0f,%.0f,%.0f,\"\n                    \"%.0f,%.0f,\",\n                    memStat.pssTotal, memStat.pssNativeHeap,\n                    memStat.pssGfx, memStat.pssEGL, memStat.pssGL, memStat.pssUnknown,\n                    memStat.privateClean, memStat.privateDirty);\n            }\n\n            if (storage.metric_storage[\"temperature\"].visible)\n            {\n                if (!mTemperatureStats.empty())\n                {\n                    fprintf(fp, \"%.1f,%.1f,%.1f,\",\n                        max<float>(mTemperatureStats[i].second.cpu, 0),\n                        max<float>(mTemperatureStats[i].second.gpu, 0),\n                        max<float>(mTemperatureStats[i].second.battery, 0));\n                }\n                else\n                {\n                    fprintf(fp, \"0,0,0,\");\n                }\n            }\n\n            if (storage.metric_storage[\"core_freq\"].visible)\n            {\n                for (int k = 0; k < mCpuConfigs.size(); k++)\n                {\n                    if (i < mChildCpuStats[k].size())\n                        fprintf(fp, \"%.0f,\", max<float>(mChildCpuStats[k][i].second.freq * 1e-3, 0));\n                    else\n                        fprintf(fp, \"0,\");\n                }\n            }\n            if (storage.metric_storage[\"core_usage\"].visible)\n            {\n                for (int k = 0; k < mCpuConfigs.size(); k++)\n                {\n                    if (i < mChildCpuStats[k].size())\n                        fprintf(fp, \"%.0f,\", calcCpuUsage(mChildCpuStats[k][i].second, mChildCpuStats[k][i + 1].second));\n                    else\n                        fprintf(fp, \"0,\");\n                }\n            }\n\n            fprintf(fp, \"\\n\");\n        }\n        fprintf(fp, \"\\n\");\n    }\n\n    fclose(fp);\n\n    return true;\n}\n\nvoid PerfDoctorApp::trimMemory(const char* level)\n{\n    char cmd[256];\n    sprintf(cmd, \"shell am send-trim-memory %s %s\", mAppNames[mAppId].c_str(), level);\n    auto lines = executeAdb(cmd);\n}\n\nbool PerfDoctorApp::startProfiler(const string& pacakgeName)\n{\n    if (mIsIOSDevices[DEVICE_ID]) return startProfiler_ios(pacakgeName);\n\n    string perfettoCmd = perfettoCmdTemplate;\n    perfettoCmd.replace(perfettoCmd.find(\"ATRACE_APP_NAME\"), strlen(\"ATRACE_APP_NAME\"), pacakgeName);\n    ofstream ofs(getAppPath() / \"p.cfg\");\n    if (ofs.is_open())\n        ofs << perfettoCmd;\n\n    char cmd[256];\n    mSurfaceViewName = \"\";\n    mSurfaceResolution = \"\";\n    mPackageName = pacakgeName;\n    pid = getPid(pacakgeName);\n\n    mFpsSummary.Min = FLT_MAX;\n    mMemorySummary.Min = FLT_MAX;\n    mAppCpuSummary.Min = FLT_MAX;\n    mCpuTempSummary.Min = FLT_MAX;\n    mFrameTimeSummary.Min = FLT_MAX;\n\n    auto lines = executeAdb(\"shell dumpsys SurfaceFlinger --list\");\n    for (auto& line : lines)\n    {\n        if (line.find(\"SurfaceView\") != 0) continue;\n        if (line.find(pacakgeName) == string::npos) continue;\n\n        if (mSurfaceViewName.empty() || line.find(\"BLAST\") != 0)\n            mSurfaceViewName = line;\n        CI_LOG_W(\"Found SurfaceView:\" << mSurfaceViewName);\n\n        //executeAdb(\"shell dumpsys SurfaceFlinger --latency-clear\");\n\n        //break;\n        // TODO: support multi-surface view\n    }\n\n    if (!mSurfaceViewName.empty())\n    {\n        sprintf(cmd, \"shell \\\"dumpsys SurfaceFlinger | grep \\'%s\\'\\\"\", mSurfaceViewName.c_str());\n        lines = executeAdb(cmd);\n        for (auto& line : lines)\n        {\n            // 0x7215e95c50: 4680.00 KiB |  720 ( 768) x 1560 |    1 |        2 | 0x10000900 | SurfaceView - com.xx.yy/com.epicgames.ue4.GameActivity#0\n            auto tokens = split(line, '|');\n            if (tokens.size() == 6)\n            {\n                mSurfaceResolution = trim(tokens[1]);\n            }\n        }\n    }\n\n    mIsProfiling = true;\n\n    return true;\n}\n\nvoid PerfDoctorApp::resetPerfData()\n{\n    AdbResults results;\n    while (mAdbResults.tryPopBack(&results))\n    {\n    }\n\n    mLastSnapshotTs = 0;\n    mLastSnapshotIdx = 0;\n    firstCpuStatTimestamp = 0;\n    firstFrameTimestamp = 0;\n    mMemoryStats.clear();\n    mTimestamps.clear();\n    mFrameTimes.clear();\n    mFpsArray.clear();\n    mCpuStats.clear();\n    mAppCpuStats.clear();\n    for (auto& item : mChildCpuStats)\n        item.clear();\n\n    mFpsSummary.reset();\n    mMemorySummary.reset();\n    mAppCpuSummary.reset();\n    mCpuTempSummary.reset();\n    mFrameTimeSummary.reset();\n\n    mTemperatureStats.clear();\n\n    mLabelPairs.clear();\n}\n\nbool PerfDoctorApp::stopProfiler()\n{\n    mIsProfiling = false;\n\n    resetPerfData();\n\n    return true;\n}\n\nbool PerfDoctorApp::updateProfiler(const AdbResults& results)\n{\n    {\n        // frame time\n        uint64_t prevMaxTimestamp = 0;\n        if (!mTimestamps.empty())\n            prevMaxTimestamp = mTimestamps[mTimestamps.size() - 1];\n\n        // adb shell dumpsys SurfaceFlinger --latency <window name>\n        // prints some information about the last 128 frames displayed in\n        // that window.\n        // The data returned looks like this:\n        // 16954612\n        // 7657467895508   7657482691352   7657493499756\n        // 7657484466553   7657499645964   7657511077881\n        // 7657500793457   7657516600576   7657527404785\n        // (...)\n        //\n        // The first line is the refresh period (here 16.95 ms), it is followed\n        // by 128 lines w/ 3 timestamps in nanosecond each:\n        // A) when the app started to draw\n        // B) the vsync immediately preceding SF submitting the frame to the h/w\n        // C) timestamp immediately after SF submitted that frame to the h/w\n        //\n        // The difference between the 1st and 3rd timestamp is the frame-latency.\n        // An interesting data is when the frame latency crosses a refresh period\n        // boundary, this can be calculated this way:\n        //\n        // ceil((C - A) / refresh-period)\n        //\n        // (each time the number above changes, we have a \"jank\").\n        // If this happens a lot during an animation, the animation appears\n        // janky, even if it runs at 60 fps in average.\n        //\n        // We use the special \"SurfaceView\" window name because the statistics for\n        // the activity's main window are not updated when the main web content is\n        // composited into a SurfaceView.\n\n        vector<TripleTimestamp> timestamps;\n\n        auto lines = results.SurfaceFlinger_latency;\n        for (int i = 1; i < lines.size(); i++)\n        {\n            auto& tokens = split(lines[i], '\\t');\n            if (tokens.size() < 3) continue; // it happens sometimes\n            if (tokens[0][0] == '0') continue;\n            timestamps.push_back({ tokens[0], tokens[1], tokens[2] });\n        }\n\n        if (lines.empty())\n        {\n            // https://developer.android.com/training/testing/performance\n            lines = results.dumpsys_gfxinfo;\n            bool find_app = false;\n            bool find_timestamps = false;\n            for (int i = 0; i < lines.size(); i++)\n            {\n                auto& line = lines[i];\n                if (find_timestamps)\n                {\n                    if (line.find(\"---PROFILEDATA---\") != string::npos)\n                        // reach end of timestamp section\n                        break;\n\n                    auto& tokens = split(line, ',');\n                    if (fromString<uint64_t>(tokens[0]) != 0)\n                        // this frame is an outlier, skip it\n                        continue;\n\n                    // ��ȡINTENDED_VSYNC VSYNC FRAME_COMPLETEDʱ�� ����VSYNC����fps jank\n                    timestamps.push_back({ tokens[1], tokens[2], tokens[13] });\n                }\n                if (line.find(mPackageName) != string::npos)\n                    find_app = true;\n                if (find_app && line.find(\"Flags,IntendedVsync\") != string::npos)\n                    find_timestamps = true;\n            }\n        }\n\n        for (const auto& triple : timestamps)\n        {\n            auto ts = fromString<uint64_t>(triple.frame_submitted);\n            if (ts == INT64_MAX)\n            {\n                // If a fence associated with a frame is still pending when we query the\n                // latency data, SurfaceFlinger gives the frame a timestamp of INT64_MAX.\n                // Since we only care about completed frames, we will ignore any timestamps\n                // with this value.\n                continue;\n            }\n            ts /= 1e6; // ns -> ms\n            if (ts <= prevMaxTimestamp) // duplicated timestamps\n                continue;\n            if (mLastSnapshotTs == 0)\n            {\n                mLastSnapshotTs = ts;\n                mLastSnapshotIdx = 0;\n            }\n            if (ts - mLastSnapshotTs >= 1000)\n            {\n                // calculate fps\n                float frameCount = (mTimestamps.size() - mLastSnapshotIdx) * 1000.0f / (ts - mLastSnapshotTs);\n\n                mFpsSummary.update(frameCount, mFpsArray.size());\n\n                mFpsArray.push_back({ ts, frameCount });\n\n                mLastSnapshotTs = ts;\n                mLastSnapshotIdx = mTimestamps.size();\n            }\n\n            mTimestamps.push_back(ts);\n\n            prevMaxTimestamp = mTimestamps[mTimestamps.size() - 1];\n            if (mTimestamps.size() > 1)\n            {\n                auto frametime = ts - mTimestamps[mTimestamps.size() - 2];\n                mFrameTimeSummary.update(frametime, mFrameTimes.size());\n                mFrameTimes.push_back({ ts, frametime }); // -2 is prev item\n            }\n        }\n\n        if (firstFrameTimestamp == 0 && !mTimestamps.empty())\n        {\n            // TODO: a potential bug\n            firstFrameTimestamp = mTimestamps[0];\n            deltaTimestamp = mTimestamps[mTimestamps.size() - 1] - firstFrameTimestamp;\n\n            // init first label\n            if (mLabelPairs.empty())\n            {\n                mLabelPairs.push_back({ \"default\", firstFrameTimestamp, 0 });\n            }\n        }\n    }\n    auto lines = results.EPOCHREALTIME;\n    uint64_t millisec_since_epoch = fromString<double>(lines[0]) * 1e3;\n\n    //auto millisec_since_epoch = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();\n    if (mCpuStats.empty())\n        firstCpuStatTimestamp = millisec_since_epoch - deltaTimestamp - 1e3; // TODO: magic \n\n    {\n        // CPU Usage\n        auto lines = results.proc_stat;\n        for (auto& line : lines)\n        {\n            if (line.find(\"cpu\") == string::npos)\n                continue;\n\n            CpuStat new_stat(line);\n\n            if (line[3] == ' ')\n            {\n                // total CPU\n                mCpuStats.push_back({ millisec_since_epoch, new_stat });\n            }\n            else\n            {\n                // child CPU\n                int cpu_id = line[3] - '0';\n                if (cpu_id >= 0 && cpu_id < mCpuConfigs.size())\n                {\n                    mChildCpuStats[cpu_id].push_back({ millisec_since_epoch, new_stat });\n                }\n            }\n        }\n\n        {\n            // App CPU Usage\n            lines = results.proc_pid_stat;\n            if (!lines.empty() && lines[0].find(\"No such\") == string::npos)\n            {\n                AppCpuStat new_stat(lines[0]);\n                mAppCpuStats.push_back({ millisec_since_epoch, new_stat });\n            }\n        }\n\n        {\n            // Memory Usage\n            // https://perfetto.dev/docs/case-studies/memory\n            lines = results.dumpsys_meminfo;\n            if (lines.size() > 1)\n            {\n                MemoryStat stat;\n                for (auto& line : lines)\n                {\n                    if (line.find(\"Native Heap\") != string::npos)\n                    {\n                        auto& tokens = split(line, ' ');\n                        stat.pssNativeHeap = fromString<float>(tokens[2]) / 1024; // KB -> MB\n                    }\n                    else if (line.find(\"EGL mtrack\") != string::npos)\n                    {\n                        auto& tokens = split(line, ' ');\n                        stat.pssEGL = fromString<float>(tokens[2]) / 1024;\n                    }\n                    else if (line.find(\"Gfx dev\") != string::npos)\n                    {\n                        auto& tokens = split(line, ' ');\n                        stat.pssGfx = fromString<float>(tokens[2]) / 1024;\n                    }\n                    else if (line.find(\"GL mtrack\") != string::npos)\n                    {\n                        auto& tokens = split(line, ' ');\n                        stat.pssGL = fromString<float>(tokens[2]) / 1024;\n                    }\n                    else if (line.find(\"Unknown\") != string::npos)\n                    {\n                        auto& tokens = split(line, ' ');\n                        stat.pssUnknown = fromString<float>(tokens[1]) / 1024;\n                    }\n                    else if (line.find(\"TOTAL\") != string::npos)\n                    {\n                        auto& tokens = split(line, ' ');\n                        stat.pssTotal = fromString<float>(tokens[1]) / 1024;\n                        stat.privateDirty = fromString<float>(tokens[2]) / 1024;\n                        stat.privateClean = fromString<float>(tokens[3]) / 1024;\n\n                        mMemorySummary.update(stat.pssTotal, mMemoryStats.size());\n\n                        break;\n                    }\n                }\n\n                mMemoryStats.push_back({ millisec_since_epoch, stat });\n            }\n        }\n\n        {\n            // scaling_cur_freq\n            lines = results.scaling_cur_freq;\n            int idx = 0;\n            for (auto& line : lines)\n            {\n                auto freq = stoi(line);\n                mChildCpuStats[idx].back().second.freq = freq;\n                idx++;\n            }\n        }\n\n        {\n            if (results.temperature.cpu > 0 || results.temperature.gpu > 0)\n            {\n                if (!mTemparatureStatSlot.cpu.empty())\n                    mCpuTempSummary.update(results.temperature.cpu, mTemperatureStats.size());\n                mTemperatureStats.push_back({ millisec_since_epoch, results.temperature });\n            }\n        }\n    }\n    return true;\n}\n\nint PerfDoctorApp::getPid(const string& pacakgeName)\n{\n    char cmd[256];\n    sprintf(cmd, \"shell pidof %s\", pacakgeName.c_str());\n    auto lines = executeAdb(cmd);\n    if (lines.empty() || lines[0].empty()) // not running\n        return 0;\n\n    return fromString<int>(lines[0]);\n}\n\nbool PerfDoctorApp::startApp_ios(const string& pacakgeName)\n{\n    char cmd[256];\n    //if (pid = getPid(pacakgeName)) // already running\n        //return true;\n\n    sprintf(cmd, \"launch %s\", pacakgeName.c_str());\n    executeIdb(cmd);\n\n    return true;\n}\n\nbool PerfDoctorApp::startApp(const string& pacakgeName)\n{\n    if (mIsIOSDevices[DEVICE_ID])\n        return startApp_ios(pacakgeName);\n\n    char cmd[256];\n    //if (pid = getPid(pacakgeName)) // already running\n        //return true;\n\n    sprintf(cmd, \"shell cmd package resolve-activity --brief %s\", pacakgeName.c_str());\n    auto lines = executeAdb(cmd);\n    if (lines.size() == 2)\n    {\n        auto fullActivityName = lines[1];\n        sprintf(cmd, \"shell am start --activity-single-top %s\", pacakgeName.c_str());\n        auto startResults = executeAdb(cmd);\n        if (startResults.size() > 2 && startResults[1].find(\"Error\") == string::npos)\n            return true;\n    }\n    sprintf(cmd, \"shell monkey -p %s -v 1\", pacakgeName.c_str());\n    executeAdb(cmd);\n    return true;\n}\n\nbool PerfDoctorApp::stopApp_ios(const string& pacakgeName)\n{\n    char cmd[256];\n    //if (pid = getPid(pacakgeName)) // already running\n        //return true;\n\n    sprintf(cmd, \"kill %s\", pacakgeName.c_str());\n    executeIdb(cmd);\n\n    return true;\n}\n\nbool PerfDoctorApp::stopApp(const string& pacakgeName)\n{\n    if (mIsIOSDevices[DEVICE_ID])\n    {\n        stopApp_ios(pacakgeName);\n    }\n    else\n    {\n        char cmd[256];\n        sprintf(cmd, \"shell am force-stop %s\", pacakgeName.c_str());\n        auto lines = executeAdb(cmd);\n    }\n\n    stopProfiler();\n\n    return true;\n}\n\nvoid PerfDoctorApp::updateMetricsData()\n{\n    global_min_t = RANGE_START;\n    if (!mTimestamps.empty())\n    {\n        auto finalTimestamp = mTimestamps[mTimestamps.size() - 1];\n        global_max_t = max<float>((finalTimestamp - mTimestamps[0]) * 1e-3, (RANGE_START + RANGE_DURATION));\n        if (!mLabelPairs.empty())\n        {\n            mLabelPairs[mLabelPairs.size() - 1].end = finalTimestamp;\n        }\n    }\n    else\n    {\n        // TODO: a bug here?\n        global_max_t = max<float>((mCpuStats[mCpuStats.size() - 1].first - firstCpuStatTimestamp) * 1e-3, (RANGE_START + RANGE_DURATION));\n    }\n\n    {\n        auto& metrics = storage.metric_storage[\"frame_time\"];\n        metrics.name = \"frame_time\";\n        metrics.min_x = -1;\n        metrics.max_x = mFrameTimeSummary.Max + 10;\n    }\n    {\n        auto& metrics = storage.metric_storage[\"fps\"];\n        metrics.name = \"fps\";\n        metrics.min_x = -1;\n        metrics.max_x = mFpsSummary.Max + 10;\n    }\n    {\n        auto& metrics = storage.metric_storage[\"cpu_usage\"];\n        metrics.name = \"cpu_usage\";\n        metrics.min_x = -1;\n        metrics.max_x = 101;\n    }\n    {\n        auto& metrics = storage.metric_storage[\"core_usage\"];\n        metrics.name = \"core_usage\";\n        metrics.min_x = -1;\n        metrics.max_x = 101;\n    }\n    {\n        auto& metrics = storage.metric_storage[\"memory_usage\"];\n        metrics.name = \"memory_usage\";\n        metrics.min_x = 0;\n        metrics.max_x = mMemorySummary.Max + 200;\n    }\n    {\n        auto& metrics = storage.metric_storage[\"core_freq\"];\n        metrics.name = \"core_freq\";\n        metrics.min_x = -1;\n        metrics.max_x = 101;\n    }\n    {\n        auto& metrics = storage.metric_storage[\"temperature\"];\n        metrics.name = \"temperature\";\n        metrics.min_x = -1;\n        metrics.max_x = 101;\n    }\n}\n\nvoid PerfDoctorApp::getUnrealLog(bool openLogFile)\n{\n    char str[256];\n    sprintf(str, \"pull /sdcard/UE4Game/%s/%s/Saved/Logs/%s.log\", APP_FOLDER.c_str(), APP_FOLDER.c_str(), APP_FOLDER.c_str());\n    executeAdb(str);\n\n    if (openLogFile)\n    {\n        launchWebBrowser(Url(APP_FOLDER + \".log\", true));\n    }\n}\n\nvoid PerfDoctorApp::getMemReport()\n{\n    auto fn = [&]() {\n        char str[256];\n        sprintf(str, \"shell ls -l /sdcard/UE4Game/%s/%s/Saved/Profiling/MemReports\", APP_FOLDER.c_str(), APP_FOLDER.c_str());\n        auto lines = executeAdb(str);\n        if (lines.size() > 1)\n        {\n            auto folder = lines[lines.size() - 1];;\n            auto tokens = split(folder, ' ');\n            folder = tokens[tokens.size() - 1];\n\n            sprintf(str, \"shell ls -l /sdcard/UE4Game/%s/%s/Saved/Profiling/MemReports/%s\", APP_FOLDER.c_str(), APP_FOLDER.c_str(), folder.c_str());\n            lines = executeAdb(str);\n            if (lines.size() > 1)\n            {\n                auto lastLine = lines[lines.size() - 1];\n                tokens = split(lastLine, ' ');\n                auto lastFile = tokens[tokens.size() - 1];\n                sprintf(str, \"pull /sdcard/UE4Game/%s/%s/Saved/Profiling/MemReports/%s/%s\", APP_FOLDER.c_str(), APP_FOLDER.c_str(), folder.c_str(), lastFile.c_str());\n                executeAdb(str);\n                launchWebBrowser(Url(lastFile, true));\n            }\n        }\n    };\n    timeline().add(fn, timeline().getCurrentTime() + 1);\n}\n\nvoid PerfDoctorApp::getDumpTicks()\n{\n    auto fn = [&]() {\n        mTickFunctions.clear();\n\n        getUnrealLog();\n\n        int line_startDumpTicks = 0; // track the latest one\n        int line_endDumpTicks = 0; // track the latest one\n        std::ifstream ifs(APP_FOLDER + \".log\");\n        if (ifs.is_open())\n        {\n            std::string line;\n\n            // first pass\n            int lineNumber = 0;\n            while (std::getline(ifs, line))\n            {\n                if (line.find(\"Tick Functions (All)\") != string::npos)\n                {\n                    line_startDumpTicks = lineNumber;\n                }\n                if (line.find(\"Total registered tick\") != string::npos)\n                {\n                    line_endDumpTicks = lineNumber;\n                }\n\n                lineNumber++;\n            }\n            CI_ASSERT(line_endDumpTicks > line_startDumpTicks);\n\n            // second pass\n            lineNumber = 0;\n            ifs.clear();                 // clear fail and eof bits\n            ifs.seekg(0, std::ios::beg); // back to the start!\n            while (std::getline(ifs, line))\n            {\n                if (lineNumber > line_startDumpTicks && lineNumber < line_endDumpTicks)\n                {\n                    line = line.substr(30);\n                    auto tokens = split(line, \",\");\n                    if (tokens.size() != 4) continue;\n                    TickFunction tick = { tokens[0], tokens[1].substr(1), tokens[2].substr(23)};\n                    tokens = split(tick.actor, ' ');\n                    if (tokens.size() == 2)\n                    {\n                        // has object field\n                        tick.type = tokens[0];\n                        tick.actor = tokens[1];\n                        tokens = split(tick.actor, ':');\n                        if (tokens.size() >= 2)\n                        {\n                            // separate level and actor\n                            tick.level = tokens[0];\n                            auto tk = tokens[1];\n                            if (tk.find(\"PersistentLevel\") != string::npos)\n                                tk = tk.substr(sizeof(\"PersistentLevel\"));\n\n                            tokens = split(tk, \"[].\");\n                            if (tokens.size() > 2)\n                                tick.component = tokens[1];\n                            if (tokens.size() > 1)\n                                tick.actor = tokens[0];\n                        }\n\n                    }\n                    mTickFunctions.push_back(tick);\n                }\n                lineNumber++;\n            }\n\n            if (!mTickFunctions.empty())\n            {\n                auto ts = getTimestampForFilename();\n                string csv_name = APP_FOLDER + \"-ticks-\" + ts + \".csv\";\n                ofstream ofs(getAppPath() / csv_name);\n                if (ofs.is_open())\n                {\n                    ofs << \"Actor,Component,Type,Level,Status,TickGroup\" << endl;\n                    for (const auto& item : mTickFunctions)\n                    {\n                        ofs << item.actor << \",\"\n                            << item.component << \",\"\n                            << item.type << \",\"\n                            << item.level << \",\" \n                            << item.status << \",\" \n                            << item.tick_group << endl;\n                    }\n                }\n                ofs.close();\n                launchWebBrowser(Url(csv_name, true));\n            }\n        }\n\n        //char str[256];\n        //sprintf(str, \"shell ls -l /sdcard/UE4Game/%s/%s/Saved/Profiling/MemReports\", APP_FOLDER.c_str(), APP_FOLDER.c_str());\n        //auto lines = executeAdb(str);\n        //if (lines.size() > 1)\n        //{\n        //    auto folder = lines[lines.size() - 1];;\n        //    auto tokens = split(folder, ' ');\n        //    folder = tokens[tokens.size() - 1];\n\n        //    sprintf(str, \"shell ls -l /sdcard/UE4Game/%s/%s/Saved/Profiling/MemReports/%s\", APP_FOLDER.c_str(), APP_FOLDER.c_str(), folder.c_str());\n        //    lines = executeAdb(str);\n        //    if (lines.size() > 1)\n        //    {\n        //        auto lastLine = lines[lines.size() - 1];\n        //        tokens = split(lastLine, ' ');\n        //        auto lastFile = tokens[tokens.size() - 1];\n        //        sprintf(str, \"pull /sdcard/UE4Game/%s/%s/Saved/Profiling/MemReports/%s/%s\", APP_FOLDER.c_str(), APP_FOLDER.c_str(), folder.c_str(), lastFile.c_str());\n        //        executeAdb(str);\n        //        launchWebBrowser(Url(lastFile, true));\n        //    }\n        //}\n    };\n    timeline().add(fn, timeline().getCurrentTime() + 1);\n}\n\nextern void createConfigImgui(WindowRef window = getWindow(), bool autoDraw = true, bool autoRender = true);\n\nvoid PerfDoctorApp::setup()\n{\n    SetUnhandledExceptionFilter(unhandled_handler);\n    am::addAssetDirectory(getAppPath());\n    mAutoStart = AUTO_START;\n    ::SetCurrentDirectoryA(getAppPath().string().c_str());\n\n    std::ifstream ifs_perfetto(getAppPath() / \"perfetto-template.txt\");\n    if (ifs_perfetto.is_open())\n    {\n        std::string line;\n        while (std::getline(ifs_perfetto, line))\n        {\n            perfettoCmdTemplate += line;\n            perfettoCmdTemplate += '\\n';\n        }\n    }\n\n    std::ifstream ifs_unreal(getAppPath() / \"unreal-cmd.txt\");\n    if (ifs_unreal.is_open())\n    {\n        std::string line;\n        while (std::getline(ifs_unreal, line))\n        {\n            mUnrealCmds.push_back(line);\n        }\n    }\n\n    log::makeLogger<log::LoggerFileRotating>(fs::path(), \"app.%Y.%m.%d.log\");\n    createConfigImgui(getWindow(), false);\n\n    implotCtx = ImPlot::CreateContext();\n    ImPlot::PushColormap(ImPlotColormap_Cool);\n\n    ImPlot::GetStyle().AntiAliasedLines = true;\n    ImPlot::GetStyle().Marker = ImPlotMarker_Circle;\n    ImPlot::GetStyle().MarkerSize = 2;\n    ImPlot::GetStyle().Colormap = COLOR_MAP;\n\n    //ImPlot::SetNextMarkerStyle(ImPlotMarker_Square, 5, ImVec4(1, 0.5f, 0, 0.25f));\n\n    mAdbThread = make_unique<thread>([this] {\n        static auto lastTimestamp = getElapsedSeconds();\n        while (mIsRunning)\n        {\n            string asyncCmd;\n            if (mAsyncCommands.tryPopBack(&asyncCmd))\n            {\n                string output;\n                runCmd(asyncCmd, output);\n                if (asyncCmd.find(\"perfetto\") != string::npos)\n                {\n                    auto cmds = split(asyncCmd, \" \");\n                    launchWebBrowser(Url(\"https://ui.perfetto.dev/#!/\", true));\n                    goto_folder(getAppPath(), getAppPath() / (cmds[1] + \".perfetto\"));\n                }\n                else if (asyncCmd.find(\"screenshot\") != string::npos && asyncCmd.find(\"hide_screenshot\") == string::npos)\n                {\n                    auto cmds = split(asyncCmd, \" \");\n                    launchWebBrowser(Url(cmds[1] + \".png\", true));\n                }\n            }\n\n            if (mPackageName.empty() || !mIsProfiling || getElapsedSeconds() - lastTimestamp < REFRESH_SECONDS)\n            {\n                sleep(1);\n                continue;\n            }\n            lastTimestamp = getElapsedSeconds();\n\n            AdbResults results;\n            char cmd[256];\n            if (!mSurfaceViewName.empty())\n            {\n                sprintf(cmd, \"shell dumpsys SurfaceFlinger --latency \\\\\\\"%s\\\\\\\"\", mSurfaceViewName.c_str());\n                results.SurfaceFlinger_latency = executeAdb(cmd);\n            }\n            else if (SUPPORT_NON_GAME && storage.metric_storage[\"fps\"].visible)\n            {\n                sprintf(cmd, \"shell dumpsys gfxinfo %s framestats\", mPackageName.c_str());\n                results.dumpsys_gfxinfo = executeAdb(cmd);\n            }\n            results.EPOCHREALTIME = executeAdb(\"shell echo $EPOCHREALTIME\");\n            if (storage.metric_storage[\"cpu_usage\"].visible || storage.metric_storage[\"core_usage\"].visible)\n            {\n                results.proc_stat = executeAdb(\"shell cat /proc/stat\");\n            }\n\n            if (storage.metric_storage[\"memory_usage\"].visible)\n            {\n                sprintf(cmd, \"shell dumpsys meminfo %s\", mPackageName.c_str());\n                results.dumpsys_meminfo = executeAdb(cmd);\n            }\n\n            if (storage.metric_storage[\"core_freq\"].visible)\n            {\n                results.scaling_cur_freq = executeAdb(\"shell cat /sys/devices/system/cpu/cpu*/cpufreq/scaling_cur_freq\");\n            }\n\n            if (storage.metric_storage[\"cpu_usage\"].visible)\n            {\n                sprintf(cmd, \"shell cat /proc/%d/stat\", pid);\n                results.proc_pid_stat = executeAdb(cmd);\n                if (!results.proc_pid_stat.empty() && results.proc_pid_stat[0].find(\"error\") != string::npos)\n                {\n                    results.success = false;\n                }\n            }\n\n            {\n                if (!mTemparatureStatSlot.cpu.empty())\n                {\n                    sprintf(cmd, \"shell cat %s\", mTemparatureStatSlot.cpu.c_str());\n                    auto lines = executeAdb(cmd);\n                    if (!lines.empty()) results.temperature.cpu = stoi(lines[0]) * 1e-3;\n                }\n                if (!mTemparatureStatSlot.gpu.empty())\n                {\n                    sprintf(cmd, \"shell cat %s\", mTemparatureStatSlot.gpu.c_str());\n                    auto lines = executeAdb(cmd);\n                    if (!lines.empty()) results.temperature.gpu = stoi(lines[0]) * 1e-3;\n                }\n                if (!mTemparatureStatSlot.battery.empty())\n                {\n                    sprintf(cmd, \"shell cat %s\", mTemparatureStatSlot.battery.c_str());\n                    auto lines = executeAdb(cmd);\n                    if (!lines.empty()) results.temperature.battery = stoi(lines[0]) * 1e-3;\n                }\n            }\n\n            mAdbResults.pushFront(results);\n        }\n    });\n\n    refreshDeviceNames();\n\n    mLastUpdateTime = getElapsedSeconds();\n\n    getWindow()->getSignalKeyDown().connect([&](KeyEvent& event) {\n        if (event.getCode() == KeyEvent::KEY_ESCAPE)\n        {\n            fps_visible = storage.metric_storage[\"fps\"].visible;\n            frame_time_visible = storage.metric_storage[\"frame_time\"].visible;\n            cpu_usage_visible = storage.metric_storage[\"cpu_usage\"].visible;\n            core_usage_visible = storage.metric_storage[\"core_usage\"].visible;\n            memory_usage_visible = storage.metric_storage[\"memory_usage\"].visible;\n            core_freq_visible = storage.metric_storage[\"core_freq\"].visible;\n            temperature_visible = storage.metric_storage[\"temperature\"].visible;\n\n            COLOR_MAP = ImPlot::GetStyle().Colormap;\n\n            quit();\n        }\n    });\n\n    getWindow()->getSignalKeyUp().connect([&](KeyEvent& event) {\n        if (event.isControlDown() && event.getCode() == KeyEvent::KEY_l) getUnrealLog(true);\n        if (event.isControlDown() && event.getCode() == KeyEvent::KEY_s) screenshot();\n        if (event.isControlDown() && event.getCode() == KeyEvent::KEY_p) capturePerfetto();\n        if (event.isControlDown() && event.getCode() == KeyEvent::KEY_m) captureSimpleperf();\n        if (event.isControlDown() && event.getCode() == KeyEvent::KEY_d) executeUnrealCmd(\"dumpticks\");\n    });\n\n    getWindow()->getSignalClose().connect([&] {\n        mIsRunning = false;\n        mAdbThread->join();\n    });\n\n    getWindow()->getSignalResize().connect([&] {\n        APP_WIDTH = getWindowWidth();\n        APP_HEIGHT = getWindowHeight();\n    });\n\n    getSignalUpdate().connect([&] {\n#ifndef NDEBUG\n        bool open = false;\n        ImPlot::ShowDemoWindow(&open);\n#endif\n        //ImGui::CaptureKeyboardFromApp(false);\n\n        if (ImGui::Begin(\"Devices\", NULL, ImGuiWindowFlags_AlwaysAutoResize))\n        {\n            drawLeftSidePanel();\n            ImGui::End();\n        }\n\n        if (mIsProfiling)\n        {\n            AdbResults results;\n            if (mAdbResults.tryPopBack(&results))\n            {\n                if (results.success)\n                {\n                    updateProfiler(results);\n                    updateMetricsData();\n                }\n            }\n        }\n\n        if (ImGui::Begin(\"Performance\"))\n        {\n            drawPerfPanel();\n        }\n        ImGui::End();\n\n    });\n\n    getSignalCleanup().connect([&] {\n        ImPlot::DestroyContext(implotCtx);\n        writeConfig();\n    });\n\n    getWindow()->getSignalDraw().connect([&] {\n        gl::clear(ColorA::gray(BACKGROUND_GRAY));\n    });\n}\n\nCINDER_APP(PerfDoctorApp, RendererGl, [](App::Settings* settings) {\n    readConfig();\n    settings->setWindowSize(APP_WIDTH, APP_HEIGHT);\n    settings->setMultiTouchEnabled(false);\n})\n"
  },
  {
    "path": "src/LightSpeedApp.gui.cpp",
    "content": "#include \"LightSpeedApp.h\"\n#include \"MiniConfigImgui.h\"\n\n\nstatic ImPlotPoint frameTime_getter(void* data, int idx)\n{\n    const auto& self = *(vector<pair<uint64_t, uint64_t>>*)data;\n    return ImPlotPoint((self[idx].first - firstFrameTimestamp) * 1e-3, self[idx].second);\n}\n\nstatic ImPlotPoint fps_getter(void* data, int idx)\n{\n    const auto& self = *(vector<pair<uint64_t, float>>*)data;\n    return ImPlotPoint((self[idx].first - firstFrameTimestamp) * 1e-3, self[idx].second);\n}\n\nstatic ImPlotPoint cpuUsage_getter(void* data, int idx)\n{\n    const auto& self = *(vector<pair<uint64_t, CpuStat>>*)data;\n    return ImPlotPoint((self[idx].first - firstCpuStatTimestamp) * 1e-3, calcCpuUsage(self[idx].second, self[idx + 1].second));\n}\n\nstatic ImPlotPoint cpuFreq_getter(void* data, int idx)\n{\n    const auto& self = *(vector<pair<uint64_t, CpuStat>>*)data;\n    int cpu_id = self[idx].second.cpu_id;\n    return ImPlotPoint((self[idx].first - firstCpuStatTimestamp) * 1e-3, self[idx].second.freq * 100 / mCpuConfigs[cpu_id].cpuinfo_max_freq);\n}\n\nstatic ImPlotPoint app_cpuUsage_getter(void* data, int idx)\n{\n    const auto& self = *(vector<pair<uint64_t, AppCpuStat>>*)data;\n    return ImPlotPoint((self[idx].first - firstCpuStatTimestamp) * 1e-3, calcAppCpuUsage(\n        mCpuStats[idx].second, mCpuStats[idx + 1].second,\n        self[idx].second, self[idx + 1].second));\n}\n\nstatic ImPlotPoint memoryUsage_getter(void* data, int idx)\n{\n    const auto& self = *(vector<pair<uint64_t, MemoryStat>>*)data;\n    return ImPlotPoint((self[idx].first - firstCpuStatTimestamp) * 1e-3, self[idx].second.pssTotal);\n}\n\nstatic ImPlotPoint gl_memoryUsage_getter(void* data, int idx)\n{\n    const auto& self = *(vector<pair<uint64_t, MemoryStat>>*)data;\n    return ImPlotPoint((self[idx].first - firstCpuStatTimestamp) * 1e-3, self[idx].second.pssGL + self[idx].second.pssEGL + self[idx].second.pssGfx);\n}\n\nstatic ImPlotPoint nativeheap_memoryUsage_getter(void* data, int idx)\n{\n    const auto& self = *(vector<pair<uint64_t, MemoryStat>>*)data;\n    return ImPlotPoint((self[idx].first - firstCpuStatTimestamp) * 1e-3, self[idx].second.pssNativeHeap);\n}\n\nstatic ImPlotPoint unknown_memoryUsage_getter(void* data, int idx)\n{\n    const auto& self = *(vector<pair<uint64_t, MemoryStat>>*)data;\n    return ImPlotPoint((self[idx].first - firstCpuStatTimestamp) * 1e-3, self[idx].second.pssUnknown);\n}\n\nstatic ImPlotPoint privateClean_memoryUsage_getter(void* data, int idx)\n{\n    const auto& self = *(vector<pair<uint64_t, MemoryStat>>*)data;\n    return ImPlotPoint((self[idx].first - firstCpuStatTimestamp) * 1e-3, self[idx].second.privateClean);\n}\n\nstatic ImPlotPoint privateDirty_memoryUsage_getter(void* data, int idx)\n{\n    const auto& self = *(vector<pair<uint64_t, MemoryStat>>*)data;\n    return ImPlotPoint((self[idx].first - firstCpuStatTimestamp) * 1e-3, self[idx].second.privateDirty);\n}\n\nstatic ImPlotPoint temp_cpu_getter(void* data, int idx)\n{\n    const auto& self = *(vector<pair<uint64_t, TemperatureStat>>*)data;\n    return ImPlotPoint((self[idx].first - firstCpuStatTimestamp) * 1e-3, self[idx].second.cpu);\n}\n\nstatic ImPlotPoint temp_gpu_getter(void* data, int idx)\n{\n    const auto& self = *(vector<pair<uint64_t, TemperatureStat>>*)data;\n    return ImPlotPoint((self[idx].first - firstCpuStatTimestamp) * 1e-3, self[idx].second.gpu);\n}\n\nstatic ImPlotPoint temp_battery_getter(void* data, int idx)\n{\n    const auto& self = *(vector<pair<uint64_t, TemperatureStat>>*)data;\n    return ImPlotPoint((self[idx].first - firstCpuStatTimestamp) * 1e-3, self[idx].second.battery);\n}\n\n// Plots axis-aligned, filled rectangles. Every two consecutive points defines opposite corners of a single rectangle.\nstatic ImPlotPoint label_getter(void* data, int idx)\n{\n    auto* self = (LabelPair*)data;\n    int span_idx = idx / 2;\n    int tag = idx % 2;\n    if (tag == 0)\n    {\n        float start_t = (self[span_idx].start - firstFrameTimestamp) * 1e-3;\n        return ImPlotPoint(start_t, 0);\n    }\n    else\n    {\n        float end_t = (self[span_idx].end - firstFrameTimestamp) * 1e-3;\n        return ImPlotPoint(end_t, 10);\n    }\n}\n\nvoid PerfDoctorApp::drawLeftSidePanel()\n{\n    ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_None;\n    if (ImGui::BeginTabBar(\"DeviceTab\", tab_bar_flags))\n    {\n        if (ImGui::BeginTabItem(\"Devices\"))\n        {\n            drawDeviceTab();\n            ImGui::EndTabItem();\n        }\n\n        if (ImGui::BeginTabItem(\"Settings\"))\n        {\n            ImPlot::ShowStyleSelector(\"Style\");\n            ImPlot::ShowColormapSelector(\"Colormap\");\n            vnm::drawMinicofigImgui();\n\n            ImGui::EndTabItem();\n        }\n\n        if (ImGui::BeginTabItem(\"Unreal\"))\n        {\n            char str[256];\n\n            ImGui::InputText(\"APP_FOLDER\", &APP_FOLDER);\n            ImGui::SameLine();\n            if (ImGui::Button(\"Get log\"))\n            {\n                getUnrealLog(true);\n            }\n\n            if (ImGui::CollapsingHeader(\"UE4CommandLine\", ImGuiTreeNodeFlags_DefaultOpen))\n            {\n                if (ImGui::Button(\"Reset\"))\n                {\n                    sprintf(str, \"shell rm /sdcard/UE4Game/%s/UE4CommandLine.txt\", APP_FOLDER.c_str());\n                    executeAdb(str);\n                }\n                if (ImGui::Button(\"Enable Insights\"))\n                {\n                    sprintf(str, \"push %s/UE4CommandLine.txt /sdcard/UE4Game/%s/\", getAppPath().string().c_str(), APP_FOLDER.c_str());\n                    executeAdb(str);\n                    executeAdb(\"reverse tcp:1980 tcp:1980\");\n                }\n            }\n\n            ImGui::InputText(\" \", &UE_CMD);\n            ImGui::SameLine();\n            if (ImGui::Button(\"Apply\"))\n            {\n                executeUnrealCmd(UE_CMD);\n            }\n            ImGui::NewLine();\n\n            for (const auto cmd : mUnrealCmds)\n            {\n                if (cmd.empty())\n                {\n                    ImGui::NewLine();\n                    continue;\n                }\n\n                if (cmd[0] == '/') continue;\n\n                auto tokens = split(cmd, '|');\n                for (int i = 0; i < tokens.size(); i++)\n                {\n                    if (i > 0)\n                        ImGui::SameLine();\n\n                    auto& token = tokens[i];\n                    if (ImGui::Button(token.c_str()))\n                    {\n                        UE_CMD = token;\n                        executeUnrealCmd(UE_CMD);\n                    }\n                }\n            }\n\n            ImGui::EndTabItem();\n        }\n    }\n    ImGui::EndTabBar();\n}\n\nvoid PerfDoctorApp::drawDeviceTab()\n{\n    if (ImGui::Button(\"Refresh\"))\n    {\n        refreshDeviceNames();\n        if (DEVICE_ID != -1)\n            refreshDeviceDetails();\n    }\n    if (ImGui::Combo(\"Pick a device\", &DEVICE_ID, mDeviceNames))\n    {\n    }\n\n    if (DEVICE_ID != mDeviceId)\n    {\n        refreshDeviceDetails();\n        resetPerfData();\n        mDeviceId = DEVICE_ID;\n    }\n\n    if (DEVICE_ID != -1)\n    {\n        if (ImGui::Combo(\"Pick an app\", &mAppId, mAppNames, ImGuiComboFlags_HeightLarge))\n        {\n            APP_NAME = mAppNames[mAppId];\n        }\n\n        ImGui::SameLine();\n        if (ImGui::Button(\"Topmost\"))\n        {\n            // adb shell \"dumpsys activity activities | grep mResumedActivity\"\n            auto lines = executeAdb(\"shell \\\"dumpsys activity activities | grep mResumedActivity\\\"\");\n            if (!lines.empty())\n            {\n                auto tokens = split(lines[0], \": {}/\");\n                auto topAppName = tokens[4];\n                if (APP_NAME != topAppName)\n                {\n                    APP_NAME = topAppName;\n                    mPackageName = APP_NAME;\n                    stopProfiler();\n                }\n\n                int idx = 0;\n                for (auto& name : mAppNames)\n                {\n                    if (name == APP_NAME)\n                    {\n                        mAppId = idx;\n                        break;\n                    }\n                    idx++;\n                }\n            }\n        }\n\n        if (mAppId != -1)\n        {\n            if (ImGui::Button(\"Start App\"))\n            {\n                startApp(mAppNames[mAppId]);\n            }\n            ImGui::SameLine();\n            if (ImGui::Button(\"Stop App\"))\n            {\n                stopApp(mAppNames[mAppId]);\n            }\n            \n            if (mIsProfiling)\n            {\n                if (ImGui::Button(\"Stop Profiling\"))\n                {\n                    stopProfiler();\n                }\n\n                ImGui::SameLine();\n\n                if (ImGui::Button(\"Export\"))\n                {\n                    exportCsv();\n                }\n                if (!mSurfaceResolution.empty())\n                {\n                    ImGui::SameLine();\n                    ImGui::Text(\"WxH: %s\", mSurfaceResolution.c_str());\n                }\n            }\n            else\n            {\n                if (mAutoStart)\n                {\n                    startProfiler(mAppNames[mAppId]);\n                    mAutoStart = false;\n                }\n                if (ImGui::Button(\"Start Profiling\"))\n                {\n                    startProfiler(mAppNames[mAppId]);\n                }\n            }\n        }\n\n        if (ImGui::Button(\"Screenshot\"))    screenshot();\n        ImGui::SameLine();\n        if (ImGui::Button(\"Perfetto\"))      capturePerfetto();\n        ImGui::SameLine();\n        if (ImGui::Button(\"SimplePerf\"))    captureSimpleperf();\n\n        if (ImGui::CollapsingHeader(\"Config\", ImGuiTreeNodeFlags_DefaultOpen))\n        {\n            ImGui::Indent();\n            if (!mDeviceStat.os_version.empty())\n                ImGui::Text(mDeviceStat.os_version.c_str());\n            if (!mDeviceStat.hardware.empty())\n                ImGui::Text(\"%s\", mDeviceStat.hardware.c_str());\n            if (!mDeviceStat.gpu_name.empty())\n                ImGui::Text(\"%s\", mDeviceStat.gpu_name.c_str());\n#if 0\n            if (mDeviceStat.width > 0 && mDeviceStat.height > 0)\n                ImGui::Text(\"%d x %d\", mDeviceStat.width, mDeviceStat.height);\n#endif\n            if (!mDeviceStat.gfx_api_version.empty())\n                ImGui::Text(mDeviceStat.gfx_api_version.c_str());\n            if (!mDeviceStat.display_WxH.empty())\n                ImGui::Text(\"Phone WxH: %s\", mDeviceStat.display_WxH.c_str());\n            if (mDeviceStat.fps_max != 0)\n                ImGui::Text(\"FPS max:%d now:%d\", mDeviceStat.fps_max, mDeviceStat.fps_now);\n            for (const auto& config : mCpuConfigs)\n            {\n                if (config.cpuinfo_min_freq > 0)\n                {\n                    ImGui::Text(\"cpu_%d: %s %.2f~%.2f GHz\",\n                        config.id, config.part.c_str(),\n                        config.cpuinfo_min_freq / 1e6, config.cpuinfo_max_freq / 1e6);\n                }\n                else\n                {\n                    ImGui::Text(\"cpu_%d: %s\",\n                        config.id, config.part.c_str());\n                }\n            }\n            ImGui::Unindent();\n        }\n\n        if (ImGui::CollapsingHeader(\"Charts\", ImGuiTreeNodeFlags_DefaultOpen))\n        {\n            for (auto& kv : storage.metric_storage)\n            {\n                ImGui::Checkbox(kv.first.c_str(), &kv.second.visible);\n            }\n        }\n\n        if (ImGui::CollapsingHeader(\"Low Memory\", ImGuiTreeNodeFlags_DefaultOpen))\n        {\n            if (ImGui::Button(\"Running Moderate\")) trimMemory(\"RUNNING_MODERATE\");\n            if (ImGui::Button(\"Running Low\")) trimMemory(\"RUNNING_LOW\");\n            if (ImGui::Button(\"Running Critical\")) trimMemory(\"RUNNING_CRITICAL\");\n        }\n\n    }\n}\n\nvoid PerfDoctorApp::drawPerfPanel()\n{\n#if 0\n    for (const auto& kv : storage.span_storage)\n    {\n        auto& series = kv.second;\n\n        ImPlot::SetNextPlotTicksX(global_min_t, global_max_t, PANEL_TICK_T);\n        ImPlot::SetNextPlotLimitsX(global_min_t, global_max_t, ImGuiCond_Always);\n        ImPlot::SetNextPlotTicksY(0, 10, 2);\n\n        if (ImPlot::BeginPlot(series_name.c_str(), NULL, NULL, ImVec2(-1, PANEL_HEIGHT), ImPlotFlags_NoChild, ImPlotAxisFlags_None))\n        {\n            //ImPlot::PushStyleColor(ImPlotCol_Line, items[i].Col);\n            ImPlot::PlotRects(series_name.c_str(), SpanSeries::getter, (void*)&series, series.span_array.size() * 2);\n            for (const auto& span : series.span_array)\n            {\n                ImPlot::PlotText(span.name.c_str(), span.start/*  / TIME_UNIT_SCALE */, 0, false, ImVec2(0, -PANEL_HEIGHT / 2));\n            }\n\n#if 0\n            ImPlot::PushPlotClipRect();\n            ImDrawList* draw_list = ImGui::GetWindowDrawList();\n            draw_list->AddRectFilled(ImVec2(tool_l, tool_t), ImVec2(tool_r, tool_b), IM_COL32(0, 255, 255, 64));\n            ImPlot::PopPlotClipRect();\n#endif\n            if (SHOW_TOOL_TIP && ImPlot::IsPlotHovered())\n            {\n                ImPlotPoint mouse = ImPlot::GetPlotMousePos();\n                mouse.x = round(mouse.x);\n                float half_width = 10;\n                float  tool_l = ImPlot::PlotToPixels(mouse.x - half_width * 1.5, mouse.y).x;\n                float  tool_r = ImPlot::PlotToPixels(mouse.x + half_width * 1.5, mouse.y).x;\n                float  tool_t = ImPlot::GetPlotPos().y;\n                float  tool_b = tool_t + ImPlot::GetPlotSize().y;\n                for (const auto& span : series.span_array)\n                {\n                    if (span.start <= mouse.x && mouse.x < span.end)\n                    {\n                        ImGui::BeginTooltip();\n                        ImGui::Text(span.label.c_str());\n                        ImGui::EndTooltip();\n                        break;\n                    }\n                }\n            }\n\n            //ImPlot::PopStyleColor();\n            ImPlot::EndPlot();\n        }\n    }\n#endif\n\n    bool s_drawLabel = true;\n    for (const auto& kv : storage.metric_storage)\n    {\n        auto& series = kv.second;\n        auto& series_name = kv.first;\n        if (!series.visible) continue;\n\n        if (s_drawLabel)\n        {\n            s_drawLabel = false;\n            float height = 1;\n            ImPlot::SetNextAxisLimits(ImAxis_X1, global_min_t, global_max_t, ImGuiCond_Always);\n            ImPlot::SetNextAxisLimits(ImAxis_Y1, 0, height, ImGuiCond_Always);\n            auto color = ImVec4(0.3f, 0.3f, 0.3f, 0.5f);\n            ImPlot::PushStyleColor(ImPlotCol_Fill, color);\n\n            if (ImPlot::BeginPlot(\"label\", NULL, NULL, ImVec2(-1, 60),\n                ImPlotFlags_NoLegend | ImPlotFlags_NoTitle | ImPlotFlags_NoMenus, ImPlotAxisFlags_NoGridLines | ImPlotAxisFlags_NoTickMarks, ImPlotAxisFlags_NoDecorations))\n            {\n                // TODO:\n                //ImPlot::PlotRects(\"label\", label_getter, (void*)mLabelPairs.data(), mLabelPairs.size() * 2);\n                for (const auto& pair : mLabelPairs)\n                {\n                    float start = (pair.start - firstFrameTimestamp) * 1e-3;\n                    float end = (pair.end - firstFrameTimestamp) * 1e-3;\n\n                    ImPlot::PlotText(pair.name.c_str(), (start + end) * 0.5, height / 2, false);\n                }\n                ImPlot::EndPlot();\n            }\n\n            ImPlot::PopStyleColor();\n        }\n\n        //ImPlot::SetNextPlotTicksX(global_min_t, global_max_t, PANEL_TICK_T);\n        ImPlot::SetNextAxisLimits(ImAxis_X1, global_min_t, global_max_t, ImGuiCond_Always);\n        //ImPlot::SetNextPlotTicksY(series.min_x, series.max_x, PANEL_TICK_X);\n        ImPlot::SetNextAxisLimits(ImAxis_Y1, series.min_x, series.max_x, ImGuiCond_Always);\n\n        string title = series_name;\n        char text[256];\n\n        if (series_name == \"fps\" && !mFpsArray.empty())\n        {\n            sprintf(text, \"fps [%.1f, %.1f] avg: %.1f\", mFpsSummary.Min, mFpsSummary.Max, mFpsSummary.Avg);\n            title = text;\n        }\n        if (series_name == \"memory_usage\" && !mMemoryStats.empty())\n        {\n            sprintf(text, \"memory_usage [%.0f, %.0f] avg: %.0f\", mMemorySummary.Min, mMemorySummary.Max, mMemorySummary.Avg);\n            title = text;\n        }\n        if (series_name == \"temperature\" && !mTemperatureStats.empty())\n        {\n            sprintf(text, \"temperature [%.0f, %.0f] avg: %.0f\", mCpuTempSummary.Min, mCpuTempSummary.Max, mCpuTempSummary.Avg);\n            title = text;\n        }\n        if (series_name == \"cpu_usage\" && !mAppCpuStats.empty())\n        {\n            sprintf(text, \"cpu_usage [%.0f, %.0f] avg: %.1f\", mAppCpuSummary.Min, mAppCpuSummary.Max, mAppCpuSummary.Avg);\n            //title = text;\n            // TODO: fix bug\n        }\n        if (ImPlot::BeginPlot(title.c_str(), NULL, NULL, ImVec2(-1, PANEL_HEIGHT),\n            ImPlotFlags_NoChild | ImPlotFlags_NoMenus, ImPlotAxisFlags_NoDecorations))\n        {\n            ImPlot::SetupLegend(ImPlotLocation_North | ImPlotLocation_West);\n\n            //ImPlot::PushStyleColor(ImPlotCol_Line, items[i].Col);\n            if (series_name == \"frame_time\")\n            {\n                ImPlot::PlotLineG(series_name.c_str(), frameTime_getter, (void*)&mFrameTimes, mFrameTimes.size());\n            }\n            else if (series_name == \"fps\")\n            {\n                ImPlot::PlotLineG(series_name.c_str(), fps_getter, (void*)&mFpsArray, mFpsArray.size());\n            }\n            else if (series_name == \"cpu_usage\")\n            {\n                if (!mCpuStats.empty())\n                {\n                    ImPlot::PlotLineG(\"sys\", cpuUsage_getter, (void*)&mCpuStats, mCpuStats.size() - 1);\n                    ImPlot::PlotLineG(\"app\", app_cpuUsage_getter, (void*)&mAppCpuStats, mAppCpuStats.size() - 1);\n                }\n            }\n            else if (series_name == \"core_usage\")\n            {\n                char label[] = \"cpu_0\";\n                for (int i = 0; i < mCpuConfigs.size(); i++)\n                {\n                    label[4] = '0' + i;\n                    ImPlot::PlotLineG(label, cpuUsage_getter, (void*)&mChildCpuStats[i], mChildCpuStats[i].size() - 1);\n                }\n            }\n            else if (series_name == \"core_freq\")\n            {\n                char label[] = \"cpu_0\";\n                for (int i = 0; i < mCpuConfigs.size(); i++)\n                {\n                    label[4] = '0' + i;\n                    ImPlot::PlotLineG(label, cpuFreq_getter, (void*)&mChildCpuStats[i], mChildCpuStats[i].size());\n                }\n            }\n            else if (series_name == \"memory_usage\")\n            {\n                ImPlot::PlotLineG(\"total\", memoryUsage_getter, (void*)&mMemoryStats, mMemoryStats.size());\n                ImPlot::PlotLineG(\"native_heap\", nativeheap_memoryUsage_getter, (void*)&mMemoryStats, mMemoryStats.size());\n                ImPlot::PlotLineG(\"graphics\", gl_memoryUsage_getter, (void*)&mMemoryStats, mMemoryStats.size());\n                ImPlot::PlotLineG(\"unknown\", unknown_memoryUsage_getter, (void*)&mMemoryStats, mMemoryStats.size());\n                //ImPlot::PlotLineG(\"private_clean\", privateClean_memoryUsage_getter, (void*)&mMemoryStats, mMemoryStats.size());\n                //ImPlot::PlotLineG(\"private_dirty\", privateDirty_memoryUsage_getter, (void*)&mMemoryStats, mMemoryStats.size());\n            }\n            else if (series_name == \"temperature\")\n            {\n                if (!mTemparatureStatSlot.cpu.empty())\n                    ImPlot::PlotLineG(\"cpu\", temp_cpu_getter, (void*)&mTemperatureStats, mTemperatureStats.size());\n                if (!mTemparatureStatSlot.gpu.empty())\n                    ImPlot::PlotLineG(\"gpu\", temp_gpu_getter, (void*)&mTemperatureStats, mTemperatureStats.size());\n                if (!mTemparatureStatSlot.battery.empty())\n                    ImPlot::PlotLineG(\"battery\", temp_battery_getter, (void*)&mTemperatureStats, mTemperatureStats.size());\n            }\n            else\n                ImPlot::PlotLineG(series_name.c_str(), MetricSeries::getter, (void*)&series, series.t_array.size());\n            //ImPlot::PopStyleColor();\n            ImPlot::EndPlot();\n        }\n    }\n}\n\nvoid PerfDoctorApp::drawLabel()\n{\n    if (ImPlot::BeginPlot(\"label\"))\n    {\n        bool clamp = false;\n#if 0\n        ImVec4 col = ImVec4(1, 0.5f, 0, 0.25f);\n        clamp ? ImPlot::AnnotateClamped(0.25, 0.25, ImVec2(-15, 15), col, \"BL\") : ImPlot::Annotate(0.25, 0.25, ImVec2(-15, 15), col, \"BL\");\n        clamp ? ImPlot::AnnotateClamped(0.75, 0.25, ImVec2(15, 15), col, \"BR\") : ImPlot::Annotate(0.75, 0.25, ImVec2(15, 15), col, \"BR\");\n        clamp ? ImPlot::AnnotateClamped(0.75, 0.75, ImVec2(15, -15), col, \"TR\") : ImPlot::Annotate(0.75, 0.75, ImVec2(15, -15), col, \"TR\");\n        clamp ? ImPlot::AnnotateClamped(0.25, 0.75, ImVec2(-15, -15), col, \"TL\") : ImPlot::Annotate(0.25, 0.75, ImVec2(-15, -15), col, \"TL\");\n        clamp ? ImPlot::AnnotateClamped(0.5, 0.5, ImVec2(0, 0), col, \"Center\") : ImPlot::Annotate(0.5, 0.5, ImVec2(0, 0), col, \"Center\");\n\n        float bx[] = { 1.2f,1.5f,1.8f };\n        float by[] = { 0.25f, 0.5f, 0.75f };\n        ImPlot::PlotBars(\"##Bars\", bx, by, 3, 0.2);\n        for (int i = 0; i < 3; ++i)\n            ImPlot::Annotate(bx[i], by[i], ImVec2(0, -5), \"B[%d]=%.2f\", i, by[i]);\n#endif\n        ImPlot::EndPlot();\n    }\n}\n"
  },
  {
    "path": "src/LightSpeedApp.h",
    "content": "#define _HAS_STD_BYTE 0\n\n#include \"cinder/app/App.h\"\n#include \"cinder/app/RendererGl.h\"\n#include \"cinder/gl/gl.h\"\n#include \"cinder/Log.h\"\n#include \"cinder/ConcurrentCircularBuffer.h\"\n\n#include \"AssetManager.h\"\n#include \"implot/implot.h\"\n#include \"implot/implot_internal.h\"\n\nusing namespace ci;\nusing namespace ci::app;\nusing namespace std;\n\nstruct Span\n{\n    string name;\n    string label;\n    float start = 0;\n    float end = 0;\n};\n\nstruct LabelPair\n{\n    string name;\n    uint64_t start = 0;\n    uint64_t end = 0;\n};\n\nstruct MemoryStat\n{\n    float pssTotal;\n    float pssGL;\n    float pssEGL;\n    float pssGfx;\n    float pssUnknown;\n    float pssNativeHeap;\n\n    float privateClean;\n    float privateDirty;\n};\n\nstruct TemperatureStatSlot\n{\n    string cpu;\n    string gpu;\n    string battery;\n};\n\nstruct TemperatureStat\n{\n    float cpu = 0, gpu = 0, battery = 0;\n};\n\nstruct CpuConfig\n{\n    int id;\n    int cpuinfo_min_freq = 0, cpuinfo_max_freq = 0;\n    string features;\n    string implementer;\n    string architecture;\n    string variant;\n    string part;\n    string revision;\n};\n\nstruct DeviceStat\n{\n    int width = 0, height = 0;\n    int fps_min = 0, fps_max = 0, fps_now = 0;\n    string display_WxH;\n    string os_version;\n    string gfx_api_version;\n    string market_name; // iOS only\n    string hardware;\n    string gpu_name;\n};\n\nstruct CpuStat\n{\n    int cpu_id;\n    long int user, nice, sys, idle, iowait, irq, softirq;\n    int freq = -1;\n\n    CpuStat(const string& line)\n    {\n        char cpu[5]; // TODO: remove\n        sscanf(line.c_str(), \"%s%d%d%d%d%d%d%d\", cpu, &user, &nice, &sys, &idle, &iowait, &irq, &softirq);\n        cpu_id = cpu[3] - '0';\n    }\n\n    long int getAll() const\n    {\n        return user + nice + sys + idle + iowait + irq + softirq;\n    }\n\n    long int getIdle() const\n    {\n        return idle;\n    }\n};\n\nfloat calcCpuUsage(const CpuStat& lhs, const CpuStat& rhs);\n\nstruct AppCpuStat\n{\n    // https://www.chenwenguan.com/android-performance-monitor-cpu/\n    long int utime, stime;\n    long int cutime, cstime;\n\n    AppCpuStat(const string& line);\n\n    long int getActiveTime() const\n    {\n        return utime + stime + cutime + cstime;\n    }\n};\n\nfloat calcAppCpuUsage(const CpuStat& lhs, const CpuStat& rhs, const AppCpuStat& appLhs, const AppCpuStat& appRhs);\n\nstruct SpanSeries\n{\n    string name;\n    vector<Span> span_array;\n\n    SpanSeries()\n    {\n    }\n\n    // Plots axis-aligned, filled rectangles. Every two consecutive points defines opposite corners of a single rectangle.\n    static ImPlotPoint getter(void* data, int idx)\n    {\n        auto* self = (SpanSeries*)data;\n        int span_idx = idx / 2;\n        int tag = idx % 2;\n        if (tag == 0)\n        {\n            float start_t = self->span_array[span_idx].start/*  / TIME_UNIT_SCALE */;\n            return ImPlotPoint(start_t, 0);\n        }\n        else\n        {\n            float end_t = self->span_array[span_idx].end/*  / TIME_UNIT_SCALE */;\n            return ImPlotPoint(end_t, 10);\n        }\n    }\n};\n\nstruct MetricSeries\n{\n    bool visible = true;\n    MetricSeries()\n    {\n\n    }\n\n    static ImPlotPoint getter(void* data, int idx)\n    {\n        auto* self = (MetricSeries*)data;\n        return ImPlotPoint(self->t_array[idx], self->x_array[idx]);\n    }\n\n    float min_x = 0;\n    float max_x = 60;\n\n    string name;\n    vector<float> t_array;\n    vector<float> x_array;\n};\n\nstruct DataStorage\n{\n    unordered_map<string, SpanSeries> span_storage;\n    unordered_map<string, MetricSeries> metric_storage;\n};\n\n// TODO: so ugly\nextern float global_min_t;\nextern float global_max_t;\nextern uint64_t firstFrameTimestamp;\nextern uint64_t deltaTimestamp;\nextern uint64_t firstCpuStatTimestamp;\nextern int pid;\nextern vector<pair<uint64_t, CpuStat>> mCpuStats;\nextern vector<CpuConfig> mCpuConfigs;\n\nint runCmd(const string& cmd, std::string& outOutput, bool waitForCompletion = true);\n\nstruct AdbResults\n{\n    bool success = true;\n    vector<string> SurfaceFlinger_latency;\n    vector<string> dumpsys_gfxinfo;\n    vector<string> EPOCHREALTIME;\n    vector<string> proc_stat;\n    vector<string> proc_pid_stat;\n    vector<string> dumpsys_meminfo;\n    vector<string> scaling_cur_freq;\n    TemperatureStat temperature;\n};\n\nstruct TickFunction\n{\n    string actor;\n    string status;\n    string tick_group;\n\n    string type;\n    string component;\n    string level;\n    //vector<string> prerequesities;\n};\n\nstruct PerfDoctorApp : public App\n{\n    DataStorage storage;\n    ImPlotContext* implotCtx = nullptr;\n\n    ConcurrentCircularBuffer<AdbResults> mAdbResults{ 2 };\n    ConcurrentCircularBuffer<string> mAsyncCommands{ 2 };\n    unique_ptr<thread> mAdbThread;\n    bool mIsRunning = true;\n    bool mAutoStart = false;\n\n    FILE* fp_idb;\n    vector<string> executeIdb(string cmd, bool async = false, bool oneDeviceOnly = true);\n\n    vector<string> executeAdb(string cmd, bool oneDeviceOnly = true);\n    void executeUnrealCmd(const string& cmd);\n\n    int mAppId = -1;\n    vector<string> mSerialNames;\n    vector<string> mDeviceNames;\n    vector<bool> mIsIOSDevices;\n    vector<string> mAppNames;\n    string mSurfaceViewName = \"\";\n    string mSurfaceResolution = \"\";\n    string mPackageName = \"\";\n    bool mIsProfiling = false;\n    float mLastUpdateTime = 0;\n    vector<pair<uint64_t, uint64_t>> mFrameTimes;\n    vector<uint64_t> mTimestamps; //ms\n    vector<pair<uint64_t, float>> mFpsArray;\n    vector<pair<uint64_t, AppCpuStat>> mAppCpuStats;\n    vector<pair<uint64_t, CpuStat>> mChildCpuStats[8];\n    vector<pair<uint64_t, MemoryStat>> mMemoryStats;\n    vector<LabelPair> mLabelPairs;\n\n    TemperatureStatSlot mTemparatureStatSlot;\n    vector<pair<uint64_t, TemperatureStat>> mTemperatureStats;\n\n    vector<string> mUnrealCmds;\n\n    vector<TickFunction> mTickFunctions;\n    \n    uint64_t mLastSnapshotTs = 0;\n    uint64_t mLastSnapshotIdx = 0;\n    DeviceStat mDeviceStat;\n\n    struct MetricSummary\n    {\n        float Min, Max, Avg;\n        void reset()\n        {\n            Min = 0;\n            Max = 0;\n            Avg = 0;\n        }\n\n        void update(float new_value, int count)\n        {\n            if (new_value > Max) Max = new_value;\n            if (new_value < Min) Min = new_value;\n            Avg = (Avg * count + new_value) / (count + 1);\n        }\n    };\n\n    MetricSummary mFpsSummary, mMemorySummary, mAppCpuSummary, mCpuTempSummary, mFrameTimeSummary;\n    int mDeviceId = -1;\n\n    bool refreshDeviceNames();\n\n    bool refreshDeviceDetails_ios();\n\n    bool refreshDeviceDetails();\n    \n    bool startProfiler_ios(const string& pacakgeName);\n\n    bool capturePerfetto();\n\n    bool captureSimpleperf();\n\n    bool screenshot();\n\n    void exportGpuTrace();\n\n    bool exportCsv();\n\n    void trimMemory(const char* level);\n\n    bool startProfiler(const string& pacakgeName);\n\n    void resetPerfData();\n\n    bool stopProfiler();\n\n    struct TripleTimestamp\n    {\n        string started_to_draw;\n        string vsync;\n        string frame_submitted;\n    };\n\n    bool updateProfiler(const AdbResults& results);\n\n    int getPid(const string& pacakgeName);\n\n    bool startApp_ios(const string& pacakgeName);\n\n    bool startApp(const string& pacakgeName);\n\n    bool stopApp_ios(const string& pacakgeName);\n\n    bool stopApp(const string& pacakgeName);\n\n    void updateMetricsData();\n\n    void drawLeftSidePanel();\n    void drawDeviceTab();\n    void drawPerfPanel();\n    void drawLabel();\n\n    void getUnrealLog(bool openLogFile = false);\n    void getMemReport();\n    void getDumpTicks();\n\n    void setup() override;\n};\n"
  },
  {
    "path": "vc2019/Resources.rc",
    "content": "#include \"../include/Resources.h\"\r\n\r\n1\tICON\t\"..\\\\resources\\\\cinder_app_icon.ico\"\r\n"
  },
  {
    "path": "vc2019/perf-doctor.sln",
    "content": "Microsoft Visual Studio Solution File, Format Version 12.00\r\n# Visual Studio Version 16\r\nVisualStudioVersion = 16.0.31727.386\r\nMinimumVisualStudioVersion = 10.0.40219.1\r\nProject(\"{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}\") = \"perf-doctor\", \"perf-doctor.vcxproj\", \"{840AA6B1-503F-4884-84F1-DB6A3BA0BD68}\"\r\nEndProject\r\nGlobal\r\n\tGlobalSection(SolutionConfigurationPlatforms) = preSolution\r\n\t\tDebug|x64 = Debug|x64\r\n\t\tRelease|x64 = Release|x64\r\n\tEndGlobalSection\r\n\tGlobalSection(ProjectConfigurationPlatforms) = postSolution\r\n\t\t{840AA6B1-503F-4884-84F1-DB6A3BA0BD68}.Debug|x64.ActiveCfg = Debug|x64\r\n\t\t{840AA6B1-503F-4884-84F1-DB6A3BA0BD68}.Debug|x64.Build.0 = Debug|x64\r\n\t\t{840AA6B1-503F-4884-84F1-DB6A3BA0BD68}.Release|x64.ActiveCfg = Release|x64\r\n\t\t{840AA6B1-503F-4884-84F1-DB6A3BA0BD68}.Release|x64.Build.0 = Release|x64\r\n\tEndGlobalSection\r\n\tGlobalSection(SolutionProperties) = preSolution\r\n\t\tHideSolutionNode = FALSE\r\n\tEndGlobalSection\r\n\tGlobalSection(ExtensibilityGlobals) = postSolution\r\n\t\tSolutionGuid = {3EFA8526-A2D0-4436-B657-8C965C105F62}\r\n\tEndGlobalSection\r\nEndGlobal\r\n"
  },
  {
    "path": "vc2019/perf-doctor.vcxproj",
    "content": "<Project DefaultTargets=\"Build\" ToolsVersion=\"14.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n  <ItemGroup Label=\"ProjectConfigurations\">\r\n    <ProjectConfiguration Include=\"Debug|x64\">\r\n      <Configuration>Debug</Configuration>\r\n      <Platform>x64</Platform>\r\n    </ProjectConfiguration>\r\n    <ProjectConfiguration Include=\"Release|x64\">\r\n      <Configuration>Release</Configuration>\r\n      <Platform>x64</Platform>\r\n    </ProjectConfiguration>\r\n  </ItemGroup>\r\n  <PropertyGroup Label=\"Globals\">\r\n    <ProjectGuid>{840AA6B1-503F-4884-84F1-DB6A3BA0BD68}</ProjectGuid>\r\n    <RootNamespace>perf-doctor</RootNamespace>\r\n    <Keyword>Win32Proj</Keyword>\r\n    <WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>\r\n    <ProjectName>perf-doctor</ProjectName>\r\n  </PropertyGroup>\r\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.Default.props\" />\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\" Label=\"Configuration\">\r\n    <ConfigurationType>Application</ConfigurationType>\r\n    <UseDebugLibraries>false</UseDebugLibraries>\r\n    <PlatformToolset>v143</PlatformToolset>\r\n    <CharacterSet>Unicode</CharacterSet>\r\n    <WholeProgramOptimization>false</WholeProgramOptimization>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\" Label=\"Configuration\">\r\n    <ConfigurationType>Application</ConfigurationType>\r\n    <UseDebugLibraries>true</UseDebugLibraries>\r\n    <PlatformToolset>v143</PlatformToolset>\r\n    <CharacterSet>Unicode</CharacterSet>\r\n  </PropertyGroup>\r\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.props\" />\r\n  <ImportGroup Label=\"ExtensionSettings\" />\r\n  <ImportGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\" Label=\"PropertySheets\">\r\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\r\n  </ImportGroup>\r\n  <ImportGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\" Label=\"PropertySheets\">\r\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\r\n  </ImportGroup>\r\n  <PropertyGroup Label=\"UserMacros\" />\r\n  <PropertyGroup>\r\n    <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>\r\n    <LinkIncremental Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\">true</LinkIncremental>\r\n    <LinkIncremental Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">false</LinkIncremental>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\">\r\n    <OutDir>$(SolutionDir)..\\Bin\\</OutDir>\r\n    <TargetName>$(ProjectName)-d</TargetName>\r\n  </PropertyGroup>\r\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">\r\n    <OutDir>$(SolutionDir)..\\Bin\\</OutDir>\r\n  </PropertyGroup>\r\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|x64'\">\r\n    <ClCompile>\r\n      <Optimization>Disabled</Optimization>\r\n      <AdditionalIncludeDirectories>..\\include;..\\..\\Cinder\\include;..\\3rdparty\\Cinder-VNM\\include;..\\3rdparty\\Cinder-VNM\\ui;..\\3rdparty\\Cinder-VNM\\ui\\implot;..\\3rdparty;..\\3rdparty\\Cinder-VNM\\ui\\imgui</AdditionalIncludeDirectories>\r\n      <PreprocessorDefinitions>WIN32;_WIN32_WINNT=0x0601;_WINDOWS;NOMINMAX;_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r\n      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>\r\n      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>\r\n      <PrecompiledHeader />\r\n      <WarningLevel>Level3</WarningLevel>\r\n      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>\r\n      <MultiProcessorCompilation>true</MultiProcessorCompilation>\r\n      <LanguageStandard>stdcpp17</LanguageStandard>\r\n    </ClCompile>\r\n    <ResourceCompile>\r\n      <AdditionalIncludeDirectories>\"..\\..\\Cinder\\include\";..\\include</AdditionalIncludeDirectories>\r\n    </ResourceCompile>\r\n    <Link>\r\n      <AdditionalDependencies>cinder.lib;OpenGL32.lib;%(AdditionalDependencies)</AdditionalDependencies>\r\n      <AdditionalLibraryDirectories>..\\3rdparty\\libmixdevice\\lib\\Win64;\"..\\..\\Cinder\\lib\\msw\\$(PlatformTarget)\";\"..\\..\\Cinder\\lib\\msw\\$(PlatformTarget)\\$(Configuration)\\$(PlatformToolset)\"</AdditionalLibraryDirectories>\r\n      <GenerateDebugInformation>true</GenerateDebugInformation>\r\n      <SubSystem>Windows</SubSystem>\r\n      <RandomizedBaseAddress>false</RandomizedBaseAddress>\r\n      <DataExecutionPrevention />\r\n      <IgnoreSpecificDefaultLibraries>LIBCMT;LIBCPMT</IgnoreSpecificDefaultLibraries>\r\n    </Link>\r\n  </ItemDefinitionGroup>\r\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|x64'\">\r\n    <ClCompile>\r\n      <AdditionalIncludeDirectories>..\\include;..\\..\\Cinder\\include;..\\3rdparty\\Cinder-VNM\\include;..\\3rdparty\\Cinder-VNM\\ui;..\\3rdparty\\Cinder-VNM\\ui\\implot;..\\3rdparty;..\\3rdparty\\Cinder-VNM\\ui\\imgui</AdditionalIncludeDirectories>\r\n      <PreprocessorDefinitions>WIN32;_WIN32_WINNT=0x0601;_WINDOWS;NOMINMAX;NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>\r\n      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>\r\n      <PrecompiledHeader />\r\n      <WarningLevel>Level3</WarningLevel>\r\n      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>\r\n      <MultiProcessorCompilation>true</MultiProcessorCompilation>\r\n      <LanguageStandard>stdcpp17</LanguageStandard>\r\n    </ClCompile>\r\n    <ProjectReference>\r\n      <LinkLibraryDependencies>true</LinkLibraryDependencies>\r\n    </ProjectReference>\r\n    <ResourceCompile>\r\n      <AdditionalIncludeDirectories>\"..\\..\\Cinder\\include\";..\\include</AdditionalIncludeDirectories>\r\n    </ResourceCompile>\r\n    <Link>\r\n      <AdditionalDependencies>cinder.lib;OpenGL32.lib;%(AdditionalDependencies)</AdditionalDependencies>\r\n      <AdditionalLibraryDirectories>..\\3rdparty\\libmixdevice\\lib\\Win64;\"..\\..\\Cinder\\lib\\msw\\$(PlatformTarget)\";\"..\\..\\Cinder\\lib\\msw\\$(PlatformTarget)\\$(Configuration)\\$(PlatformToolset)\"</AdditionalLibraryDirectories>\r\n      <GenerateDebugInformation>true</GenerateDebugInformation>\r\n      <GenerateMapFile>true</GenerateMapFile>\r\n      <SubSystem>Windows</SubSystem>\r\n      <OptimizeReferences>true</OptimizeReferences>\r\n      <EnableCOMDATFolding />\r\n      <RandomizedBaseAddress>false</RandomizedBaseAddress>\r\n      <DataExecutionPrevention />\r\n    </Link>\r\n  </ItemDefinitionGroup>\r\n  <ItemGroup>\r\n    <ResourceCompile Include=\"Resources.rc\" />\r\n  </ItemGroup>\r\n  <ItemGroup />\r\n  <ItemGroup />\r\n  <ItemGroup>\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\CinderImGui.h\" />\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\ui\\imgui\\imconfig.h\" />\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\ui\\imgui\\imgui.h\" />\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\ui\\imgui\\imgui_internal.h\" />\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\ui\\imgui\\imstb_rectpack.h\" />\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\ui\\imgui\\imstb_textedit.h\" />\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\ui\\imgui\\imstb_truetype.h\" />\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\ui\\implot\\implot.h\" />\r\n    <ClInclude Include=\"..\\include\\Resources.h\" />\r\n    <ClInclude Include=\"..\\include\\item.def\" />\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\AnsiToUtf.h\" />\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\AssetManager.h\" />\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\CaptureHelper.h\" />\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\CinderGuizmo.h\" />\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\CinderRemoteImgui.h\" />\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\CubemapRenderer.h\" />\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\DearLogger.h\" />\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\FontHelper.h\" />\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\GLHelper.h\" />\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\GlslParamsBuilder.h\" />\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\GlslParamsBuilderImgui.h\" />\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\LimitSingleInstance.h\" />\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\MiniConfig.h\" />\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\MiniConfigImgui.h\" />\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\MotionHelper.h\" />\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\NvOptimusEnablement.h\" />\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\OscHelper.h\" />\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\SharedMemory.h\" />\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\StateMachine.h\" />\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\TextureHelper.h\" />\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\TuioHelper.h\" />\r\n    <ClInclude Include=\"..\\src\\LightSpeedApp.h\" />\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <ClCompile Include=\"..\\3rdparty\\Cinder-VNM\\ui\\CinderImGui.cpp\" />\r\n    <ClCompile Include=\"..\\3rdparty\\Cinder-VNM\\ui\\imgui\\imgui.cpp\" />\r\n    <ClCompile Include=\"..\\3rdparty\\Cinder-VNM\\ui\\imgui\\imgui_demo.cpp\" />\r\n    <ClCompile Include=\"..\\3rdparty\\Cinder-VNM\\ui\\imgui\\imgui_draw.cpp\" />\r\n    <ClCompile Include=\"..\\3rdparty\\Cinder-VNM\\ui\\imgui\\imgui_tables.cpp\" />\r\n    <ClCompile Include=\"..\\3rdparty\\Cinder-VNM\\ui\\imgui\\imgui_widgets.cpp\" />\r\n    <ClCompile Include=\"..\\3rdparty\\Cinder-VNM\\ui\\implot\\implot.cpp\" />\r\n    <ClCompile Include=\"..\\3rdparty\\Cinder-VNM\\ui\\implot\\implot_demo.cpp\" />\r\n    <ClCompile Include=\"..\\3rdparty\\Cinder-VNM\\ui\\implot\\implot_items.cpp\" />\r\n    <ClCompile Include=\"..\\src\\LightSpeedApp.cpp\" />\r\n    <ClCompile Include=\"..\\3rdparty\\Cinder-VNM\\src\\AssetManager.cpp\" />\r\n    <ClCompile Include=\"..\\3rdparty\\Cinder-VNM\\src\\MiniConfig.cpp\" />\r\n    <ClCompile Include=\"..\\src\\LightSpeedApp.gui.cpp\" />\r\n  </ItemGroup>\r\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.targets\" />\r\n  <ImportGroup Label=\"ExtensionTargets\" />\r\n</Project>"
  },
  {
    "path": "vc2019/perf-doctor.vcxproj.filters",
    "content": "<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n  <ItemGroup>\r\n    <Filter Include=\"Source Files\">\r\n      <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>\r\n      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>\r\n    </Filter>\r\n    <Filter Include=\"Header Files\">\r\n      <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>\r\n      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>\r\n    </Filter>\r\n    <Filter Include=\"Resource Files\">\r\n      <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>\r\n      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav</Extensions>\r\n    </Filter>\r\n    <Filter Include=\"Blocks\">\r\n      <UniqueIdentifier>{761985B6-6762-49B5-B39B-4A5B655AA368}</UniqueIdentifier>\r\n    </Filter>\r\n    <Filter Include=\"Blocks\\vnm\">\r\n      <UniqueIdentifier>{E9AF86AD-70B4-46AF-8C7C-300D4E79EF73}</UniqueIdentifier>\r\n    </Filter>\r\n    <Filter Include=\"Blocks\\vnm\\src\">\r\n      <UniqueIdentifier>{7BA1BBBE-2DEB-447B-BA2B-027ED0D4DFEF}</UniqueIdentifier>\r\n    </Filter>\r\n    <Filter Include=\"Blocks\\vnm\\include\">\r\n      <UniqueIdentifier>{E38AAA2E-58AC-4109-A4C1-0E009B6C1521}</UniqueIdentifier>\r\n    </Filter>\r\n    <Filter Include=\"Blocks\\vnm\\ui\">\r\n      <UniqueIdentifier>{197d083d-5491-4fbf-b601-28c8a01f2cc8}</UniqueIdentifier>\r\n    </Filter>\r\n    <Filter Include=\"Blocks\\vnm\\imgui\">\r\n      <UniqueIdentifier>{3ce9f7bf-b552-495c-af2f-79e330785515}</UniqueIdentifier>\r\n    </Filter>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <ClCompile Include=\"..\\src\\LightSpeedApp.cpp\">\r\n      <Filter>Source Files</Filter>\r\n    </ClCompile>\r\n    <ClInclude Include=\"..\\include\\Resources.h\">\r\n      <Filter>Header Files</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\include\\item.def\">\r\n      <Filter>Header Files</Filter>\r\n    </ClInclude>\r\n    <ClCompile Include=\"..\\src\\LightSpeedApp.cpp\">\r\n      <Filter>Source Files</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\3rdparty\\Cinder-VNM\\src\\AssetManager.cpp\">\r\n      <Filter>Blocks\\vnm\\src</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\3rdparty\\Cinder-VNM\\src\\MiniConfig.cpp\">\r\n      <Filter>Blocks\\vnm\\src</Filter>\r\n    </ClCompile>\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\AnsiToUtf.h\">\r\n      <Filter>Blocks\\vnm\\include</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\AssetManager.h\">\r\n      <Filter>Blocks\\vnm\\include</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\CaptureHelper.h\">\r\n      <Filter>Blocks\\vnm\\include</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\CinderGuizmo.h\">\r\n      <Filter>Blocks\\vnm\\include</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\CinderRemoteImgui.h\">\r\n      <Filter>Blocks\\vnm\\include</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\CubemapRenderer.h\">\r\n      <Filter>Blocks\\vnm\\include</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\DearLogger.h\">\r\n      <Filter>Blocks\\vnm\\include</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\FontHelper.h\">\r\n      <Filter>Blocks\\vnm\\include</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\GLHelper.h\">\r\n      <Filter>Blocks\\vnm\\include</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\GlslParamsBuilder.h\">\r\n      <Filter>Blocks\\vnm\\include</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\GlslParamsBuilderImgui.h\">\r\n      <Filter>Blocks\\vnm\\include</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\LimitSingleInstance.h\">\r\n      <Filter>Blocks\\vnm\\include</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\MiniConfig.h\">\r\n      <Filter>Blocks\\vnm\\include</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\MiniConfigImgui.h\">\r\n      <Filter>Blocks\\vnm\\include</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\MotionHelper.h\">\r\n      <Filter>Blocks\\vnm\\include</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\NvOptimusEnablement.h\">\r\n      <Filter>Blocks\\vnm\\include</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\OscHelper.h\">\r\n      <Filter>Blocks\\vnm\\include</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\SharedMemory.h\">\r\n      <Filter>Blocks\\vnm\\include</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\StateMachine.h\">\r\n      <Filter>Blocks\\vnm\\include</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\TextureHelper.h\">\r\n      <Filter>Blocks\\vnm\\include</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\TuioHelper.h\">\r\n      <Filter>Blocks\\vnm\\include</Filter>\r\n    </ClInclude>\r\n    <ClCompile Include=\"..\\3rdparty\\Cinder-VNM\\ui\\implot\\implot.cpp\">\r\n      <Filter>Blocks\\vnm\\ui</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\3rdparty\\Cinder-VNM\\ui\\implot\\implot_demo.cpp\">\r\n      <Filter>Blocks\\vnm\\ui</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\3rdparty\\Cinder-VNM\\ui\\implot\\implot_items.cpp\">\r\n      <Filter>Blocks\\vnm\\ui</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\src\\LightSpeedApp.gui.cpp\">\r\n      <Filter>Source Files</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\3rdparty\\Cinder-VNM\\ui\\imgui\\imgui.cpp\">\r\n      <Filter>Blocks\\vnm\\imgui</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\3rdparty\\Cinder-VNM\\ui\\imgui\\imgui_demo.cpp\">\r\n      <Filter>Blocks\\vnm\\imgui</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\3rdparty\\Cinder-VNM\\ui\\imgui\\imgui_draw.cpp\">\r\n      <Filter>Blocks\\vnm\\imgui</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\3rdparty\\Cinder-VNM\\ui\\imgui\\imgui_tables.cpp\">\r\n      <Filter>Blocks\\vnm\\imgui</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\3rdparty\\Cinder-VNM\\ui\\imgui\\imgui_widgets.cpp\">\r\n      <Filter>Blocks\\vnm\\imgui</Filter>\r\n    </ClCompile>\r\n    <ClCompile Include=\"..\\3rdparty\\Cinder-VNM\\ui\\CinderImGui.cpp\">\r\n      <Filter>Blocks\\vnm\\ui</Filter>\r\n    </ClCompile>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <ClInclude Include=\"..\\include\\Resources.h\">\r\n      <Filter>Header Files</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\ui\\implot\\implot.h\">\r\n      <Filter>Blocks\\vnm\\ui</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\src\\LightSpeedApp.h\">\r\n      <Filter>Source Files</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\ui\\imgui\\imconfig.h\">\r\n      <Filter>Blocks\\vnm\\imgui</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\ui\\imgui\\imgui.h\">\r\n      <Filter>Blocks\\vnm\\imgui</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\ui\\imgui\\imgui_internal.h\">\r\n      <Filter>Blocks\\vnm\\imgui</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\ui\\imgui\\imstb_rectpack.h\">\r\n      <Filter>Blocks\\vnm\\imgui</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\ui\\imgui\\imstb_textedit.h\">\r\n      <Filter>Blocks\\vnm\\imgui</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\ui\\imgui\\imstb_truetype.h\">\r\n      <Filter>Blocks\\vnm\\imgui</Filter>\r\n    </ClInclude>\r\n    <ClInclude Include=\"..\\3rdparty\\Cinder-VNM\\include\\CinderImGui.h\">\r\n      <Filter>Blocks\\vnm\\include</Filter>\r\n    </ClInclude>\r\n  </ItemGroup>\r\n  <ItemGroup>\r\n    <ResourceCompile Include=\"Resources.rc\">\r\n      <Filter>Resource Files</Filter>\r\n    </ResourceCompile>\r\n  </ItemGroup>\r\n</Project>"
  },
  {
    "path": "vc2019/resource.h",
    "content": "//{{NO_DEPENDENCIES}}\r\n// Microsoft Visual C++ generated include file.\r\n// Used by Resources.rc\r\n//\r\n#define IDI_ICON1                       101\r\n\r\n// Next default values for new objects\r\n// \r\n#ifdef APSTUDIO_INVOKED\r\n#ifndef APSTUDIO_READONLY_SYMBOLS\r\n#define _APS_NEXT_RESOURCE_VALUE        102\r\n#define _APS_NEXT_COMMAND_VALUE         40001\r\n#define _APS_NEXT_CONTROL_VALUE         1000\r\n#define _APS_NEXT_SYMED_VALUE           101\r\n#endif\r\n#endif\r\n"
  }
]